@wormhole-foundation/wormhole-connect 3.0.1-beta.2-development → 3.0.1-beta.4-development

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 (322) hide show
  1. package/dist/assets/{add-CA46SOZ1.js → add-Xg1xhVFF.js} +1 -1
  2. package/dist/assets/{all-wallets-B1qnLkOo.js → all-wallets-BoxRqCuD.js} +1 -1
  3. package/dist/assets/{app-store-NTpCK9MF.js → app-store-DWw_7TVB.js} +1 -1
  4. package/dist/assets/{apple-DRVt4JWr.js → apple-C3S_oS38.js} +1 -1
  5. package/dist/assets/{aptos-DkSiRwPH.js → aptos-BuLH7jck.js} +3 -3
  6. package/dist/assets/{aptos-63ExGocu.js → aptos-gb8snog6.js} +1 -1
  7. package/dist/assets/{arrow-bottom-CPth9tFV.js → arrow-bottom-TxaXdcXE.js} +1 -1
  8. package/dist/assets/{arrow-bottom-circle-BWo9DWoB.js → arrow-bottom-circle-zT0TMjGz.js} +1 -1
  9. package/dist/assets/{arrow-left-P6RmBJWT.js → arrow-left-DEymMKEb.js} +1 -1
  10. package/dist/assets/{arrow-right-BHHiE7kD.js → arrow-right-CrQ93Gth.js} +1 -1
  11. package/dist/assets/{arrow-top-D5GRFsZm.js → arrow-top-DO6PV0os.js} +1 -1
  12. package/dist/assets/{bank-C2WLfHR8.js → bank-D6rx1mBK.js} +1 -1
  13. package/dist/assets/{basic-BCJkH5GS.js → basic-C5fzEsEe.js} +1 -1
  14. package/dist/assets/{blake2b-Bb1VZYtg.js → blake2b-B2b685Yu.js} +1 -1
  15. package/dist/assets/{browser-BPjT1bN5.js → browser-Co04W0I6.js} +1 -1
  16. package/dist/assets/{card-JaBku5Bf.js → card-B2Z4mK1Z.js} +1 -1
  17. package/dist/assets/{ccip-CTrUg8DF.js → ccip-By49zU3M.js} +1 -1
  18. package/dist/assets/{chain-DF9mIQM9.js → chain-Du7paeNG.js} +1 -1
  19. package/dist/assets/{checkmark-BQL5JCw2.js → checkmark-C8HU5fja.js} +1 -1
  20. package/dist/assets/{checkmark-bold-DP1vE2RN.js → checkmark-bold-DIs1ZMqP.js} +1 -1
  21. package/dist/assets/{chevron-bottom-BV0Au0hP.js → chevron-bottom-BFsapVx9.js} +1 -1
  22. package/dist/assets/{chevron-left-C4v6Iui8.js → chevron-left-Fkdkr5ZY.js} +1 -1
  23. package/dist/assets/{chevron-right-CbVMuuvx.js → chevron-right-BfpUZvuC.js} +1 -1
  24. package/dist/assets/{chevron-top-CuIo_USv.js → chevron-top-CgQu63-4.js} +1 -1
  25. package/dist/assets/{chrome-store-fbydRQd1.js → chrome-store-GIO26gYx.js} +1 -1
  26. package/dist/assets/{chunk-KJH4KKG6-B7DCZZVY.js → chunk-KJH4KKG6-Po5MChR6.js} +1 -1
  27. package/dist/assets/{clock-D62L3EFP.js → clock-BDzvQcXR.js} +1 -1
  28. package/dist/assets/{close-BLRqO6Zn.js → close-JWa5ANIE.js} +1 -1
  29. package/dist/assets/{coinPlaceholder-0tmFvYYj.js → coinPlaceholder-a0UGO8gJ.js} +1 -1
  30. package/dist/assets/{compass-Ba8-RKca.js → compass-CEQdAwHs.js} +1 -1
  31. package/dist/assets/{contract-bGGxC9_m.js → contract-BhySpM-Z.js} +1 -1
  32. package/dist/assets/{copy-CWqrh_sD.js → copy-S_d5_yPl.js} +1 -1
  33. package/dist/assets/{create-CbRd6EbF.js → create-gkOVonha.js} +1 -1
  34. package/dist/assets/{cursor-DFYzmUAe.js → cursor-BhEbcCXK.js} +1 -1
  35. package/dist/assets/{cursor-transparent-IY3fA7aT.js → cursor-transparent-BcLVDVWp.js} +1 -1
  36. package/dist/assets/{desktop-DLudyYW3.js → desktop-DqSryZUj.js} +1 -1
  37. package/dist/assets/{disconnect-gShcPNrf.js → disconnect-YOsS0M4y.js} +1 -1
  38. package/dist/assets/{discord-S8T3fJF7.js → discord-CqeqTfSo.js} +1 -1
  39. package/dist/assets/{etherscan-C-ODOYjC.js → etherscan-DlH7X_ye.js} +1 -1
  40. package/dist/assets/{evm-DwqzhXfk.js → evm-CWAxZ2a7.js} +3 -3
  41. package/dist/assets/{evm-D65l_VUA.js → evm-fcQsoqVd.js} +4 -4
  42. package/dist/assets/{exclamation-triangle-I4hrUAkj.js → exclamation-triangle-B7tI_-cI.js} +1 -1
  43. package/dist/assets/{extension-C2E94rju.js → extension-DyHQJuRO.js} +1 -1
  44. package/dist/assets/{external-link-BE25aYRx.js → external-link-ChiVtGCq.js} +1 -1
  45. package/dist/assets/{facebook-VHvsuzqv.js → facebook-BIe7nERx.js} +1 -1
  46. package/dist/assets/{farcaster-sG7oFC35.js → farcaster-BTyklWGz.js} +1 -1
  47. package/dist/assets/{filters-D9VcvmFo.js → filters-De_gO5iz.js} +1 -1
  48. package/dist/assets/{github-BLJyKdzw.js → github-DQfZjMbN.js} +1 -1
  49. package/dist/assets/{google-C4YbBNSv.js → google-Gguig8Cy.js} +1 -1
  50. package/dist/assets/{help-circle-CMmVaOnp.js → help-circle-DHeCCsr1.js} +1 -1
  51. package/dist/assets/{id-g_mC9xVi.js → id-DjntBhAt.js} +1 -1
  52. package/dist/assets/{image-nAeKstDS.js → image-2J0s_97c.js} +1 -1
  53. package/dist/assets/{index-CKPf-3Vo.js → index--d0JCrsI.js} +1 -1
  54. package/dist/assets/{index-C0-WLpMA.js → index-BE55BSK7.js} +1 -1
  55. package/dist/assets/{index-Cu0b-jgK.js → index-BJYqkXUw.js} +1 -1
  56. package/dist/assets/{index-C_YTupmk.js → index-BYTZG2bF.js} +1 -1
  57. package/dist/assets/{index-CVqQ68io.js → index-BedU_k3i.js} +1 -1
  58. package/dist/assets/{index-BTkoFKAW.js → index-BgLBca6k.js} +1 -1
  59. package/dist/assets/{index-DynC8vQ4.js → index-BjvqCh5g.js} +1 -1
  60. package/dist/assets/{index-BqLA4xTj.js → index-BpI-Jtyb.js} +3 -3
  61. package/dist/assets/{index-GmuqTVr0.js → index-Breet2G4.js} +1 -1
  62. package/dist/assets/{index-BUtdFAj3.js → index-Bx8vjRmV.js} +1 -1
  63. package/dist/assets/{index-DusYxt7C.js → index-CfdmPAak.js} +3 -3
  64. package/dist/assets/{index-DA4wR-ie.js → index-DB7g9m_R.js} +1 -1
  65. package/dist/assets/{index-DKdokzug.js → index-DMWfYwZZ.js} +1 -1
  66. package/dist/assets/{index-COZ2cSR6.js → index-DSTd1tRp.js} +1 -1
  67. package/dist/assets/{index-CVqXQiSE.js → index-DZ96gAj4.js} +1 -1
  68. package/dist/assets/{index-CYFq9U58.js → index-TYicGq2L.js} +1 -1
  69. package/dist/assets/index-Z3Xir6L3.js +1 -0
  70. package/dist/assets/{index-DC3x_AFd.js → index-kF0xEQ0E.js} +1 -1
  71. package/dist/assets/{index-CCOXtJ1P.js → index-zEIfo2_n.js} +1 -1
  72. package/dist/assets/index.es-3Tq6bjFW.js +47 -0
  73. package/dist/assets/index.es-CBqWEk7T.js +15 -0
  74. package/dist/assets/{info-P71aU507.js → info-D4MdYH3E.js} +1 -1
  75. package/dist/assets/{info-circle-D8ZhpY4M.js → info-circle-2o2Bq9RM.js} +1 -1
  76. package/dist/assets/{lightbulb-CWL8Hapk.js → lightbulb-G1HZSu_o.js} +1 -1
  77. package/dist/assets/{mail-BKdMRnR2.js → mail-CYPzgN-C.js} +1 -1
  78. package/dist/assets/{mobile-Bw0EoBkW.js → mobile-G3tO8xk-.js} +1 -1
  79. package/dist/assets/{more-BSKGQd1b.js → more-nk1W6LmK.js} +1 -1
  80. package/dist/assets/{network-placeholder-B1xqyidN.js → network-placeholder-DakjB3wH.js} +1 -1
  81. package/dist/assets/{nftPlaceholder-CuCsNvkN.js → nftPlaceholder-JMholGYC.js} +1 -1
  82. package/dist/assets/{off-BX6zoZuA.js → off-SNO-Bsmr.js} +1 -1
  83. package/dist/assets/{play-store-CCveEK_B.js → play-store-BpxDB0NB.js} +1 -1
  84. package/dist/assets/{plus-C02SGp4V.js → plus-oY5qI4Lq.js} +1 -1
  85. package/dist/assets/{provider-jsonrpc-DTnJKzTS.js → provider-jsonrpc-CG-x8-V6.js} +1 -1
  86. package/dist/assets/{qr-code-DGe_aS_i.js → qr-code-jee4rxaz.js} +1 -1
  87. package/dist/assets/{recycle-horizontal-DtRomJbx.js → recycle-horizontal-BEF6XBYh.js} +1 -1
  88. package/dist/assets/{refresh-DPABcpes.js → refresh-aEpBxujB.js} +1 -1
  89. package/dist/assets/{reown-logo-DG2ULLka.js → reown-logo-CEo-n5QW.js} +1 -1
  90. package/dist/assets/{search-EURxday_.js → search-CrfJGGMS.js} +1 -1
  91. package/dist/assets/{secp256k1-D-G9AbtW.js → secp256k1-CBh6eQLF.js} +1 -1
  92. package/dist/assets/{secp256k1-DfnLU_Rr.js → secp256k1-OI4v3wvK.js} +1 -1
  93. package/dist/assets/{send-t6aoH9GB.js → send-ChU6l1_w.js} +1 -1
  94. package/dist/assets/signer-BRan8q4C.js +2 -0
  95. package/dist/assets/solana-B3bc0p0T.js +2 -0
  96. package/dist/assets/{solana-C-diloCa.js → solana-CxgaSoPj.js} +9 -9
  97. package/dist/assets/solanaEmbed.esm-Mnq6o_qa.js +10 -0
  98. package/dist/assets/{sui-Pc10JTxL.js → sui-CXoaI0gx.js} +2 -2
  99. package/dist/assets/{sui-DXg2Lhyt.js → sui-DXdm7DBB.js} +4 -4
  100. package/dist/assets/{swapHorizontal-Cd2Bq-oX.js → swapHorizontal-De2aXFHG.js} +1 -1
  101. package/dist/assets/{swapHorizontalBold-CK6YXqcD.js → swapHorizontalBold-CtwNUoVl.js} +1 -1
  102. package/dist/assets/{swapHorizontalMedium-BCT4Hlrg.js → swapHorizontalMedium-BsH9NNRL.js} +1 -1
  103. package/dist/assets/{swapHorizontalRoundedBold-C-NDd7Fq.js → swapHorizontalRoundedBold-ClK2_MrS.js} +1 -1
  104. package/dist/assets/{swapVertical-BfKszPb9.js → swapVertical-BVWoUs-p.js} +1 -1
  105. package/dist/assets/{telegram-D5sYoBZp.js → telegram-BgYefK90.js} +1 -1
  106. package/dist/assets/{three-dots-qiTqAG0h.js → three-dots-D6JqA1P-.js} +1 -1
  107. package/dist/assets/{tokens-BjeNFBPV.js → tokens-BwBlXmY1.js} +12 -12
  108. package/dist/assets/{twitch-1VH6BaUA.js → twitch-DSLx5P08.js} +1 -1
  109. package/dist/assets/{twitterIcon-hIEIDwcz.js → twitterIcon-DIhMC7Ie.js} +1 -1
  110. package/dist/assets/{verify-DxvRt34f.js → verify-Dh3yUwPE.js} +1 -1
  111. package/dist/assets/{verify-filled-RtidYdgS.js → verify-filled-mA5B8sgV.js} +1 -1
  112. package/dist/assets/{w3m-modal-DI_ypCY0.js → w3m-modal-DpvEw1mA.js} +1 -1
  113. package/dist/assets/{wallet-Cb9kcAk9.js → wallet-Bz3DYndO.js} +1 -1
  114. package/dist/assets/{wallet-placeholder-pTFD8Qr_.js → wallet-placeholder-BYYYxJZ1.js} +1 -1
  115. package/dist/assets/{walletconnect-DvJIx5jD.js → walletconnect-NKbhveni.js} +1 -1
  116. package/dist/assets/{warning-circle-CRzNiBlj.js → warning-circle-Dh13B0js.js} +1 -1
  117. package/dist/assets/{x-Dk-mK5uZ.js → x-B2DeHGEp.js} +1 -1
  118. package/dist/main.js +75 -75
  119. package/dist/src/config/index.d.ts.map +1 -1
  120. package/dist/src/config/tokens.d.ts +2 -2
  121. package/dist/src/config/tokens.d.ts.map +1 -1
  122. package/dist/src/config/types.d.ts +2 -0
  123. package/dist/src/config/types.d.ts.map +1 -1
  124. package/dist/src/utils/inProgressTxCache.d.ts.map +1 -1
  125. package/lib/{add-DrLWWjDN.mjs → add-CChCYI2G.mjs} +1 -1
  126. package/lib/{add-DVGSYBJf.js → add-CDVX1evr.js} +1 -1
  127. package/lib/{all-wallets-CjzZMHCA.mjs → all-wallets-D2JZa1Jx.mjs} +1 -1
  128. package/lib/{all-wallets-DGVJQYa0.js → all-wallets-Wql6lmNE.js} +1 -1
  129. package/lib/{app-store-BABxSxrd.js → app-store-1dBCl4tM.js} +1 -1
  130. package/lib/{app-store-kpf503GR.mjs → app-store-CLDcpqR0.mjs} +1 -1
  131. package/lib/{apple-C962M6Ax.js → apple-BHKwlbOf.js} +1 -1
  132. package/lib/{apple-C0AtBJDu.mjs → apple-DIxTUQFy.mjs} +1 -1
  133. package/lib/{aptos-uWJCRLoQ.js → aptos-BL0wRMvV.js} +1 -1
  134. package/lib/{aptos-XxQj_uxF.mjs → aptos-TAzFliq5.mjs} +1 -1
  135. package/lib/{arrow-bottom-D0wK6uMJ.mjs → arrow-bottom-BI4NLoaY.mjs} +1 -1
  136. package/lib/{arrow-bottom-circle-iOl-NxXR.js → arrow-bottom-circle-CAq7o5Oy.js} +1 -1
  137. package/lib/{arrow-bottom-circle-D5QwftYY.mjs → arrow-bottom-circle-HmnccP7v.mjs} +1 -1
  138. package/lib/{arrow-bottom-CIZJcZfr.js → arrow-bottom-lsBwXKtD.js} +1 -1
  139. package/lib/{arrow-left-BL0dHjzy.mjs → arrow-left-7ur69wUu.mjs} +1 -1
  140. package/lib/{arrow-left-C-RAtnQ2.js → arrow-left-BsQ-5Ptc.js} +1 -1
  141. package/lib/{arrow-right-COiq03Wj.js → arrow-right-D992kYZk.js} +1 -1
  142. package/lib/{arrow-right-DaZMOW_1.mjs → arrow-right-lENdnq4k.mjs} +1 -1
  143. package/lib/{arrow-top-7Srj2XLP.js → arrow-top-BO-2RkYj.js} +1 -1
  144. package/lib/{arrow-top-QPVhK81o.mjs → arrow-top-mSzeb_YL.mjs} +1 -1
  145. package/lib/{bank-C5lNHVtL.mjs → bank-CoEWKxhi.mjs} +1 -1
  146. package/lib/{bank-Bp2l8LtZ.js → bank-Hw0j97F3.js} +1 -1
  147. package/lib/{basic-C5W71-rE.mjs → basic-BaSePtpQ.mjs} +2 -2
  148. package/lib/{basic-DQ6ISwhI.js → basic-C2cAlU_P.js} +1 -1
  149. package/lib/{browser-DV0hL_fK.js → browser-BlvoS4as.js} +1 -1
  150. package/lib/{browser-CJhUYmz6.mjs → browser-rF5Wrb7Q.mjs} +1 -1
  151. package/lib/{card-yZLq1X6c.js → card-BMnXbbhN.js} +1 -1
  152. package/lib/{card-DSeabGLV.mjs → card-D_WE8NXm.mjs} +1 -1
  153. package/lib/{ccip-BCsOYNZd.js → ccip--ZxEFQf_.js} +1 -1
  154. package/lib/{ccip-CFqlillN.mjs → ccip-CqL9Anaf.mjs} +1 -1
  155. package/lib/{checkmark-BW4NeFlB.js → checkmark-CesSNUet.js} +1 -1
  156. package/lib/{checkmark-DhgNpDof.mjs → checkmark-OMVwQQ5U.mjs} +1 -1
  157. package/lib/{checkmark-bold-DnEFF9eL.js → checkmark-bold-BD-XO987.js} +1 -1
  158. package/lib/{checkmark-bold-CxJkyUOt.mjs → checkmark-bold-CD7QLi07.mjs} +1 -1
  159. package/lib/{chevron-bottom-Pi9qTSKk.mjs → chevron-bottom-BwVLFe30.mjs} +1 -1
  160. package/lib/{chevron-bottom-Tb5GYU7P.js → chevron-bottom-IMKe9YXA.js} +1 -1
  161. package/lib/{chevron-left-BRp6K_BQ.js → chevron-left-D9qVH2_2.js} +1 -1
  162. package/lib/{chevron-left-Cl35pkRv.mjs → chevron-left-Lf-ywM2h.mjs} +1 -1
  163. package/lib/{chevron-right-D1Ic6C28.js → chevron-right-WKiLOYc0.js} +1 -1
  164. package/lib/{chevron-right-pjH-xKxB.mjs → chevron-right-gRQ8_S61.mjs} +1 -1
  165. package/lib/{chevron-top-SdyRa8IE.js → chevron-top-Bxo7EgbN.js} +1 -1
  166. package/lib/{chevron-top-DSe-dX8z.mjs → chevron-top-DslLIugK.mjs} +1 -1
  167. package/lib/{chrome-store-0qgfQSAS.js → chrome-store-7358vPCZ.js} +1 -1
  168. package/lib/{chrome-store-ThoUGIhl.mjs → chrome-store-B7rWxuFe.mjs} +1 -1
  169. package/lib/{clock-B0sBEXQ5.mjs → clock-BGtDjqYb.mjs} +1 -1
  170. package/lib/{clock-2HqPHolX.js → clock-Ry96ruDh.js} +1 -1
  171. package/lib/{close-Bznv5frT.mjs → close-Bj7xcq2I.mjs} +1 -1
  172. package/lib/{close-BJQf5USo.js → close-C6sBVa0R.js} +1 -1
  173. package/lib/{coinPlaceholder-CvvSiYI-.js → coinPlaceholder-9HCA6YJ_.js} +1 -1
  174. package/lib/{coinPlaceholder-1gZoTAqN.mjs → coinPlaceholder-CUWHPX6Q.mjs} +1 -1
  175. package/lib/{compass-BE99mJOV.mjs → compass-B6RLv5bP.mjs} +1 -1
  176. package/lib/{compass-BBMA-82e.js → compass-CccZJ5Hi.js} +1 -1
  177. package/lib/{constants-Bp_337ur.mjs → constants-I50X20ow.mjs} +1 -1
  178. package/lib/{constants-BDS32jve.js → constants-o93Ip-ZI.js} +1 -1
  179. package/lib/{copy-B_JboG8P.js → copy-CQDBtuRc.js} +1 -1
  180. package/lib/{copy-Cwolsgnk.mjs → copy-ucy3iRHw.mjs} +1 -1
  181. package/lib/{cursor-C2jyr1Tt.js → cursor-CSvFFh4Q.js} +1 -1
  182. package/lib/{cursor-0EyS6nH4.mjs → cursor-CzBbQiJe.mjs} +1 -1
  183. package/lib/{cursor-transparent-ZUI7NwAo.mjs → cursor-transparent-BVPzLo6n.mjs} +1 -1
  184. package/lib/{cursor-transparent-BaVE19A2.js → cursor-transparent-OMlVLjL8.js} +1 -1
  185. package/lib/{desktop-Dmz61Quh.js → desktop-CPDPdHBV.js} +1 -1
  186. package/lib/{desktop-B1U1mc6q.mjs → desktop-shQ2mQoL.mjs} +1 -1
  187. package/lib/{disconnect-8HUMogEY.mjs → disconnect-BKVkn-S7.mjs} +1 -1
  188. package/lib/{disconnect-Bn_0Td6c.js → disconnect-DGSddjKW.js} +1 -1
  189. package/lib/{discord-4tBuPwio.js → discord-748YGKmQ.js} +1 -1
  190. package/lib/{discord-DNMu-4pj.mjs → discord-CU-xUnfX.mjs} +1 -1
  191. package/lib/{etherscan-DTafkFM9.mjs → etherscan-6_ieSOxb.mjs} +1 -1
  192. package/lib/{etherscan-CdfpxSFw.js → etherscan-Ccpuewtf.js} +1 -1
  193. package/lib/{evm-B5SS0axR.mjs → evm-DfM6aIHd.mjs} +3 -3
  194. package/lib/{evm-BZKMUp6E.js → evm-DoAUqshZ.js} +3 -3
  195. package/lib/{exclamation-triangle-BLb5RCv9.mjs → exclamation-triangle-B1yodgmL.mjs} +1 -1
  196. package/lib/{exclamation-triangle-W8wr4W3B.js → exclamation-triangle-BcTwNgcS.js} +1 -1
  197. package/lib/{extension-B3rp6j3f.js → extension-BwMlRm6l.js} +1 -1
  198. package/lib/{extension-DqXaH5V_.mjs → extension-CpR0U7JU.mjs} +1 -1
  199. package/lib/{external-link-DWSOPcgR.js → external-link-CSvt1sJd.js} +1 -1
  200. package/lib/{external-link-DupOMQca.mjs → external-link-D5LlQVjF.mjs} +1 -1
  201. package/lib/{facebook-C25qgXgI.mjs → facebook-Ch2fWEDP.mjs} +1 -1
  202. package/lib/{facebook-gaoSLwmV.js → facebook-DKN-SwlC.js} +1 -1
  203. package/lib/{farcaster-BKQVbYft.mjs → farcaster-CuhYu7xL.mjs} +1 -1
  204. package/lib/{farcaster-Dw_KFzSe.js → farcaster-Eo6frWYn.js} +1 -1
  205. package/lib/{filters-BSv2GVWx.js → filters-D8RfIYLp.js} +1 -1
  206. package/lib/{filters-BRj-u8fO.mjs → filters-hN9hAmqt.mjs} +1 -1
  207. package/lib/{github-CVSqx81G.js → github-Bj11sR8O.js} +1 -1
  208. package/lib/{github-B8zYv5B1.mjs → github-CBnfKu_p.mjs} +1 -1
  209. package/lib/{google-CJy4jhj7.mjs → google-DkNw7izD.mjs} +1 -1
  210. package/lib/{google-DWyFM_-_.js → google-ocyOtxA8.js} +1 -1
  211. package/lib/{help-circle-D2kyGnMD.mjs → help-circle-BYF3SQ07.mjs} +1 -1
  212. package/lib/{help-circle-BihX0QHp.js → help-circle-DIUT7rfs.js} +1 -1
  213. package/lib/hosted.js +1 -1
  214. package/lib/hosted.mjs +1 -1
  215. package/lib/{id-BvDoX2i7.mjs → id-C70TM1mY.mjs} +1 -1
  216. package/lib/{id-ZWI-bwNJ.js → id-CFPGVN7x.js} +1 -1
  217. package/lib/{image-CNQTgOF8.js → image-Csb5_nLh.js} +1 -1
  218. package/lib/{image-BeWwKKKj.mjs → image-N27_sf6L.mjs} +1 -1
  219. package/lib/{index-BXBTU3I5.mjs → index-BJokM0dj.mjs} +78 -78
  220. package/lib/{index-Dpl42t-y.mjs → index-BQI4s97M.mjs} +19199 -19189
  221. package/lib/index-CtU_yCFR.js +304 -0
  222. package/lib/{index-D2yjOpeA.js → index-DPTquT8S.js} +2 -2
  223. package/lib/{index.es-BvsB6Z8q.js → index.es-B-_H_cmu.js} +1 -1
  224. package/lib/{index.es-C4KG3MSj.mjs → index.es-DJiOqF7x.mjs} +1 -1
  225. package/lib/{index.es-C2112Y2b.js → index.es-WjSz4osV.js} +1 -1
  226. package/lib/{index.es-Cy_oFTNH.mjs → index.es-s7TRhhGL.mjs} +3 -3
  227. package/lib/index.js +1 -1
  228. package/lib/index.mjs +1 -1
  229. package/lib/{info-CjKZyXW_.mjs → info-AQVHCGaq.mjs} +1 -1
  230. package/lib/{info-C73QOiqc.js → info-CxmLliqa.js} +1 -1
  231. package/lib/{info-circle-DE-EmffO.js → info-circle-D2JXCfNS.js} +1 -1
  232. package/lib/{info-circle-CEpS6rzX.mjs → info-circle-y2TMBRYb.mjs} +1 -1
  233. package/lib/{lightbulb-BVq3C-EG.mjs → lightbulb-BKSrtaqH.mjs} +1 -1
  234. package/lib/{lightbulb-Dm6Hsfd3.js → lightbulb-BbhqbK_X.js} +1 -1
  235. package/lib/{mail-CqUQETIH.mjs → mail-BBgJ1r1U.mjs} +1 -1
  236. package/lib/{mail-GRon9tbg.js → mail-CoY6lTNd.js} +1 -1
  237. package/lib/{mobile-BmGmHmVh.js → mobile-Bctu3ihf.js} +1 -1
  238. package/lib/{mobile-CEbEFp0X.mjs → mobile-DNfcwXIc.mjs} +1 -1
  239. package/lib/{more-CnS-NcGa.js → more--vfXH0mk.js} +1 -1
  240. package/lib/{more-Cs0cmKvd.mjs → more-CH7etA30.mjs} +1 -1
  241. package/lib/{network-placeholder-CjPyqfGa.js → network-placeholder-6HdYNIFM.js} +1 -1
  242. package/lib/{network-placeholder-DYuB36S0.mjs → network-placeholder-ChGkSHiE.mjs} +1 -1
  243. package/lib/{nftPlaceholder-COJmgjQo.mjs → nftPlaceholder-BEC17VTi.mjs} +1 -1
  244. package/lib/{nftPlaceholder-CoY2NOAz.js → nftPlaceholder-CFV32cdU.js} +1 -1
  245. package/lib/{off-CZo3LYgL.mjs → off-ClkoZEBq.mjs} +1 -1
  246. package/lib/{off-B-WmBPpa.js → off-lYX-5yS0.js} +1 -1
  247. package/lib/{play-store-Chciiwp3.js → play-store-BG47IOEu.js} +1 -1
  248. package/lib/{play-store-Edmxg3AX.mjs → play-store-CkhMEAU7.mjs} +1 -1
  249. package/lib/{plus-D2jFkgs1.mjs → plus-BtTwbs2C.mjs} +1 -1
  250. package/lib/{plus-C93OSdaz.js → plus-DrlcozYb.js} +1 -1
  251. package/lib/{qr-code-c2tFySK0.mjs → qr-code-DYJJwRSj.mjs} +1 -1
  252. package/lib/{qr-code-y78Lk8wE.js → qr-code-v9_pM0Zk.js} +1 -1
  253. package/lib/{recycle-horizontal-PXk9BX3j.js → recycle-horizontal-BvzP-O-1.js} +1 -1
  254. package/lib/{recycle-horizontal-CWycpdDF.mjs → recycle-horizontal-EBM2ypKZ.mjs} +1 -1
  255. package/lib/{refresh-C77_db2T.mjs → refresh-BAhwdZGm.mjs} +1 -1
  256. package/lib/{refresh-mky0B17c.js → refresh-TpfixFZn.js} +1 -1
  257. package/lib/{reown-logo-0RkEf9EI.mjs → reown-logo-B0Su0Ter.mjs} +1 -1
  258. package/lib/{reown-logo-DceXhK36.js → reown-logo-DU1oKeQq.js} +1 -1
  259. package/lib/{search-BrMSW1-8.mjs → search-BPQ2hivJ.mjs} +1 -1
  260. package/lib/{search-CWru3218.js → search-Dmv7gbQ1.js} +1 -1
  261. package/lib/{secp256k1-C4P0dmMC.mjs → secp256k1-BZs3Z9mj.mjs} +1 -1
  262. package/lib/{secp256k1-BU-UfBCB.js → secp256k1-BjuZX5cP.js} +1 -1
  263. package/lib/{secp256k1-Cks0bicH.js → secp256k1-CLJ0hFH7.js} +1 -1
  264. package/lib/{secp256k1-CI3_SM8F.mjs → secp256k1-CtFVBB1y.mjs} +1 -1
  265. package/lib/{send-CRyBVD1k.js → send-BD36uDqC.js} +1 -1
  266. package/lib/{send-DFkvxnIh.mjs → send-BtmBm7An.mjs} +1 -1
  267. package/lib/{solana-BVnMWq13.js → solana-BCCsr1Cx.js} +4 -4
  268. package/lib/{solana-L02hbBDE.mjs → solana-CJwReM-9.mjs} +6 -6
  269. package/lib/{solanaEmbed.esm-DSwNdsgx.mjs → solanaEmbed.esm-DUeK0Aox.mjs} +1 -1
  270. package/lib/{solanaEmbed.esm-BG5cgKub.js → solanaEmbed.esm-TlHPGYbs.js} +1 -1
  271. package/lib/src/config/index.d.ts.map +1 -1
  272. package/lib/src/config/tokens.d.ts +2 -2
  273. package/lib/src/config/tokens.d.ts.map +1 -1
  274. package/lib/src/config/types.d.ts +2 -0
  275. package/lib/src/config/types.d.ts.map +1 -1
  276. package/lib/src/utils/inProgressTxCache.d.ts.map +1 -1
  277. package/lib/{sui-Dv1p0XoG.js → sui-CfpeqXfu.js} +1 -1
  278. package/lib/{sui-CN1tZAOs.mjs → sui-DCDjGAGw.mjs} +1 -1
  279. package/lib/{swapHorizontal-Bo_-2U6j.mjs → swapHorizontal-BrAMZxpk.mjs} +1 -1
  280. package/lib/{swapHorizontal-BiCkAPre.js → swapHorizontal-zZA0Pi1S.js} +1 -1
  281. package/lib/{swapHorizontalBold-BPL2XaSi.mjs → swapHorizontalBold-BcMCprxV.mjs} +1 -1
  282. package/lib/{swapHorizontalBold-CWHbSIEu.js → swapHorizontalBold-DiN_RSP7.js} +1 -1
  283. package/lib/{swapHorizontalMedium-CTsDFfzR.mjs → swapHorizontalMedium-BJ2Ste5L.mjs} +1 -1
  284. package/lib/{swapHorizontalMedium-D_2Z2Hfq.js → swapHorizontalMedium-CoOVPZkR.js} +1 -1
  285. package/lib/{swapHorizontalRoundedBold-8b5z2YJ_.mjs → swapHorizontalRoundedBold-Cjf3Fskk.mjs} +1 -1
  286. package/lib/{swapHorizontalRoundedBold-CDKFFagj.js → swapHorizontalRoundedBold-DxwvY3dz.js} +1 -1
  287. package/lib/{swapVertical-CNBatiM6.js → swapVertical-Bq0Lj7Jp.js} +1 -1
  288. package/lib/{swapVertical-UTCgpnIJ.mjs → swapVertical-p6z9y9EP.mjs} +1 -1
  289. package/lib/{telegram-lTj0r5My.js → telegram-dLc4G7r4.js} +1 -1
  290. package/lib/{telegram-CVvlgH_Z.mjs → telegram-ejEcBbcF.mjs} +1 -1
  291. package/lib/{three-dots-KK4NyvR7.mjs → three-dots-DaVRiDOk.mjs} +1 -1
  292. package/lib/{three-dots-DQLgK82o.js → three-dots-d_UVr-9U.js} +1 -1
  293. package/lib/{tokens-B2pmB4Ph.js → tokens-BWrHpkNL.js} +1 -1
  294. package/lib/{tokens-BQHmitaT.mjs → tokens-BnimC1zF.mjs} +1 -1
  295. package/lib/{twitch-CO4nmS5o.mjs → twitch-BHisrkgo.mjs} +1 -1
  296. package/lib/{twitch-wV3Yc6kA.js → twitch-C8keHWlC.js} +1 -1
  297. package/lib/{twitterIcon-pCNPPny7.js → twitterIcon-BQcavToi.js} +1 -1
  298. package/lib/{twitterIcon-BU99IvD2.mjs → twitterIcon-D3iLXIw6.mjs} +1 -1
  299. package/lib/{verify-Ci9XMhb8.mjs → verify-BWBTB_1a.mjs} +1 -1
  300. package/lib/{verify-B21LHiy7.js → verify-CXgbYH0A.js} +1 -1
  301. package/lib/{verify-filled-LUtqUhbS.mjs → verify-filled-D-Ce24N1.mjs} +1 -1
  302. package/lib/{verify-filled-DCMcHuAt.js → verify-filled-EtgRJyXw.js} +1 -1
  303. package/lib/{w3m-modal-DJRTg4Aa.js → w3m-modal-BRD-3_ln.js} +1 -1
  304. package/lib/{w3m-modal-BJkuxcj8.mjs → w3m-modal-jJj4CHrQ.mjs} +2 -2
  305. package/lib/{wallet-BqBebKQF.js → wallet-D5GlthNd.js} +1 -1
  306. package/lib/{wallet-USpq1vKL.mjs → wallet-D9nn7VuJ.mjs} +1 -1
  307. package/lib/{wallet-placeholder-CL_evZUb.mjs → wallet-placeholder-Bdm8Ey5Z.mjs} +1 -1
  308. package/lib/{wallet-placeholder-Cf1u-2wB.js → wallet-placeholder-CHDzAL0k.js} +1 -1
  309. package/lib/{walletconnect-Da6ZdP8w.js → walletconnect-CAKGYqr_.js} +1 -1
  310. package/lib/{walletconnect-3g5k3agX.mjs → walletconnect-DbTFPVUf.mjs} +1 -1
  311. package/lib/{warning-circle-B3ivLfCN.mjs → warning-circle-BNb3asEb.mjs} +1 -1
  312. package/lib/{warning-circle-CvTdOy7u.js → warning-circle-CQo0cKjW.js} +1 -1
  313. package/lib/{x-BOwtJrlH.mjs → x-35IydjAH.mjs} +1 -1
  314. package/lib/{x-DQCRmr2P.js → x-BeRG8E5j.js} +1 -1
  315. package/package.json +1 -1
  316. package/dist/assets/index-BZFyhaji.js +0 -1
  317. package/dist/assets/index.es-CWMLsIMc.js +0 -47
  318. package/dist/assets/index.es-g5_0R3zE.js +0 -15
  319. package/dist/assets/signer-7-tpWjBV.js +0 -2
  320. package/dist/assets/solana-C6mHMmQi.js +0 -2
  321. package/dist/assets/solanaEmbed.esm-DhAz8SOB.js +0 -10
  322. package/lib/index-DwMMfwYI.js +0 -304
@@ -1,25 +1,25 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/solanaEmbed.esm-DhAz8SOB.js","main.js","main.css","assets/index-VWaDGczM.js","assets/secp256k1-D-G9AbtW.js","assets/util-C_16CLeU.js","assets/wallets-B2cUxj0w.js","assets/signer-7-tpWjBV.js","assets/chain-DF9mIQM9.js","assets/index-Czf_KRcW.js","assets/index.es-g5_0R3zE.js","assets/secp256k1-DfnLU_Rr.js","assets/basic-BCJkH5GS.js","assets/index-DusYxt7C.js","assets/browser-CeceZ__e.js","assets/w3m-modal-DI_ypCY0.js"])))=>i.map(i=>d[i]);
2
- var nv=Object.defineProperty;var ov=(s,e,t)=>e in s?nv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Nt=(s,e,t)=>ov(s,typeof e!="symbol"?e+"":e,t);import{I as av,P as ei,f as _,_ as Vo,d as kt,J as cv,L as Wn,V as dh,O as ph,W as lv,Q as id,y as rd,B as Pa,R as hv,H as gh,U as nd,G as Mi,X as uv,Y as dv,C as vm,Z as pv}from"../main.js";import{a as gv}from"./util-C_16CLeU.js";import{g as fv}from"./wallets-B2cUxj0w.js";import{i as fh,d as mv,a as wv}from"./signer-7-tpWjBV.js";import{a3 as E,a4 as Im,a5 as Wi,a6 as zc,a7 as Em,f as yv,a1 as od,a2 as hl,t as ad}from"./index-Czf_KRcW.js";import{I as bs,d as Di,s as wi,a as Sr,c as Am,b as Nm,k as _m,e as Cm,f as Sm,g as bc,h as Ge,t as Ae,C as $m,i as Pm,j as jn,l as Mn,r as bv,m as Gt,n as gs,o as st,p as $r,q as cd,u as vv,v as Iv,w as ca,x as Ev,y as yi,A as Au,E as Ne,z as qe,D as Vn,B as Kn,F as Vi,P as vc,Q as Tm,G as Mm,H as Av,J as vt,K as qt,L as tt}from"./index.es-g5_0R3zE.js";class jt extends Error{constructor(e,t){super(e),this.error=t}}class Ki extends jt{constructor(){super(...arguments),this.name="WalletNotReadyError"}}class Nv extends jt{constructor(){super(...arguments),this.name="WalletLoadError"}}class Cn extends jt{constructor(){super(...arguments),this.name="WalletConfigError"}}class Fc extends jt{constructor(){super(...arguments),this.name="WalletConnectionError"}}class Om extends jt{constructor(){super(...arguments),this.name="WalletDisconnectedError"}}class la extends jt{constructor(){super(...arguments),this.name="WalletDisconnectionError"}}class Ps extends jt{constructor(){super(...arguments),this.name="WalletAccountError"}}class Pr extends jt{constructor(){super(...arguments),this.name="WalletPublicKeyError"}}class Fe extends jt{constructor(){super(...arguments),this.name="WalletNotConnectedError"}}class ur extends jt{constructor(){super(...arguments),this.name="WalletSendTransactionError"}}class et extends jt{constructor(){super(...arguments),this.name="WalletSignTransactionError"}}class ha extends jt{constructor(){super(...arguments),this.name="WalletSignMessageError"}}class ld extends jt{constructor(){super(...arguments),this.name="WalletSignInError"}}class _v extends jt{constructor(){super(...arguments),this.name="WalletWindowClosedError"}}var ne;(function(s){s.Installed="Installed",s.NotDetected="NotDetected",s.Loadable="Loadable",s.Unsupported="Unsupported"})(ne||(ne={}));class xm extends av{get connected(){return!!this.publicKey}async autoConnect(){await this.connect()}async prepareTransaction(e,t,i={}){const r=this.publicKey;if(!r)throw new Fe;return e.feePayer=e.feePayer||r,e.recentBlockhash=e.recentBlockhash||(await t.getLatestBlockhash({commitment:i.preflightCommitment,minContextSlot:i.minContextSlot})).blockhash,e}}function ua(s){if(typeof window>"u"||typeof document>"u")return;const e=[];function t(){if(s())for(const n of e)n()}const i=setInterval(t,1e3);e.push(()=>clearInterval(i)),document.readyState==="loading"&&(document.addEventListener("DOMContentLoaded",t,{once:!0}),e.push(()=>document.removeEventListener("DOMContentLoaded",t))),document.readyState!=="complete"&&(window.addEventListener("load",t,{once:!0}),e.push(()=>window.removeEventListener("load",t))),t()}function pi(s){return"version"in s}class Nu extends xm{async sendTransaction(e,t,i={}){let r=!0;try{if(pi(e)){if(!this.supportedTransactionVersions)throw new ur("Sending versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(e.version))throw new ur(`Sending transaction version ${e.version} isn't supported by this wallet`);try{e=await this.signTransaction(e);const n=e.serialize();return await t.sendRawTransaction(n,i)}catch(n){throw n instanceof et?(r=!1,n):new ur(n==null?void 0:n.message,n)}}else try{const{signers:n,...o}=i;e=await this.prepareTransaction(e,t,o),n!=null&&n.length&&e.partialSign(...n),e=await this.signTransaction(e);const a=e.serialize();return await t.sendRawTransaction(a,o)}catch(n){throw n instanceof et?(r=!1,n):new ur(n==null?void 0:n.message,n)}}catch(n){throw r&&this.emit("error",n),n}}async signAllTransactions(e){for(const i of e)if(pi(i)){if(!this.supportedTransactionVersions)throw new et("Signing versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(i.version))throw new et(`Signing transaction version ${i.version} isn't supported by this wallet`)}const t=[];for(const i of e)t.push(await this.signTransaction(i));return t}}class da extends Nu{}const Oi="solana:signAndSendTransaction",ul="solana:signIn",io="solana:signMessage",Mt="solana:signTransaction",Dm="standard:connect",hd="standard:disconnect",km="standard:events";function Cv(s){return Dm in s.features&&km in s.features&&(Oi in s.features||Mt in s.features)}var Ko;(function(s){s.Mainnet="mainnet-beta",s.Testnet="testnet",s.Devnet="devnet"})(Ko||(Ko={}));const Sv="Bitget";class $v extends da{constructor(e={}){super(),this.name=Sv,this.url="https://web3.bitget.com",this.icon="data:image/svg+xml;base64,PHN2ZyBmaWxsPSJub25lIiBoZWlnaHQ9IjI1NiIgdmlld0JveD0iMCAwIDI1NiAyNTYiIHdpZHRoPSIyNTYiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxmaWx0ZXIgaWQ9ImEiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiIgZmlsdGVyVW5pdHM9InVzZXJTcGFjZU9uVXNlIiBoZWlnaHQ9IjQ1MS40MzEiIHdpZHRoPSI1NjkuNTU4IiB4PSItOTAuMjQxMSIgeT0iLTY5LjczNjkiPjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+PGZlQmxlbmQgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiBtb2RlPSJub3JtYWwiIHJlc3VsdD0ic2hhcGUiLz48ZmVHYXVzc2lhbkJsdXIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIgc3RkRGV2aWF0aW9uPSI0OS4yMzA4Ii8+PC9maWx0ZXI+PGZpbHRlciBpZD0iYiIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGhlaWdodD0iMzcxLjUwNyIgd2lkdGg9IjM1MS41OTYiIHg9Ii0xNjAuNTExIiB5PSItMTY1Ljk4NyI+PGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz48ZmVCbGVuZCBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIG1vZGU9Im5vcm1hbCIgcmVzdWx0PSJzaGFwZSIvPjxmZUdhdXNzaWFuQmx1ciByZXN1bHQ9ImVmZmVjdDFfZm9yZWdyb3VuZEJsdXJfMjAzNV8xMTA2IiBzdGREZXZpYXRpb249IjQ5LjIzMDgiLz48L2ZpbHRlcj48ZmlsdGVyIGlkPSJjIiBjb2xvci1pbnRlcnBvbGF0aW9uLWZpbHRlcnM9InNSR0IiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgaGVpZ2h0PSI0MjQuNDUyIiB3aWR0aD0iNDQ0Ljg1MSIgeD0iLTI0MS4wNzgiIHk9IjY3LjY0MiI+PGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz48ZmVCbGVuZCBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIG1vZGU9Im5vcm1hbCIgcmVzdWx0PSJzaGFwZSIvPjxmZUdhdXNzaWFuQmx1ciByZXN1bHQ9ImVmZmVjdDFfZm9yZWdyb3VuZEJsdXJfMjAzNV8xMTA2IiBzdGREZXZpYXRpb249IjQ5LjIzMDgiLz48L2ZpbHRlcj48ZmlsdGVyIGlkPSJkIiBjb2xvci1pbnRlcnBvbGF0aW9uLWZpbHRlcnM9InNSR0IiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgaGVpZ2h0PSIzODUuMTA1IiB3aWR0aD0iNDMwLjE5MSIgeD0iLTIwLjM5NjgiIHk9Ii0yNDIuNzU4Ij48ZmVGbG9vZCBmbG9vZC1vcGFjaXR5PSIwIiByZXN1bHQ9IkJhY2tncm91bmRJbWFnZUZpeCIvPjxmZUJsZW5kIGluPSJTb3VyY2VHcmFwaGljIiBpbjI9IkJhY2tncm91bmRJbWFnZUZpeCIgbW9kZT0ibm9ybWFsIiByZXN1bHQ9InNoYXBlIi8+PGZlR2F1c3NpYW5CbHVyIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIvPjwvZmlsdGVyPjxjbGlwUGF0aCBpZD0iZSI+PHBhdGggZD0ibTAgMGgyNTZ2MjU2aC0yNTZ6Ii8+PC9jbGlwUGF0aD48ZyBjbGlwLXBhdGg9InVybCgjZSkiPjxwYXRoIGQ9Im0wIDBoMjU2djI1NmgtMjU2eiIgZmlsbD0iIzU0ZmZmNSIvPjxnIGZpbHRlcj0idXJsKCNhKSI+PHBhdGggZD0ibTEzLjQ4MDYgMTk4LjYwNWMtNDIuODA4MiAxMjAuNDM4IDE4Ni4xODA0IDg2LjQyMiAzMDYuMDI2NCA1NC4zNTkgMTIyLjY1OC00MC43MDUgMzcuODc5LTIyMC4xMzcxLTUwLjA5Mi0yMjQuMTA4Mi04Ny45NzItMy45NzExIDEwLjkwNyA4Mi45NjgyLTYzLjgyIDEwNy44MDAyLTc0LjcyNyAyNC44MzEtMTM4LjYwNDMtODguNTk3Ny0xOTIuMTE0NCA2MS45NDl6IiBmaWxsPSIjZmZmIi8+PC9nPjxnIGZpbHRlcj0idXJsKCNiKSI+PHBhdGggZD0ibTg1LjUxMTgtNDUuODIyNWMtMjIuNDU1Ni02MS4zNTM1LTEwMi40MzA3IDIxLjgyNzItMTM5LjYxMTMgNzEuMDg2OC0zNS40NjU3IDUzLjU4MzYgNTcuMTA4ODcgOTkuODg3NyA5My40MjAzIDc0Ljc3MjcgMzYuMzExNS0yNS4xMTQzLTMxLjU0NjMyLTMwLjAwMDctOS45NS02Mi42NTg1IDIxLjU5NjMtMzIuNjU3NzQgODQuMjEwMi02LjUwOSA1Ni4xNDEtODMuMjAxeiIgZmlsbD0iIzAwZmZmMCIgZmlsbC1vcGFjaXR5PSIuNjciLz48L2c+PGcgZmlsdGVyPSJ1cmwoI2MpIj48cGF0aCBkPSJtOTYuNDc5NiAyMjUuNDI0Yy0zMC42Mjk0LTEwMy4wNjEtMTYyLjU2MTQtNDguNzg3LTIyNC42OTg2LTguNzY3LTU5Ljc3MSA0Ny4zODUgODIuMTQ3OSAxODMuNjkxIDE0MS4wOTE1IDE3Ni43MTkgNTguOTQzNi02Ljk3My00Ny4yODQzLTY2LjMxMS0xMC44ODU0OC05NS4yMDYgMzYuMzk4NzgtMjguODk0IDEzMi43Nzg5OCA1Ni4wNzkgOTQuNDkyNTgtNzIuNzQ2eiIgZmlsbD0iIzlkODFmZiIvPjwvZz48ZyBmaWx0ZXI9InVybCgjZCkiPjxwYXRoIGQ9Im0yODIuMTItMTA3LjM1M2MtNjYuMDczLTc4LjY3OC0xNjAuNjU3LTEzLjYxNy0xOTkuNjkwNCAyOC43NDgzLTM0LjE1NTcgNDcuOTYwMSAxNDEuODQ1NCAxMzUuODM1OSAxOTAuNjkxNCAxMjAuNzc2MSA0OC44NDctMTUuMDU5OS02Ni42MDktNDYuMjIxNzgtNDUuODI0LTc1LjQ1OTMgMjAuNzg1LTI5LjIzNzYgMTM3LjQxNSAyNC4yODIyNCA1NC44MjMtNzQuMDY1MXoiIGZpbGw9IiM0ZDk0ZmYiLz48L2c+PHBhdGggY2xpcC1ydWxlPSJldmVub2RkIiBkPSJtOTMuMTg5IDE1Mi44MzZoNDMuNDg1bC00OS40NjU0LTQ5Ljc4NSA1MC4xMDE0LTQ5Ljc4NDcgMTMuNjQ1LTEzLjI2NjNoLTQ1LjEzNmwtNTcuNDgzMSA1Ny43NzczYy0yLjkwMSAyLjkxMTctMi44ODYxIDcuNjI0Ny4wMjk3IDEwLjUyMTd6bTI2LjE0MS00OS42NjhoLS4zMzVsLjMzMS0uMDA0em0wIDAgNDkuNDYxIDQ5Ljc4MS01MC4xMDEgNDkuNzg1LTEzLjY0NSAxMy4yNjZoNDUuMTM1bDU3LjQ4NC01Ny43NzRjMi45MDEtMi45MTIgMi44ODYtNy42MjQtLjAzLTEwLjUyMWwtNDQuODIzLTQ0LjUzN3oiIGZpbGw9IiMwMDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ne.Unsupported&&ua(()=>{var t,i;return(i=(t=window.bitkeep)==null?void 0:t.solana)!=null&&i.isBitKeep?(this._readyState=ne.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Installed)throw new Ki;this._connecting=!0;const e=window.bitkeep.solana;let t;try{t=await e.getAccount()}catch(r){throw new Ps(r==null?void 0:r.message,r)}let i;try{i=new ei(t)}catch(r){throw new Pr(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch(t){this.emit("error",new la(t==null?void 0:t.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signTransaction(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signAllTransactions(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Fe;try{const{signature:i}=await t.signMessage(e);return i}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const Pv="Clover";class Tv extends da{constructor(e={}){super(),this.name=Pv,this.url="https://clv.org",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDgiIGhlaWdodD0iNDgiIHZpZXdCb3g9IjAgMCA0OCA0OCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTM2LjQ4IDBIMTEuNTJDNS4xNTc2OCAwIDAgNS4xNTc2OCAwIDExLjUyVjM2LjQ4QzAgNDIuODQyMyA1LjE1NzY4IDQ4IDExLjUyIDQ4SDM2LjQ4QzQyLjg0MjMgNDggNDggNDIuODQyMyA0OCAzNi40OFYxMS41MkM0OCA1LjE1NzY4IDQyLjg0MjMgMCAzNi40OCAwWiIgZmlsbD0idXJsKCNwYWludDBfbGluZWFyXzc5MTBfMTYzMzUxKSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTI0LjAwMDYgMzkuMzYwNkMzMi40ODM3IDM5LjM2MDYgMzkuMzYwNiAzMi40ODM3IDM5LjM2MDYgMjQuMDAwNkMzOS4zNjA2IDE1LjUxNzUgMzIuNDgzNyA4LjY0MDYyIDI0LjAwMDYgOC42NDA2MkMxNS41MTc1IDguNjQwNjIgOC42NDA2MiAxNS41MTc1IDguNjQwNjIgMjQuMDAwNkM4LjY0MDYyIDMyLjQ4MzcgMTUuNTE3NSAzOS4zNjA2IDI0LjAwMDYgMzkuMzYwNlpNMjEuMjg5OSAxNS44Njg4SDI2LjcxMVYyMS4zNDdIMjEuMjkwNFYyNi42NTRIMjYuNzExVjMyLjEzMjJIMjEuMjg5OVYyNi44MjUySDE1Ljg2OTNWMjEuMzQ3SDIxLjI4OTlWMTUuODY4OFpNMjYuNzEyIDIxLjM0N0gzMi4xMzMxVjI2LjgyNTJIMjYuNzEyVjIxLjM0N1oiIGZpbGw9ImJsYWNrIi8+CjxkZWZzPgo8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfNzkxMF8xNjMzNTEiIHgxPSI0OCIgeTE9Ii0xLjQzMDUxZS0wNiIgeDI9IjEuNDMwNTFlLTA2IiB5Mj0iNDgiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KPHN0b3Agc3RvcC1jb2xvcj0iI0E5RkZFMCIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM4NkQ1RkYiLz4KPC9saW5lYXJHcmFkaWVudD4KPC9kZWZzPgo8L3N2Zz4=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ne.Unsupported&&ua(()=>{var t;return(t=window.clover_solana)!=null&&t.isCloverWallet?(this._readyState=ne.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Installed)throw new Ki;this._connecting=!0;const e=window.clover_solana;let t;try{t=await e.getAccount()}catch(r){throw new Ps(r==null?void 0:r.message,r)}let i;try{i=new ei(t)}catch(r){throw new Pr(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){this._wallet&&(this._wallet=null,this._publicKey=null),this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signTransaction(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signAllTransactions(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Fe;try{const{signature:i}=await t.signMessage(e);return Uint8Array.from(i)}catch(i){throw new ha(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}function Mv(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<s.length;c++){const h=s.charAt(c),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=c}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,u=0,d=0;const p=c.length;for(;d!==p&&c[d]===0;)d++,h++;const g=(p-d)*n+1>>>0,f=new Uint8Array(g);for(;d!==p;){let m=c[d],b=0;for(let I=g-1;(m!==0||b<u)&&I!==-1;I--,b++)m+=256*f[I]>>>0,f[I]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");u=b,d++}let y=g-u;for(;y!==g&&f[y]===0;)y++;let w=i.repeat(h);for(;y<g;++y)w+=s.charAt(f[y]);return w}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;c[h]===i;)u++,h++;const p=(c.length-h)*r+1>>>0,g=new Uint8Array(p);for(;h<c.length;){const m=c.charCodeAt(h);if(m>255)return;let b=e[m];if(b===255)return;let I=0;for(let N=p-1;(b!==0||I<d)&&N!==-1;N--,I++)b+=t*g[N]>>>0,g[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=I,h++}let f=p-d;for(;f!==p&&g[f]===0;)f++;const y=new Uint8Array(u+(p-f));let w=u;for(;f!==p;)y[w++]=g[f++];return y}function l(c){const h=a(c);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:l}}var Ov="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const dl=Mv(Ov),xv="Coin98";class Dv extends da{constructor(e={}){super(),this.name=xv,this.url="https://coin98.com",this.icon="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA3NiA3NSI+CiAgPGRlZnM+CiAgICA8bGluZWFyR3JhZGllbnQgaWQ9ImEiIHgxPSIxMDEuNjgxJSIgeDI9Ii0xLjU1NyUiIHkxPSIxNS4yNjglIiB5Mj0iODQuOTE3JSI+CiAgICAgIDxzdG9wIG9mZnNldD0iMCUiIHN0b3AtY29sb3I9IiNGMUQ5NjEiLz4KICAgICAgPHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjQ0RBMTQ2Ii8+CiAgICA8L2xpbmVhckdyYWRpZW50PgogIDwvZGVmcz4KICA8ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgPHJlY3Qgd2lkdGg9Ijc1IiBoZWlnaHQ9Ijc1IiBmaWxsPSIjMDAwIiByeD0iMTYiLz4KICAgIDxwYXRoIGZpbGw9InVybCgjYSkiIGZpbGwtcnVsZT0ibm9uemVybyIgZD0iTTYxLjQ0IDBhMTMuNzE0IDEzLjcxNCAwIDAgMSA5LjY4IDQuMDEgMTMuNjYxIDEzLjY2MSAwIDAgMSA0LjAwOCA5LjY2OHY0Ny42NDZhMTMuNjYgMTMuNjYgMCAwIDEtNC4wMDcgOS42NjZBMTMuNzEzIDEzLjcxMyAwIDAgMSA2MS40NCA3NUgxMy42ODZhMTMuNzEzIDEzLjcxMyAwIDAgMS05LjY4LTQuMDFBMTMuNjYgMTMuNjYgMCAwIDEgMCA2MS4zMjRWMTMuNjc4YzAtMy42MjUgMS40NC03LjEwMiA0LjAwNy05LjY2N0ExMy43MTQgMTMuNzE0IDAgMCAxIDEzLjY4NyAwWk0yMC4wNjMgNDYuMjMxaC00LjgyNWExMC4wMzIgMTAuMDMyIDAgMCAwIDIuOTQ2IDcuMDg2IDEwLjA3IDEwLjA3IDAgMCAwIDcuMSAyLjk0MiAxMC4wNjUgMTAuMDY1IDAgMCAwIDcuMTA4LTIuOTM1IDEwLjAzIDEwLjAzIDAgMCAwIDIuOTQ2LTcuMDkzaC00LjgyNGE1LjIwNyA1LjIwNyAwIDAgMS0xLjUzIDMuNjg4IDUuMjI1IDUuMjI1IDAgMCAxLTMuNjk2IDEuNTI4IDUuMjM0IDUuMjM0IDAgMCAxLTMuNjk1LTEuNTI4IDUuMjEzIDUuMjEzIDAgMCAxLTEuNTMtMy42ODhaTTU0LjMzIDMzLjcxNmExMS43NjMgMTEuNzYzIDAgMCAwLTEyLjc5OSAyLjUzOEExMS42OTcgMTEuNjk3IDAgMCAwIDM4Ljk5IDQ5LjAzYTExLjcyMyAxMS43MjMgMCAwIDAgNC4zMjggNS4yNTkgMTEuNzU3IDExLjc1NyAwIDAgMCA2LjUyNiAxLjk3IDExLjc2NiAxMS43NjYgMCAwIDAgOC4yOS0zLjQzNSAxMS43MiAxMS43MiAwIDAgMCAzLjQ0Mi04LjI3NCAxMS43MDIgMTEuNzAyIDAgMCAwLTEuOTc1LTYuNTE0IDExLjczNiAxMS43MzYgMCAwIDAtNS4yNjktNC4zMlptLTQuNDg4IDMuOTJhNi45MzcgNi45MzcgMCAwIDEgNC45IDIuMDI1IDYuOTEgNi45MSAwIDAgMSAyLjAyOCA0Ljg5MiA2Ljg5NyA2Ljg5NyAwIDAgMS0xLjE3IDMuODM0IDYuOTMyIDYuOTMyIDAgMCAxLTEwLjY0MyAxLjA0MiA2LjkwMiA2LjkwMiAwIDAgMS0xLjUtNy41MjIgNi45MDkgNi45MDkgMCAwIDEgMi41NDQtMy4xIDYuOTI4IDYuOTI4IDAgMCAxIDMuODQxLTEuMTY3Wm0uMTcgNC41NTJhMi40MzEgMi40MzEgMCAwIDAtMi4yNDEgMS4xNTQgMi40MTggMi40MTggMCAwIDAtLjM1NiAxLjI1NyAyLjM5NSAyLjM5NSAwIDAgMCAxLjYxOSAyLjI5djEuNzUzaDEuNjE4di0xLjc1NGEyLjQyNyAyLjQyNyAwIDAgMCAxLjU5NC0xLjk1IDIuNDE4IDIuNDE4IDAgMCAwLTEtMi4zMSAyLjQzMSAyLjQzMSAwIDAgMC0xLjIzNC0uNDRabS0yMC4yMi0yMi41NTJhMTEuNzYyIDExLjc2MiAwIDAgMC0xMi43OTYgMi41MzEgMTEuNjk3IDExLjY5NyAwIDAgMC0yLjU1NCAxMi43NjkgMTEuNzIzIDExLjcyMyAwIDAgMCA0LjMyIDUuMjYyIDExLjc1NyAxMS43NTcgMCAwIDAgMTQuODI1LTEuNDQ2IDExLjcxNyAxMS43MTcgMCAwIDAgMy40NDUtOC4yODQgMTEuNzAzIDExLjcwMyAwIDAgMC0xLjk3NC02LjUxMiAxMS43MzYgMTEuNzM2IDAgMCAwLTUuMjY2LTQuMzJabS00LjUxIDMuOTE3YTYuOTQ1IDYuOTQ1IDAgMCAxIDQuODk3IDIuMDI5IDYuOTE4IDYuOTE4IDAgMCAxIDIuMDMyIDQuODg2IDYuOTA2IDYuOTA2IDAgMCAxLTEuMTY4IDMuODQyIDYuOTQgNi45NCAwIDAgMS0xMC42NiAxLjA0OCA2LjkxMSA2LjkxMSAwIDAgMS0xLjUtNy41MzYgNi45MTggNi45MTggMCAwIDEgMi41NS0zLjEwMyA2LjkzNyA2LjkzNyAwIDAgMSAzLjg1LTEuMTY2Wm0yNC41Ni00LjgxYTEwLjA1OSAxMC4wNTkgMCAwIDAtNy4xMDMgMi45NCAxMC4wMiAxMC4wMiAwIDAgMC0yLjk0IDcuMDkgOS45IDkuOSAwIDAgMCAxLjIzIDQuNzk1IDEzLjU3NSAxMy41NzUgMCAwIDEgNC4yMTQtMi4zMjIgNS4wODIgNS4wODIgMCAwIDEtLjYyNS0yLjQ3NyA1LjIwNiA1LjIwNiAwIDAgMSAxLjUwMy0zLjczNiA1LjIyMyA1LjIyMyAwIDAgMSAzLjcyMi0xLjU1NCA1LjIzNCA1LjIzNCAwIDAgMSAzLjcyIDEuNTU0IDUuMjEzIDUuMjEzIDAgMCAxIDEuNTA1IDMuNzM2IDUuMjc5IDUuMjc5IDAgMCAxLS42MjMgMi40NzMgMTMuNTc0IDEzLjU3NCAwIDAgMSA0LjIxMyAyLjMyMiA5LjkwMyA5LjkwMyAwIDAgMCAxLjIzLTQuNzk1IDEwLjAzMiAxMC4wMzIgMCAwIDAtMi45NDYtNy4wODYgMTAuMDcgMTAuMDcgMCAwIDAtNy4xLTIuOTRabS0yMy43NSA3Ljk5aC0xLjYxN3YxLjc1YTIuNDE5IDIuNDE5IDAgMCAwLTEuNTgyIDIuNjg3IDIuNDE0IDIuNDE0IDAgMCAwIDIuMzkgMi4wMDYgMi40NSAyLjQ1IDAgMCAwIDEuNTU1LS41NzQgMi40MTQgMi40MTQgMCAwIDAtLjc0Ni00LjExOXYtMS43NVoiLz4KICA8L2c+Cjwvc3ZnPgo=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ne.Unsupported&&ua(()=>{var t;return(t=window.coin98)!=null&&t.sol?(this._readyState=ne.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){var e;return!!((e=this._wallet)!=null&&e.isConnected())}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Installed)throw new Ki;this._connecting=!0;const e=window.coin98.sol;let t;try{t=(await e.connect())[0]}catch(r){throw new Ps(r==null?void 0:r.message,r)}let i;try{i=new ei(t)}catch(r){throw new Pr(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch(t){this.emit("error",new la(t==null?void 0:t.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{const i=await t.request({method:"sol_sign",params:[e]}),r=new ei(i.publicKey),n=dl.decode(i.signature);return e.addSignature(r,_.Buffer.from(n)),e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Fe;try{const i=await t.request({method:"sol_signAllTransactions",params:[e]}),r=new ei(i.publicKey),n=i.signatures;return e.map((o,a)=>{const l=dl.decode(n[a]);return o.addSignature(r,_.Buffer.from(l)),o})}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Fe;try{const i=await t.request({method:"sol_signMessage",params:[e]});return dl.decode(i.signature)}catch(i){throw new ha(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const kv="Nightly";class jv extends da{constructor(){super(),this.name=kv,this.url="https://nightly.app",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iOTYiIGhlaWdodD0iOTYiIHZpZXdCb3g9IjAgMCA5NiA5NiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQ4IDk2Qzc0LjUwOTcgOTYgOTYgNzQuNTA5NyA5NiA0OEM5NiAyMS40OTAzIDc0LjUwOTcgMCA0OCAwQzIxLjQ5MDMgMCAwIDIxLjQ5MDMgMCA0OEMwIDc0LjUwOTcgMjEuNDkwMyA5NiA0OCA5NloiIGZpbGw9IiM2RDczRjgiLz4KPHBhdGggZD0iTTQ4IDg1LjYzNTZDNDggODUuNjM1NiA1Mi40NTMzIDg1LjYzNTYgNTUuNDQgODIuNTg2N0M1OC45MTU1IDc5LjI4MDEgNTcuMzUxMSA3NS40MzEyIDYyLjI3NTUgNzEuNDMxMkM2Ni45ODY2IDY3LjY0NDUgNzIuOTI0NCA3MC4zMzc5IDcyLjkyNDQgNzAuMzM3OUM3Ny4wMjIyIDYyLjEyNDUgNzQuNzkxMSA1Mi41NjkgNzQuNzkxMSA1Mi41NjlDODEuNzY4OCAzNC4yNTc5IDc1Ljk2NDQgMjEuMTU1NyA3NC40NDQ0IDE3LjM2MDFDNjkuNDQ4OCAyNC4zMzc5IDYzLjE5MTEgMjkuMTczNCA1NS43OTU1IDMyLjQwOUM1My4yMjY2IDMxLjcwNjggNTAuNTk1NSAzMS4zMzM0IDQ4IDMxLjM2MDFDNDUuNDEzMyAzMS4zMzM0IDQyLjc3MzMgMzEuNzA2OCA0MC4yMDQ0IDMyLjQwOUMzMi44MTc3IDI5LjE2NDUgMjYuNTUxMSAyNC4zMzc5IDIxLjU1NTUgMTcuMzYwMUMyMC4wMzU1IDIxLjE1NTcgMTQuMjMxMSAzNC4yNTc5IDIxLjIwODkgNTIuNTY5QzIxLjIwODkgNTIuNTY5IDE4Ljk3NzggNjIuMTI0NSAyMy4wNzU1IDcwLjMzNzlDMjMuMDc1NSA3MC4zMzc5IDI5LjAxMzMgNjcuNjQ0NSAzMy43MjQ0IDcxLjQzMTJDMzguNjU3NyA3NS40MzEyIDM3LjA4NDQgNzkuMjgwMSA0MC41NiA4Mi41ODY3QzQzLjU0NjYgODUuNjM1NiA0OCA4NS42MzU2IDQ4IDg1LjYzNTZaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNNDIuNDc5OSA2NS4yOThDNDIuMjkzMyA1OS4yMTggMzYuMzAyMSA1Ny4yNjI0IDMyLjIxMzMgNTkuODIyNEMzMi4yMTMzIDU5LjgyMjQgMzIuODUzMyA2Mi40MzU4IDM1LjgzOTkgNjMuNzUxM0MzOC4yNzU1IDY0LjgyNjkgMzkuMzI0NCA2My4zODY5IDQyLjQ3OTkgNjUuMjk4WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNMjIuNDk3NyAyMy4wOTM1QzIwLjA4ODggMzEuNTQ2OCAyMS4xMjg4IDQyLjI0MDIgMjQuOTMzMyA1MC4wMjY5QzI4LjgyNjYgNDcuMjcxMyAzMi45MTU1IDQzLjAxMzUgMzUuMDkzMyAzOC41MDY5QzI5Ljk2NDQgMzQuNzExMyAyNS42NjIyIDMxLjEwMjQgMjIuNDk3NyAyMy4wOTM1WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNTMuNTE5OSA2NS4yOThDNTMuNzA2NiA1OS4yMTggNTkuNjk3NyA1Ny4yNjI0IDYzLjc4NjYgNTkuODIyNEM2My43ODY2IDU5LjgyMjQgNjMuMTQ2NiA2Mi40MzU4IDYwLjE1OTkgNjMuNzUxM0M1Ny43MjQzIDY0LjgyNjkgNTYuNjc1NSA2My4zODY5IDUzLjUxOTkgNjUuMjk4WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNzMuNTAyMiAyMy4wOTM1Qzc1LjkxMTEgMzEuNTQ2OCA3NC44NzExIDQyLjI0MDIgNzEuMDY2NiA1MC4wMjY5QzY3LjE3MzMgNDcuMjcxMyA2My4wODQ0IDQzLjAxMzUgNjAuOTA2NiAzOC41MDY5QzY2LjAzNTUgMzQuNzExMyA3MC4zMzc3IDMxLjEwMjQgNzMuNTAyMiAyMy4wOTM1WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNDcuOTk5OSA4NS4zMDY5QzUwLjE0MDQgODUuMzA2OSA1MS44NzU1IDgzLjc3ODcgNTEuODc1NSA4MS44OTM2QzUxLjg3NTUgODAuMDA4NCA1MC4xNDA0IDc4LjQ4MDIgNDcuOTk5OSA3OC40ODAyQzQ1Ljg1OTUgNzguNDgwMiA0NC4xMjQ0IDgwLjAwODQgNDQuMTI0NCA4MS44OTM2QzQ0LjEyNDQgODMuNzc4NyA0NS44NTk1IDg1LjMwNjkgNDcuOTk5OSA4NS4zMDY5WiIgZmlsbD0iIzdCODFGOSIvPgo8L3N2Zz4K",this.supportedTransactionVersions=new Set(["legacy",0]),this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.NotDetected,this._connecting=!1,this._publicKey=null,this._wallet=null,this._readyState!==ne.Unsupported&&ua(()=>{var e;return(e=window==null?void 0:window.nightly)!=null&&e.solana?(this._readyState=ne.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get connecting(){return this._connecting}get readyState(){return this._readyState}get publicKey(){return this._publicKey}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Installed)throw new Ki;this._connecting=!0;const e=window.nightly.solana;try{await e.connect()}catch(i){throw new Fc(i==null?void 0:i.message,i)}if(e.publicKey.toString()==="11111111111111111111111111111111")throw new Ps;let t;try{t=new ei(e.publicKey.toBytes())}catch(i){throw new Pr(i==null?void 0:i.message,i)}this._wallet=e,this._publicKey=t,this.emit("connect",t)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch{this.emit("error",new Om)}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signTransaction(e)}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signAllTransactions(e)}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Fe;try{return t.signMessage(new TextDecoder().decode(e))}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const ud="solana:mainnet",Rv="solana:devnet",Lv="solana:testnet",Uv="solana:localnet",zv="Solong";class Fv extends Nu{constructor(e={}){super(),this.name=zv,this.url="https://solongwallet.io",this.icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAGlklEQVR4Ae3bA5DsyhfH8TNr49r2/du2bdu2bdu2zcdNrm3b9toz533rvctUn3Umk9p01WfdvVW/6nROBxJVS1rSkpa0pCUtaUlLWtKSpl4VXos3GJ4sujQFuUKfWl+qT730arzB8Ex9YksKcgXjFOCVeIPhBYydB8mawQ+yiGC8n0EN6zAVcgXhpQjoq1DDdsyDAAB9Pwo1HMC9INk0FIM8Bt1Qh9WohQQCvD+BtEMdtmC8I7y5aIE67MV0SBwDvB3qsE/UHwMJIpC/QB1OYiLEEeCPoQ7nMRcSwwDrao3Zl8aTIEGEUYlL0IAMXuQOr66UvsegDm+ExDJAPNiafSg0AlyIbmjAWX1aQzEkiH6T0QkNaEdpnAN8NNRhPcSF9e9el2ebBhyAuNBvGtLQgIuQOAd4D6jDMRQbM3AmOqEBDfq0xjJIEP3GohkakEFVjAP0y401sAsLnAE+pb6EsC5AA9J4sHsG+kX0PQR1eFJ8AwTWQh0+DjFm4a1Qh2/AOoz/BHX4ZdwD/CDU4aioX2GUMW+AOnB2bqiBBDHe86EOTYw5GRKJwQ/ijUM91OGTxgysxSmowzeNw7j08m5DHX4l7Igg2TY0g9hbLBZ+f7oxC98CdWjDvYzD+MVQh07GfEQsZyDgVWA71OGvorfnQQCAcqaYUFZDHW6j/itAoB70GcergzqsEa0rhGTTEA7mP0koK4xdyeOMmvBBhJU2zsjPMw7lu9O3zShpXheHk4hhcZ4w26AOG4RSxDiUfwZ12KdPqy+FBDHeV6EOZxizIg6HsMGbiQ5jdjzBXRfeefGg3tgbv9BYC0fhZE7sjUMY9Pf9rdcI5XtQh39BjBA/C3VYnM0zcgiDek+GOhzh93mQoMs7kIxze/eMhnxIEOPNM9bcFtTEeAb6I419axu/m2CsgxU4Aw1A/UxIUM/bO/9+cVkDDd5x42x8N1iH8Taow0NhHcZLoQ5Pi/MMzDMW+DTu7g6vIY9AdkAdHmaUMyn6roA6PD22AeLB6DbWplHG7LubfY+kfiIkiH5T0AJ1uFtMA1xUzOc1UIclzvCeXF+o7DygDlvds29RgVVzYj+K4xhgEX4NdcjgecE++rSL+ZdLmIxRB77Ose7l4XPIQB3eF8M60C/n8++ghltE/QLIFfqUiyUE8kOoYSW7jmLIFXeN4X0NaajDDlG/NG6XswrxKdxu+G/weh27j3wCej9uN9zEOjc3sObl4S243XBLhDfWE0mAMQjwZfhxDng7pG/8Sj4/ER/Gd/BdfBhPRGW2A/wxNAfcBOnFCHwZZ6GGs/gqapMAb/QEnIT20Uk8IQkQeB7aof3UihcM9wDvhyboANHXv1+IdWBOB2hsIftto+iSPEif8aGPcjrA50GHyPMiOIT9B/N5apaMgQT8D2poxMdwt8s+hkao4X9ZDxBTIdHwy/h8AeqQxhMhAU9BB9ThPMqHTYCYjU6owy3uPstSfL4Z6uZPC+Mk8gOomz8DEg3vXshAHb4MMXwZarhXGDPwa739w2j48623BPAniOFPUMPsMAL8INTw9AgDrLZOCmjFPEjA3WD1aUJVGAG+CGr4ECRCy6GGg3iyaF0+n/PwFByEGpaJ+qkw1sB7QA3/hUTozdBetFymvXhTWGVMOc7bp36/FhKRamNW9dcxZmpZiI+32ad+vAQSoWejGzpAXXh22Fek3wY1rDD2kVnijR3ExYQMPgkJOUB/nFW0Is3vnw6JhlHX9a4N70Iq/ACBv0MNu7J9WxHw7jaA2deFOtw32zeVHtHLWvMN0dtSkOzwS3spYy7iH1hx2d/wYdyTvnkR3BdeQjjerVBDN14JyZIfQWH5RC7e1rw32npZV54LCc+SPD5/HgqYD3WW5+gTqt6X+rA4v0701hRkKF0+bL+HTM9Hgv/MHH60wyvHWigsafwA1ZAhMguLoL34kbDcQEI1uAH8mcbuxPHImf8i5EMGxqvER9EI7cUqVMTl0Y6HoxHaBzvxNkyC9EEe7oEv4Sy0D/YQ+IS4ver1JNT38z7sWnwbb8TT8Cg8Gs/Gu/Ar7EEXtI/2ud7Ni0GAYCbiJDQiazA57k9nTcdqaJb9UtSvitXbmjavCJ9AMzRkJ/B80boUJBLhDe7Nw1/QCR1i9fgKRg6HByzvjZ/hInQQMjiCT2PSMHxC1a/l8wvwGxyG9kEaW/EtPI4xiiE5JcLrd6PxcLwM78SH8EG8Fc/H/UUXVUByGh8SSYBJgEmASYCJJMAkwBi6A3xCqZhiBz8+AAAAAElFTkSuQmCC",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ne.Unsupported&&ua(()=>window.solong?(this._readyState=ne.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){var e;return!!((e=this._wallet)!=null&&e.currentAccount)}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Installed)throw new Ki;this._connecting=!0;const e=window.solong;let t;try{t=await e.selectAccount()}catch(r){throw new Ps(r==null?void 0:r.message,r)}let i;try{i=new ei(t)}catch(r){throw new Pr(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){this._wallet&&(this._wallet=null,this._publicKey=null),this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signTransaction(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const qv="Torus";class Bv extends da{constructor({params:e={showTorusButton:!1}}={params:{showTorusButton:!1}}){super(),this.name=qv,this.url="https://tor.us",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzMiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMyAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYuNSIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzAzNjRGRiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTExLjIxODYgOS40OTIxOUMxMC40NTM5IDkuNDkyMTkgOS44MzM5OCAxMC4xMTIxIDkuODMzOTggMTAuODc2OFYxMi40ODk4QzkuODMzOTggMTMuMjU0NSAxMC40NTM5IDEzLjg3NDQgMTEuMjE4NiAxMy44NzQ0SDEzLjY2ODRWMjIuODk3NkMxMy42Njg0IDIzLjY2MjMgMTQuMjg4MyAyNC4yODIyIDE1LjA1MyAyNC4yODIySDE2LjY2NkMxNy40MzA3IDI0LjI4MjIgMTguMDUwNiAyMy42NjIzIDE4LjA1MDYgMjIuODk3NlYxMi41MDE1QzE4LjA1MDYgMTIuNDk3NiAxOC4wNTA2IDEyLjQ5MzcgMTguMDUwNiAxMi40ODk4VjEwLjg3NjhDMTguMDUwNiAxMC4xMTIxIDE3LjQzMDcgOS40OTIxOSAxNi42NjYgOS40OTIxOUgxNS4wNTNIMTEuMjE4NloiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0yMS4zMzc2IDEzLjg3NDRDMjIuNTQ3NyAxMy44NzQ0IDIzLjUyODcgMTIuODkzNCAyMy41Mjg3IDExLjY4MzNDMjMuNTI4NyAxMC40NzMyIDIyLjU0NzcgOS40OTIxOSAyMS4zMzc2IDkuNDkyMTlDMjAuMTI3NSA5LjQ5MjE5IDE5LjE0NjUgMTAuNDczMiAxOS4xNDY1IDExLjY4MzNDMTkuMTQ2NSAxMi44OTM0IDIwLjEyNzUgMTMuODc0NCAyMS4zMzc2IDEzLjg3NDRaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.Loadable,this._connecting=!1,this._wallet=null,this._publicKey=null,this._params=e}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){var e;return!!((e=this._wallet)!=null&&e.isLoggedIn)}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Loadable)throw new Ki;this._connecting=!0;let e;try{e=(await Vo(async()=>{const{default:n}=await import("./solanaEmbed.esm-DhAz8SOB.js");return{default:n}},__vite__mapDeps([0,1,2,3]))).default}catch(n){throw new Nv(n==null?void 0:n.message,n)}let t;try{t=window.torus||new e}catch(n){throw new Cn(n==null?void 0:n.message,n)}if(!t.isInitialized)try{await t.init(this._params)}catch(n){throw new Fc(n==null?void 0:n.message,n)}let i;try{i=await t.login()}catch(n){throw new Ps(n==null?void 0:n.message,n)}let r;try{r=new ei(i[0])}catch(n){throw new Pr(n==null?void 0:n.message,n)}this._wallet=t,this._publicKey=r,this.emit("connect",r)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{e.isLoggedIn&&await e.cleanUp()}catch(t){this.emit("error",new la(t==null?void 0:t.message,t))}}this.emit("disconnect")}async sendTransaction(e,t,i={}){try{const r=this._wallet;if(!r)throw new Fe;try{const{signers:n,...o}=i;e=await this.prepareTransaction(e,t,o),n!=null&&n.length&&e.partialSign(...n),o.preflightCommitment=o.preflightCommitment||t.commitment;const{signature:a}=await r.signAndSendTransaction(e,o);return a}catch(n){throw n instanceof jt?n:new ur(n==null?void 0:n.message,n)}}catch(r){throw this.emit("error",r),r}}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signTransaction(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signAllTransactions(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signMessage(e)}catch(i){throw new ha(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}function pl(s){switch(s){case"processed":case"confirmed":case"finalized":case void 0:return s;case"recent":return"processed";case"single":case"singleGossip":return"confirmed";case"max":case"root":return"finalized";default:return}}const Hv="https://api.mainnet-beta.solana.com";function Wv(s){return s.includes(Hv)?ud:/\bdevnet\b/i.test(s)?Rv:/\btestnet\b/i.test(s)?Lv:/\blocalhost\b/i.test(s)||/\b127\.0\.0\.1\b/.test(s)?Uv:ud}var Ic;(function(s){s.Mainnet="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",s.Devnet="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",s.Deprecated_Mainnet="solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",s.Deprecated_Devnet="solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"})(Ic||(Ic={}));var $s;(function(s){s.signTransaction="solana_signTransaction",s.signMessage="solana_signMessage",s.signAndSendTransaction="solana_signAndSendTransaction",s.signAndSendAllTransactions="solana_signAndSendAllTransactions",s.signAllTransactions="solana_signAllTransactions"})($s||($s={}));const pt={Mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Deprecated_Mainnet:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",Deprecated_Devnet:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"};let Vv=class extends bs{constructor(e){super()}};const dd=E.FIVE_SECONDS,qs={pulse:"heartbeat_pulse"};let jm=class Rm extends Vv{constructor(e){super(e),this.events=new kt.EventEmitter,this.interval=dd,this.interval=(e==null?void 0:e.interval)||dd}static async init(e){const t=new Rm(e);return await t.init(),t}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),E.toMiliseconds(this.interval))}pulse(){this.events.emit(qs.pulse)}};function Kv(s){return!s||typeof s.then!="function"?Promise.resolve(s):s}function yt(s,...e){try{return Kv(s(...e))}catch(t){return Promise.reject(t)}}function Gv(s){const e=typeof s;return s===null||e!=="object"&&e!=="function"}function Yv(s){const e=Object.getPrototypeOf(s);return!e||e.isPrototypeOf(Object)}function tc(s){if(Gv(s))return String(s);if(Yv(s)||Array.isArray(s))return JSON.stringify(s);if(typeof s.toJSON=="function")return tc(s.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const mh="base64:";function Qv(s){return typeof s=="string"?s:mh+Xv(s)}function Zv(s){return typeof s!="string"||!s.startsWith(mh)?s:Jv(s.slice(mh.length))}function Jv(s){return globalThis.Buffer?_.Buffer.from(s,"base64"):Uint8Array.from(globalThis.atob(s),e=>e.codePointAt(0))}function Xv(s){return globalThis.Buffer?_.Buffer.from(s).toString("base64"):globalThis.btoa(String.fromCodePoint(...s))}function ts(s){var e;return s&&((e=s.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function e0(...s){return ts(s.join(":"))}function Ta(s){return s=ts(s),s?s+":":""}function t0(s,e){if(e===void 0)return!0;let t=0,i=s.indexOf(":");for(;i>-1;)t++,i=s.indexOf(":",i+1);return t<=e}function s0(s,e){return e?s.startsWith(e)&&s[s.length-1]!=="$":s[s.length-1]!=="$"}const i0="memory",r0=()=>{const s=new Map;return{name:i0,getInstance:()=>s,hasItem(e){return s.has(e)},getItem(e){return s.get(e)??null},getItemRaw(e){return s.get(e)??null},setItem(e,t){s.set(e,t)},setItemRaw(e,t){s.set(e,t)},removeItem(e){s.delete(e)},getKeys(){return[...s.keys()]},clear(){s.clear()},dispose(){s.clear()}}};function n0(s={}){const e={mounts:{"":s.driver||r0()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=c=>{for(const h of e.mountpoints)if(c.startsWith(h))return{base:h,relativeKey:c.slice(h.length),driver:e.mounts[h]};return{base:"",relativeKey:c,driver:e.mounts[""]}},i=(c,h)=>e.mountpoints.filter(u=>u.startsWith(c)||h&&c.startsWith(u)).map(u=>({relativeBase:c.length>u.length?c.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(c,h)=>{if(e.watching){h=ts(h);for(const u of e.watchListeners)u(c,h)}},n=async()=>{if(!e.watching){e.watching=!0;for(const c in e.mounts)e.unwatch[c]=await pd(e.mounts[c],r,c)}},o=async()=>{if(e.watching){for(const c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},a=(c,h,u)=>{const d=new Map,p=g=>{let f=d.get(g.base);return f||(f={driver:g.driver,base:g.base,items:[]},d.set(g.base,f)),f};for(const g of c){const f=typeof g=="string",y=ts(f?g:g.key),w=f?void 0:g.value,m=f||!g.options?h:{...h,...g.options},b=t(y);p(b).items.push({key:y,value:w,relativeKey:b.relativeKey,options:m})}return Promise.all([...d.values()].map(g=>u(g))).then(g=>g.flat())},l={hasItem(c,h={}){c=ts(c);const{relativeKey:u,driver:d}=t(c);return yt(d.hasItem,u,h)},getItem(c,h={}){c=ts(c);const{relativeKey:u,driver:d}=t(c);return yt(d.getItem,u,h).then(p=>Di(p))},getItems(c,h={}){return a(c,h,u=>u.driver.getItems?yt(u.driver.getItems,u.items.map(d=>({key:d.relativeKey,options:d.options})),h).then(d=>d.map(p=>({key:e0(u.base,p.key),value:Di(p.value)}))):Promise.all(u.items.map(d=>yt(u.driver.getItem,d.relativeKey,d.options).then(p=>({key:d.key,value:Di(p)})))))},getItemRaw(c,h={}){c=ts(c);const{relativeKey:u,driver:d}=t(c);return d.getItemRaw?yt(d.getItemRaw,u,h):yt(d.getItem,u,h).then(p=>Zv(p))},async setItem(c,h,u={}){if(h===void 0)return l.removeItem(c);c=ts(c);const{relativeKey:d,driver:p}=t(c);p.setItem&&(await yt(p.setItem,d,tc(h),u),p.watch||r("update",c))},async setItems(c,h){await a(c,h,async u=>{if(u.driver.setItems)return yt(u.driver.setItems,u.items.map(d=>({key:d.relativeKey,value:tc(d.value),options:d.options})),h);u.driver.setItem&&await Promise.all(u.items.map(d=>yt(u.driver.setItem,d.relativeKey,tc(d.value),d.options)))})},async setItemRaw(c,h,u={}){if(h===void 0)return l.removeItem(c,u);c=ts(c);const{relativeKey:d,driver:p}=t(c);if(p.setItemRaw)await yt(p.setItemRaw,d,h,u);else if(p.setItem)await yt(p.setItem,d,Qv(h),u);else return;p.watch||r("update",c)},async removeItem(c,h={}){typeof h=="boolean"&&(h={removeMeta:h}),c=ts(c);const{relativeKey:u,driver:d}=t(c);d.removeItem&&(await yt(d.removeItem,u,h),(h.removeMeta||h.removeMata)&&await yt(d.removeItem,u+"$",h),d.watch||r("remove",c))},async getMeta(c,h={}){typeof h=="boolean"&&(h={nativeOnly:h}),c=ts(c);const{relativeKey:u,driver:d}=t(c),p=Object.create(null);if(d.getMeta&&Object.assign(p,await yt(d.getMeta,u,h)),!h.nativeOnly){const g=await yt(d.getItem,u+"$",h).then(f=>Di(f));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(p,g))}return p},setMeta(c,h,u={}){return this.setItem(c+"$",h,u)},removeMeta(c,h={}){return this.removeItem(c+"$",h)},async getKeys(c,h={}){var y;c=Ta(c);const u=i(c,!0);let d=[];const p=[];let g=!0;for(const w of u){(y=w.driver.flags)!=null&&y.maxDepth||(g=!1);const m=await yt(w.driver.getKeys,w.relativeBase,h);for(const b of m){const I=w.mountpoint+ts(b);d.some(N=>I.startsWith(N))||p.push(I)}d=[w.mountpoint,...d.filter(b=>!b.startsWith(w.mountpoint))]}const f=h.maxDepth!==void 0&&!g;return p.filter(w=>(!f||t0(w,h.maxDepth))&&s0(w,c))},async clear(c,h={}){c=Ta(c),await Promise.all(i(c,!1).map(async u=>{if(u.driver.clear)return yt(u.driver.clear,u.relativeBase,h);if(u.driver.removeItem){const d=await u.driver.getKeys(u.relativeBase||"",h);return Promise.all(d.map(p=>u.driver.removeItem(p,h)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>gd(c)))},async watch(c){return await n(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(h=>h!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,h){if(c=Ta(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((u,d)=>d.length-u.length)),e.mounts[c]=h,e.watching&&Promise.resolve(pd(h,r,c)).then(u=>{e.unwatch[c]=u}).catch(console.error),l},async unmount(c,h=!0){var u,d;c=Ta(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&((d=(u=e.unwatch)[c])==null||d.call(u),delete e.unwatch[c]),h&&await gd(e.mounts[c]),e.mountpoints=e.mountpoints.filter(p=>p!==c),delete e.mounts[c])},getMount(c=""){c=ts(c)+":";const h=t(c);return{driver:h.driver,base:h.base}},getMounts(c="",h={}){return c=ts(c),i(c,h.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(c,h={})=>l.getKeys(c,h),get:(c,h={})=>l.getItem(c,h),set:(c,h,u={})=>l.setItem(c,h,u),has:(c,h={})=>l.hasItem(c,h),del:(c,h={})=>l.removeItem(c,h),remove:(c,h={})=>l.removeItem(c,h)};return l}function pd(s,e,t){return s.watch?s.watch((i,r)=>e(i,t+r)):()=>{}}async function gd(s){typeof s.dispose=="function"&&await yt(s.dispose)}const o0="idb-keyval";var a0=(s={})=>{const e=s.base&&s.base.length>0?`${s.base}:`:"",t=r=>e+r;let i;return s.dbName&&s.storeName&&(i=Am(s.dbName,s.storeName)),{name:o0,options:s,async hasItem(r){return!(typeof await bc(t(r),i)>"u")},async getItem(r){return await bc(t(r),i)??null},setItem(r,n){return Sm(t(r),n,i)},removeItem(r){return Cm(t(r),i)},getKeys(){return _m(i)},clear(){return Nm(i)}}};const c0="WALLET_CONNECT_V2_INDEXED_DB",l0="keyvaluestorage";let h0=class{constructor(){this.indexedDb=n0({driver:a0({dbName:c0,storeName:l0})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,Sr(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var gl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof _.global<"u"?_.global:typeof self<"u"?self:{},sc={exports:{}};(function(){let s;function e(){}s=e,s.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},s.prototype.setItem=function(t,i){this[t]=String(i)},s.prototype.removeItem=function(t){delete this[t]},s.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(i){t[i]=void 0,delete t[i]})},s.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},s.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof gl<"u"&&gl.localStorage?sc.exports=gl.localStorage:typeof window<"u"&&window.localStorage?sc.exports=window.localStorage:sc.exports=new e})();function u0(s){var e;return[s[0],wi((e=s[1])!=null?e:"")]}let d0=class{constructor(){this.localStorage=sc.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(u0)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return wi(t)}async setItem(e,t){this.localStorage.setItem(e,Sr(t))}async removeItem(e){this.localStorage.removeItem(e)}};const p0="wc_storage_version",fd=1,g0=async(s,e,t)=>{const i=p0,r=await e.getItem(i);if(r&&r>=fd){t(e);return}const n=await s.getKeys();if(!n.length){t(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const l=a.toLowerCase();if(l.includes("wc@")||l.includes("walletconnect")||l.includes("wc_")||l.includes("wallet_connect")){const c=await s.getItem(a);await e.setItem(a,c),o.push(a)}}await e.setItem(i,fd),t(e),f0(s,o)},f0=async(s,e)=>{e.length&&e.forEach(async t=>{await s.removeItem(t)})};let m0=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new d0;this.storage=e;try{const t=new h0;g0(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}};var w0=Object.defineProperty,y0=(s,e,t)=>e in s?w0(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,md=(s,e,t)=>y0(s,typeof e!="symbol"?e+"":e,t);let b0=class extends bs{constructor(e){super(),this.opts=e,md(this,"protocol","wc"),md(this,"version",2)}};var v0=Object.defineProperty,I0=(s,e,t)=>e in s?v0(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,E0=(s,e,t)=>I0(s,e+"",t);let A0=class extends bs{constructor(e,t){super(),this.core=e,this.logger=t,E0(this,"records",new Map)}},N0=class{constructor(e,t){this.logger=e,this.core=t}},_0=class extends bs{constructor(e,t){super(),this.relayer=e,this.logger=t}},C0=class extends bs{constructor(e){super()}},S0=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},$0=class extends bs{constructor(e,t){super(),this.relayer=e,this.logger=t}},P0=class extends bs{constructor(e,t){super(),this.core=e,this.logger=t}},T0=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},M0=class{constructor(e,t){this.projectId=e,this.logger=t}},O0=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};function Go(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function wd(s){return Go(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const Lm="2.23.2";let ro={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${Lm}`},qc=class wh extends Error{constructor(e,t={}){var a;const i=(()=>{var l;return t.cause instanceof wh?t.cause.details:(l=t.cause)!=null&&l.message?t.cause.message:t.details})(),r=t.cause instanceof wh&&t.cause.docsPath||t.docsPath,n=(a=ro.getDocsUrl)==null?void 0:a.call(ro,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...ro.version?[`Version: ${ro.version}`]:[]].join(`
3
- `);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Lm}walk(e){return Um(this,e)}};function Um(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?Um(s.cause,e):e?null:s}let zm=class extends qc{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}};function Gn(s,{dir:e,size:t=32}={}){return typeof s=="string"?x0(s,{dir:e,size:t}):D0(s,{dir:e,size:t})}function x0(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new zm({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function D0(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new zm({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}let k0=class extends qc{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}},j0=class extends qc{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function Yn(s,{size:e}){if(wd(s)>e)throw new j0({givenSize:wd(s),maxSize:e})}function yh(s,e={}){const{signed:t}=e;e.size&&Yn(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function R0(s,e={}){return Number(yh(s,e))}const L0=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function bh(s,e={}){return typeof s=="number"||typeof s=="bigint"?qm(s,e):typeof s=="string"?F0(s,e):typeof s=="boolean"?U0(s,e):Fm(s,e)}function U0(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(Yn(t,{size:e.size}),Gn(t,{size:e.size})):t}function Fm(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=L0[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(Yn(i,{size:e.size}),Gn(i,{dir:"right",size:e.size})):i}function qm(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const l=typeof s=="bigint"?"n":"";throw new k0({max:n?`${n}${l}`:void 0,min:`${o}${l}`,signed:t,size:i,value:`${s}${l}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?Gn(a,{size:i}):a}const z0=new TextEncoder;function F0(s,e={}){const t=z0.encode(s);return Fm(t,e)}const q0=new TextEncoder;function B0(s,e={}){return typeof s=="number"||typeof s=="bigint"?W0(s,e):typeof s=="boolean"?H0(s,e):Go(s)?Bm(s,e):Hm(s,e)}function H0(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(Yn(t,{size:e.size}),Gn(t,{size:e.size})):t}const ri={zero:48,nine:57,A:65,F:70,a:97,f:102};function yd(s){if(s>=ri.zero&&s<=ri.nine)return s-ri.zero;if(s>=ri.A&&s<=ri.F)return s-(ri.A-10);if(s>=ri.a&&s<=ri.f)return s-(ri.a-10)}function Bm(s,e={}){let t=s;e.size&&(Yn(t,{size:e.size}),t=Gn(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const l=yd(i.charCodeAt(a++)),c=yd(i.charCodeAt(a++));if(l===void 0||c===void 0)throw new qc(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=l*16+c}return n}function W0(s,e){const t=qm(s,e);return Bm(t)}function Hm(s,e={}){const t=q0.encode(s);return typeof e.size=="number"?(Yn(t,{size:e.size}),Gn(t,{dir:"right",size:e.size})):t}function Ec(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function V0(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Bc(s,...e){if(!V0(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function uF(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ec(s.outputLen),Ec(s.blockLen)}function bd(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function K0(s,e){Bc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Ma=BigInt(2**32-1),vd=BigInt(32);function G0(s,e=!1){return e?{h:Number(s&Ma),l:Number(s>>vd&Ma)}:{h:Number(s>>vd&Ma)|0,l:Number(s&Ma)|0}}function Y0(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=G0(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const Q0=(s,e,t)=>s<<t|e>>>32-t,Z0=(s,e,t)=>e<<t|s>>>32-t,J0=(s,e,t)=>e<<t-32|s>>>64-t,X0=(s,e,t)=>s<<t-32|e>>>64-t,Lr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function eI(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function dF(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function pF(s,e){return s<<32-e|s>>>e}const Id=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function tI(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Ed(s){for(let e=0;e<s.length;e++)s[e]=tI(s[e])}function sI(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Wm(s){return typeof s=="string"&&(s=sI(s)),Bc(s),s}function gF(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Bc(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}let iI=class{clone(){return this._cloneInto()}};function rI(s){const e=i=>s().update(Wm(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function mF(s=32){if(Lr&&typeof Lr.getRandomValues=="function")return Lr.getRandomValues(new Uint8Array(s));if(Lr&&typeof Lr.randomBytes=="function")return Lr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Vm=[],Km=[],Gm=[],nI=BigInt(0),no=BigInt(1),oI=BigInt(2),aI=BigInt(7),cI=BigInt(256),lI=BigInt(113);for(let s=0,e=no,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Vm.push(2*(5*i+t)),Km.push((s+1)*(s+2)/2%64);let r=nI;for(let n=0;n<7;n++)e=(e<<no^(e>>aI)*lI)%cI,e&oI&&(r^=no<<(no<<BigInt(n))-no);Gm.push(r)}const[hI,uI]=Y0(Gm,!0),Ad=(s,e,t)=>t>32?J0(s,e,t):Q0(s,e,t),Nd=(s,e,t)=>t>32?X0(s,e,t):Z0(s,e,t);function dI(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,l=(o+2)%10,c=t[l],h=t[l+1],u=Ad(c,h,1)^t[a],d=Nd(c,h,1)^t[a+1];for(let p=0;p<50;p+=10)s[o+p]^=u,s[o+p+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Km[o],l=Ad(r,n,a),c=Nd(r,n,a),h=Vm[o];r=s[h],n=s[h+1],s[h]=l,s[h+1]=c}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=hI[i],s[1]^=uI[i]}t.fill(0)}let pI=class Ym extends iI{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Ec(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=eI(this.state)}keccak(){Id||Ed(this.state32),dI(this.state32,this.rounds),Id||Ed(this.state32),this.posOut=0,this.pos=0}update(e){bd(this);const{blockLen:t,state:i}=this;e=Wm(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){bd(this,!1),Bc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ec(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(K0(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:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Ym(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const gI=(s,e,t)=>rI(()=>new pI(e,s,t)),fI=gI(1,136,256/8);function Qm(s,e){const t=e||"hex",i=fI(Go(s,{strict:!1})?B0(s):s);return t==="bytes"?i:bh(i)}let mI=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}};const fl=new mI(8192);function wI(s,e){if(fl.has(`${s}.${e}`))return fl.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=Qm(Hm(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return fl.set(`${s}.${e}`,n),n}function yI(s){const e=Qm(`0x${s.substring(4)}`).substring(26);return wI(`0x${e}`)}async function bI({hash:s,signature:e}){const t=Go(s)?s:bh(s),{secp256k1:i}=await Vo(async()=>{const{secp256k1:o}=await import("./secp256k1-D-G9AbtW.js");return{secp256k1:o}},__vite__mapDeps([4,1,2,5,6,7,8,9,10]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:c,s:h,v:u,yParity:d}=e,p=Number(d??u),g=_d(p);return new i.Signature(yh(c),yh(h)).addRecoveryBit(g)}const o=Go(e)?e:bh(e),a=R0(`0x${o.slice(130)}`),l=_d(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(l)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function _d(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function vI({hash:s,signature:e}){return yI(await bI({hash:s,signature:e}))}var Zm=cv(),II={};const Jm=":";function On(s){const[e,t]=s.split(Jm);return{namespace:e,reference:t}}function EI(s){const[e,t,i]=s.split(Jm);return{namespace:e,reference:t,address:i}}function Xm(s,e){return s.includes(":")?[s]:e.chains||[]}const AI="ReactNative",fs={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},NI="js";function Ac(){return typeof _.process<"u"&&typeof _.process.versions<"u"&&typeof _.process.versions.node<"u"}function Gi(){return!Wi()&&!!zc()&&navigator.product===AI}function _I(){return Gi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="android"}function CI(){return Gi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="ios"}function pa(){return!Ac()&&!!zc()&&!!Wi()}function ga(){return Gi()?fs.reactNative:Ac()?fs.node:pa()?fs.browser:fs.unknown}function Cd(){var s;try{return Gi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Application)<"u"?(s=_.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function SI(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function ew(){return Im()||{name:"",description:"",url:"",icons:[""]}}function $I(){if(ga()===fs.reactNative&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"){const{OS:t,Version:i}=_.global.Platform;return[t,i].join("-")}const s=Pm();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function PI(){var s;const e=ga();return e===fs.browser?[e,((s=Em())==null?void 0:s.host)||"unknown"].join(":"):e}function tw(s,e,t){const i=$I(),r=PI();return[[s,e].join("-"),[NI,t].join("-"),i,r].join("/")}function TI({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:l}){const c=t.split("?"),h=tw(s,e,i),u={auth:r,ua:h,projectId:n,useOnCloseEvent:o,packageName:l||void 0,bundleId:a||void 0},d=SI(c[1]||"",u);return c[0]+"?"+d}function dr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function sw(s){return Object.fromEntries(s.entries())}function iw(s){return new Map(Object.entries(s))}function rr(s=E.FIVE_MINUTES,e){const t=E.toMiliseconds(s||E.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,l)=>{if(o)return a(o);n=setTimeout(()=>{const c=new Error(e);o=Promise.reject(c),l(c)},t),i=a,r=l})}}function ki(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function rw(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.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: ${s}`)}function MI(s){return rw("topic",s)}function OI(s){return rw("id",s)}function nw(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function ut(s,e){return E.fromMiliseconds(Date.now()+E.toMiliseconds(s))}function Si(s){return Date.now()>=E.toMiliseconds(s)}function Ie(s,e){return`${s}${e?`:${e}`:""}`}function ic(s=[],e=[]){return[...new Set([...s,...e])]}async function xI({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=DI(n,s,e),a=ga();if(a===fs.browser){if(!((i=Wi())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}kI(o)}else a===fs.reactNative&&typeof(_.global==null?void 0:_.global.Linking)<"u"&&await _.global.Linking.openURL(o)}catch(r){console.error(r)}}function DI(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${UI(i,!0)}`}else r=`${r}/wc?${i}`;return r}function kI(s){let e="_self";LI()?e="_top":(RI()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function jI(s,e){let t="";try{if(pa()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Sd(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function $d(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function _u(){return typeof _.process<"u"&&II.IS_VITEST==="true"}function RI(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function LI(){try{return window.self!==window.top}catch{return!1}}function UI(s,e=!1){const t=_.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function ow(s){return _.Buffer.from(s,"base64").toString("utf-8")}function zI(s){return new Promise(e=>setTimeout(e,s))}function Yo(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function FI(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Hc(s,...e){if(!FI(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Cu(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Yo(s.outputLen),Yo(s.blockLen)}function Rn(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function aw(s,e){Hc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Oa=BigInt(2**32-1),Pd=BigInt(32);function qI(s,e=!1){return e?{h:Number(s&Oa),l:Number(s>>Pd&Oa)}:{h:Number(s>>Pd&Oa)|0,l:Number(s&Oa)|0}}function BI(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=qI(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const HI=(s,e,t)=>s<<t|e>>>32-t,WI=(s,e,t)=>e<<t|s>>>32-t,VI=(s,e,t)=>e<<t-32|s>>>64-t,KI=(s,e,t)=>s<<t-32|e>>>64-t,Ur=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function GI(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function ml(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Bs(s,e){return s<<32-e|s>>>e}const Td=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function YI(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Md(s){for(let e=0;e<s.length;e++)s[e]=YI(s[e])}function QI(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Ln(s){return typeof s=="string"&&(s=QI(s)),Hc(s),s}let Su=class{clone(){return this._cloneInto()}};function cw(s){const e=i=>s().update(Ln(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function fa(s=32){if(Ur&&typeof Ur.getRandomValues=="function")return Ur.getRandomValues(new Uint8Array(s));if(Ur&&typeof Ur.randomBytes=="function")return Ur.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const lw=[],hw=[],uw=[],ZI=BigInt(0),oo=BigInt(1),JI=BigInt(2),XI=BigInt(7),e1=BigInt(256),t1=BigInt(113);for(let s=0,e=oo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],lw.push(2*(5*i+t)),hw.push((s+1)*(s+2)/2%64);let r=ZI;for(let n=0;n<7;n++)e=(e<<oo^(e>>XI)*t1)%e1,e&JI&&(r^=oo<<(oo<<BigInt(n))-oo);uw.push(r)}const[s1,i1]=BI(uw,!0),Od=(s,e,t)=>t>32?VI(s,e,t):HI(s,e,t),xd=(s,e,t)=>t>32?KI(s,e,t):WI(s,e,t);function r1(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,l=(o+2)%10,c=t[l],h=t[l+1],u=Od(c,h,1)^t[a],d=xd(c,h,1)^t[a+1];for(let p=0;p<50;p+=10)s[o+p]^=u,s[o+p+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=hw[o],l=Od(r,n,a),c=xd(r,n,a),h=lw[o];r=s[h],n=s[h+1],s[h]=l,s[h+1]=c}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=s1[i],s[1]^=i1[i]}t.fill(0)}let n1=class dw extends Su{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Yo(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=GI(this.state)}keccak(){Td||Md(this.state32),r1(this.state32,this.rounds),Td||Md(this.state32),this.posOut=0,this.pos=0}update(e){Rn(this);const{blockLen:t,state:i}=this;e=Ln(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Rn(this,!1),Hc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Yo(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(aw(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:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new dw(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const o1=(s,e,t)=>cw(()=>new n1(e,s,t)),a1=o1(1,136,256/8),c1="https://rpc.walletconnect.org/v1";function pw(s){const e=`Ethereum Signed Message:
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/solanaEmbed.esm-Mnq6o_qa.js","main.js","main.css","assets/index.es-CBqWEk7T.js","assets/index-Czf_KRcW.js","assets/index-VWaDGczM.js","assets/secp256k1-CBh6eQLF.js","assets/util-C_16CLeU.js","assets/wallets-B2cUxj0w.js","assets/signer-BRan8q4C.js","assets/chain-Du7paeNG.js","assets/secp256k1-OI4v3wvK.js","assets/basic-C5fzEsEe.js","assets/index-CfdmPAak.js","assets/browser-CeceZ__e.js","assets/w3m-modal-DpvEw1mA.js"])))=>i.map(i=>d[i]);
2
+ var nv=Object.defineProperty;var ov=(s,e,t)=>e in s?nv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Nt=(s,e,t)=>ov(s,typeof e!="symbol"?e+"":e,t);import{I as av,P as ei,f as _,_ as Vo,J as cv,V as dh,L as ph,W as lv,O as id,y as rd,B as Pa,Q as hv,H as gh,R as nd,G as Mi,U as uv,X as dv,C as vm,Y as pv}from"../main.js";import{a as gv}from"./util-C_16CLeU.js";import{g as fv}from"./wallets-B2cUxj0w.js";import{i as fh,d as mv,a as wv}from"./signer-BRan8q4C.js";import{e as kt,I as bs,d as Di,s as wi,a as Sr,c as Im,b as Em,k as Am,f as Nm,g as _m,h as bc,i as Ge,t as Ae,C as Cm,j as Sm,l as jn,m as Mn,r as yv,n as Gt,o as gs,p as st,q as $r,u as od,v as bv,w as vv,x as ca,y as Iv,z as yi,A as Au,E as Ne,B as qe,D as Wn,F as Vn,G as Wi,H as Kn,P as vc,Q as $m,J as Pm,K as Ev,L as vt,M as qt,N as tt}from"./index.es-CBqWEk7T.js";import{a3 as E,a4 as Tm,a5 as Vi,a6 as zc,a7 as Mm,f as Av,a1 as ad,a2 as hl,t as cd}from"./index-Czf_KRcW.js";class jt extends Error{constructor(e,t){super(e),this.error=t}}class Ki extends jt{constructor(){super(...arguments),this.name="WalletNotReadyError"}}class Nv extends jt{constructor(){super(...arguments),this.name="WalletLoadError"}}class Cn extends jt{constructor(){super(...arguments),this.name="WalletConfigError"}}class Fc extends jt{constructor(){super(...arguments),this.name="WalletConnectionError"}}class Om extends jt{constructor(){super(...arguments),this.name="WalletDisconnectedError"}}class la extends jt{constructor(){super(...arguments),this.name="WalletDisconnectionError"}}class Ps extends jt{constructor(){super(...arguments),this.name="WalletAccountError"}}class Pr extends jt{constructor(){super(...arguments),this.name="WalletPublicKeyError"}}class Fe extends jt{constructor(){super(...arguments),this.name="WalletNotConnectedError"}}class ur extends jt{constructor(){super(...arguments),this.name="WalletSendTransactionError"}}class et extends jt{constructor(){super(...arguments),this.name="WalletSignTransactionError"}}class ha extends jt{constructor(){super(...arguments),this.name="WalletSignMessageError"}}class ld extends jt{constructor(){super(...arguments),this.name="WalletSignInError"}}class _v extends jt{constructor(){super(...arguments),this.name="WalletWindowClosedError"}}var ne;(function(s){s.Installed="Installed",s.NotDetected="NotDetected",s.Loadable="Loadable",s.Unsupported="Unsupported"})(ne||(ne={}));class xm extends av{get connected(){return!!this.publicKey}async autoConnect(){await this.connect()}async prepareTransaction(e,t,i={}){const r=this.publicKey;if(!r)throw new Fe;return e.feePayer=e.feePayer||r,e.recentBlockhash=e.recentBlockhash||(await t.getLatestBlockhash({commitment:i.preflightCommitment,minContextSlot:i.minContextSlot})).blockhash,e}}function ua(s){if(typeof window>"u"||typeof document>"u")return;const e=[];function t(){if(s())for(const n of e)n()}const i=setInterval(t,1e3);e.push(()=>clearInterval(i)),document.readyState==="loading"&&(document.addEventListener("DOMContentLoaded",t,{once:!0}),e.push(()=>document.removeEventListener("DOMContentLoaded",t))),document.readyState!=="complete"&&(window.addEventListener("load",t,{once:!0}),e.push(()=>window.removeEventListener("load",t))),t()}function pi(s){return"version"in s}class Nu extends xm{async sendTransaction(e,t,i={}){let r=!0;try{if(pi(e)){if(!this.supportedTransactionVersions)throw new ur("Sending versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(e.version))throw new ur(`Sending transaction version ${e.version} isn't supported by this wallet`);try{e=await this.signTransaction(e);const n=e.serialize();return await t.sendRawTransaction(n,i)}catch(n){throw n instanceof et?(r=!1,n):new ur(n==null?void 0:n.message,n)}}else try{const{signers:n,...o}=i;e=await this.prepareTransaction(e,t,o),n!=null&&n.length&&e.partialSign(...n),e=await this.signTransaction(e);const a=e.serialize();return await t.sendRawTransaction(a,o)}catch(n){throw n instanceof et?(r=!1,n):new ur(n==null?void 0:n.message,n)}}catch(n){throw r&&this.emit("error",n),n}}async signAllTransactions(e){for(const i of e)if(pi(i)){if(!this.supportedTransactionVersions)throw new et("Signing versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(i.version))throw new et(`Signing transaction version ${i.version} isn't supported by this wallet`)}const t=[];for(const i of e)t.push(await this.signTransaction(i));return t}}class da extends Nu{}const Oi="solana:signAndSendTransaction",ul="solana:signIn",io="solana:signMessage",Mt="solana:signTransaction",Dm="standard:connect",hd="standard:disconnect",km="standard:events";function Cv(s){return Dm in s.features&&km in s.features&&(Oi in s.features||Mt in s.features)}var Ko;(function(s){s.Mainnet="mainnet-beta",s.Testnet="testnet",s.Devnet="devnet"})(Ko||(Ko={}));const Sv="Bitget";class $v extends da{constructor(e={}){super(),this.name=Sv,this.url="https://web3.bitget.com",this.icon="data:image/svg+xml;base64,PHN2ZyBmaWxsPSJub25lIiBoZWlnaHQ9IjI1NiIgdmlld0JveD0iMCAwIDI1NiAyNTYiIHdpZHRoPSIyNTYiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxmaWx0ZXIgaWQ9ImEiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiIgZmlsdGVyVW5pdHM9InVzZXJTcGFjZU9uVXNlIiBoZWlnaHQ9IjQ1MS40MzEiIHdpZHRoPSI1NjkuNTU4IiB4PSItOTAuMjQxMSIgeT0iLTY5LjczNjkiPjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+PGZlQmxlbmQgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiBtb2RlPSJub3JtYWwiIHJlc3VsdD0ic2hhcGUiLz48ZmVHYXVzc2lhbkJsdXIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIgc3RkRGV2aWF0aW9uPSI0OS4yMzA4Ii8+PC9maWx0ZXI+PGZpbHRlciBpZD0iYiIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGhlaWdodD0iMzcxLjUwNyIgd2lkdGg9IjM1MS41OTYiIHg9Ii0xNjAuNTExIiB5PSItMTY1Ljk4NyI+PGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz48ZmVCbGVuZCBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIG1vZGU9Im5vcm1hbCIgcmVzdWx0PSJzaGFwZSIvPjxmZUdhdXNzaWFuQmx1ciByZXN1bHQ9ImVmZmVjdDFfZm9yZWdyb3VuZEJsdXJfMjAzNV8xMTA2IiBzdGREZXZpYXRpb249IjQ5LjIzMDgiLz48L2ZpbHRlcj48ZmlsdGVyIGlkPSJjIiBjb2xvci1pbnRlcnBvbGF0aW9uLWZpbHRlcnM9InNSR0IiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgaGVpZ2h0PSI0MjQuNDUyIiB3aWR0aD0iNDQ0Ljg1MSIgeD0iLTI0MS4wNzgiIHk9IjY3LjY0MiI+PGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz48ZmVCbGVuZCBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIG1vZGU9Im5vcm1hbCIgcmVzdWx0PSJzaGFwZSIvPjxmZUdhdXNzaWFuQmx1ciByZXN1bHQ9ImVmZmVjdDFfZm9yZWdyb3VuZEJsdXJfMjAzNV8xMTA2IiBzdGREZXZpYXRpb249IjQ5LjIzMDgiLz48L2ZpbHRlcj48ZmlsdGVyIGlkPSJkIiBjb2xvci1pbnRlcnBvbGF0aW9uLWZpbHRlcnM9InNSR0IiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgaGVpZ2h0PSIzODUuMTA1IiB3aWR0aD0iNDMwLjE5MSIgeD0iLTIwLjM5NjgiIHk9Ii0yNDIuNzU4Ij48ZmVGbG9vZCBmbG9vZC1vcGFjaXR5PSIwIiByZXN1bHQ9IkJhY2tncm91bmRJbWFnZUZpeCIvPjxmZUJsZW5kIGluPSJTb3VyY2VHcmFwaGljIiBpbjI9IkJhY2tncm91bmRJbWFnZUZpeCIgbW9kZT0ibm9ybWFsIiByZXN1bHQ9InNoYXBlIi8+PGZlR2F1c3NpYW5CbHVyIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIvPjwvZmlsdGVyPjxjbGlwUGF0aCBpZD0iZSI+PHBhdGggZD0ibTAgMGgyNTZ2MjU2aC0yNTZ6Ii8+PC9jbGlwUGF0aD48ZyBjbGlwLXBhdGg9InVybCgjZSkiPjxwYXRoIGQ9Im0wIDBoMjU2djI1NmgtMjU2eiIgZmlsbD0iIzU0ZmZmNSIvPjxnIGZpbHRlcj0idXJsKCNhKSI+PHBhdGggZD0ibTEzLjQ4MDYgMTk4LjYwNWMtNDIuODA4MiAxMjAuNDM4IDE4Ni4xODA0IDg2LjQyMiAzMDYuMDI2NCA1NC4zNTkgMTIyLjY1OC00MC43MDUgMzcuODc5LTIyMC4xMzcxLTUwLjA5Mi0yMjQuMTA4Mi04Ny45NzItMy45NzExIDEwLjkwNyA4Mi45NjgyLTYzLjgyIDEwNy44MDAyLTc0LjcyNyAyNC44MzEtMTM4LjYwNDMtODguNTk3Ny0xOTIuMTE0NCA2MS45NDl6IiBmaWxsPSIjZmZmIi8+PC9nPjxnIGZpbHRlcj0idXJsKCNiKSI+PHBhdGggZD0ibTg1LjUxMTgtNDUuODIyNWMtMjIuNDU1Ni02MS4zNTM1LTEwMi40MzA3IDIxLjgyNzItMTM5LjYxMTMgNzEuMDg2OC0zNS40NjU3IDUzLjU4MzYgNTcuMTA4ODcgOTkuODg3NyA5My40MjAzIDc0Ljc3MjcgMzYuMzExNS0yNS4xMTQzLTMxLjU0NjMyLTMwLjAwMDctOS45NS02Mi42NTg1IDIxLjU5NjMtMzIuNjU3NzQgODQuMjEwMi02LjUwOSA1Ni4xNDEtODMuMjAxeiIgZmlsbD0iIzAwZmZmMCIgZmlsbC1vcGFjaXR5PSIuNjciLz48L2c+PGcgZmlsdGVyPSJ1cmwoI2MpIj48cGF0aCBkPSJtOTYuNDc5NiAyMjUuNDI0Yy0zMC42Mjk0LTEwMy4wNjEtMTYyLjU2MTQtNDguNzg3LTIyNC42OTg2LTguNzY3LTU5Ljc3MSA0Ny4zODUgODIuMTQ3OSAxODMuNjkxIDE0MS4wOTE1IDE3Ni43MTkgNTguOTQzNi02Ljk3My00Ny4yODQzLTY2LjMxMS0xMC44ODU0OC05NS4yMDYgMzYuMzk4NzgtMjguODk0IDEzMi43Nzg5OCA1Ni4wNzkgOTQuNDkyNTgtNzIuNzQ2eiIgZmlsbD0iIzlkODFmZiIvPjwvZz48ZyBmaWx0ZXI9InVybCgjZCkiPjxwYXRoIGQ9Im0yODIuMTItMTA3LjM1M2MtNjYuMDczLTc4LjY3OC0xNjAuNjU3LTEzLjYxNy0xOTkuNjkwNCAyOC43NDgzLTM0LjE1NTcgNDcuOTYwMSAxNDEuODQ1NCAxMzUuODM1OSAxOTAuNjkxNCAxMjAuNzc2MSA0OC44NDctMTUuMDU5OS02Ni42MDktNDYuMjIxNzgtNDUuODI0LTc1LjQ1OTMgMjAuNzg1LTI5LjIzNzYgMTM3LjQxNSAyNC4yODIyNCA1NC44MjMtNzQuMDY1MXoiIGZpbGw9IiM0ZDk0ZmYiLz48L2c+PHBhdGggY2xpcC1ydWxlPSJldmVub2RkIiBkPSJtOTMuMTg5IDE1Mi44MzZoNDMuNDg1bC00OS40NjU0LTQ5Ljc4NSA1MC4xMDE0LTQ5Ljc4NDcgMTMuNjQ1LTEzLjI2NjNoLTQ1LjEzNmwtNTcuNDgzMSA1Ny43NzczYy0yLjkwMSAyLjkxMTctMi44ODYxIDcuNjI0Ny4wMjk3IDEwLjUyMTd6bTI2LjE0MS00OS42NjhoLS4zMzVsLjMzMS0uMDA0em0wIDAgNDkuNDYxIDQ5Ljc4MS01MC4xMDEgNDkuNzg1LTEzLjY0NSAxMy4yNjZoNDUuMTM1bDU3LjQ4NC01Ny43NzRjMi45MDEtMi45MTIgMi44ODYtNy42MjQtLjAzLTEwLjUyMWwtNDQuODIzLTQ0LjUzN3oiIGZpbGw9IiMwMDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ne.Unsupported&&ua(()=>{var t,i;return(i=(t=window.bitkeep)==null?void 0:t.solana)!=null&&i.isBitKeep?(this._readyState=ne.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Installed)throw new Ki;this._connecting=!0;const e=window.bitkeep.solana;let t;try{t=await e.getAccount()}catch(r){throw new Ps(r==null?void 0:r.message,r)}let i;try{i=new ei(t)}catch(r){throw new Pr(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch(t){this.emit("error",new la(t==null?void 0:t.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signTransaction(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signAllTransactions(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Fe;try{const{signature:i}=await t.signMessage(e);return i}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const Pv="Clover";class Tv extends da{constructor(e={}){super(),this.name=Pv,this.url="https://clv.org",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDgiIGhlaWdodD0iNDgiIHZpZXdCb3g9IjAgMCA0OCA0OCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTM2LjQ4IDBIMTEuNTJDNS4xNTc2OCAwIDAgNS4xNTc2OCAwIDExLjUyVjM2LjQ4QzAgNDIuODQyMyA1LjE1NzY4IDQ4IDExLjUyIDQ4SDM2LjQ4QzQyLjg0MjMgNDggNDggNDIuODQyMyA0OCAzNi40OFYxMS41MkM0OCA1LjE1NzY4IDQyLjg0MjMgMCAzNi40OCAwWiIgZmlsbD0idXJsKCNwYWludDBfbGluZWFyXzc5MTBfMTYzMzUxKSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTI0LjAwMDYgMzkuMzYwNkMzMi40ODM3IDM5LjM2MDYgMzkuMzYwNiAzMi40ODM3IDM5LjM2MDYgMjQuMDAwNkMzOS4zNjA2IDE1LjUxNzUgMzIuNDgzNyA4LjY0MDYyIDI0LjAwMDYgOC42NDA2MkMxNS41MTc1IDguNjQwNjIgOC42NDA2MiAxNS41MTc1IDguNjQwNjIgMjQuMDAwNkM4LjY0MDYyIDMyLjQ4MzcgMTUuNTE3NSAzOS4zNjA2IDI0LjAwMDYgMzkuMzYwNlpNMjEuMjg5OSAxNS44Njg4SDI2LjcxMVYyMS4zNDdIMjEuMjkwNFYyNi42NTRIMjYuNzExVjMyLjEzMjJIMjEuMjg5OVYyNi44MjUySDE1Ljg2OTNWMjEuMzQ3SDIxLjI4OTlWMTUuODY4OFpNMjYuNzEyIDIxLjM0N0gzMi4xMzMxVjI2LjgyNTJIMjYuNzEyVjIxLjM0N1oiIGZpbGw9ImJsYWNrIi8+CjxkZWZzPgo8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfNzkxMF8xNjMzNTEiIHgxPSI0OCIgeTE9Ii0xLjQzMDUxZS0wNiIgeDI9IjEuNDMwNTFlLTA2IiB5Mj0iNDgiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KPHN0b3Agc3RvcC1jb2xvcj0iI0E5RkZFMCIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM4NkQ1RkYiLz4KPC9saW5lYXJHcmFkaWVudD4KPC9kZWZzPgo8L3N2Zz4=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ne.Unsupported&&ua(()=>{var t;return(t=window.clover_solana)!=null&&t.isCloverWallet?(this._readyState=ne.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Installed)throw new Ki;this._connecting=!0;const e=window.clover_solana;let t;try{t=await e.getAccount()}catch(r){throw new Ps(r==null?void 0:r.message,r)}let i;try{i=new ei(t)}catch(r){throw new Pr(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){this._wallet&&(this._wallet=null,this._publicKey=null),this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signTransaction(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signAllTransactions(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Fe;try{const{signature:i}=await t.signMessage(e);return Uint8Array.from(i)}catch(i){throw new ha(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}function Mv(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<s.length;c++){const h=s.charAt(c),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=c}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,u=0,d=0;const p=c.length;for(;d!==p&&c[d]===0;)d++,h++;const g=(p-d)*n+1>>>0,f=new Uint8Array(g);for(;d!==p;){let m=c[d],b=0;for(let I=g-1;(m!==0||b<u)&&I!==-1;I--,b++)m+=256*f[I]>>>0,f[I]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");u=b,d++}let y=g-u;for(;y!==g&&f[y]===0;)y++;let w=i.repeat(h);for(;y<g;++y)w+=s.charAt(f[y]);return w}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;c[h]===i;)u++,h++;const p=(c.length-h)*r+1>>>0,g=new Uint8Array(p);for(;h<c.length;){const m=c.charCodeAt(h);if(m>255)return;let b=e[m];if(b===255)return;let I=0;for(let N=p-1;(b!==0||I<d)&&N!==-1;N--,I++)b+=t*g[N]>>>0,g[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=I,h++}let f=p-d;for(;f!==p&&g[f]===0;)f++;const y=new Uint8Array(u+(p-f));let w=u;for(;f!==p;)y[w++]=g[f++];return y}function l(c){const h=a(c);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:l}}var Ov="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const dl=Mv(Ov),xv="Coin98";class Dv extends da{constructor(e={}){super(),this.name=xv,this.url="https://coin98.com",this.icon="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA3NiA3NSI+CiAgPGRlZnM+CiAgICA8bGluZWFyR3JhZGllbnQgaWQ9ImEiIHgxPSIxMDEuNjgxJSIgeDI9Ii0xLjU1NyUiIHkxPSIxNS4yNjglIiB5Mj0iODQuOTE3JSI+CiAgICAgIDxzdG9wIG9mZnNldD0iMCUiIHN0b3AtY29sb3I9IiNGMUQ5NjEiLz4KICAgICAgPHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjQ0RBMTQ2Ii8+CiAgICA8L2xpbmVhckdyYWRpZW50PgogIDwvZGVmcz4KICA8ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgPHJlY3Qgd2lkdGg9Ijc1IiBoZWlnaHQ9Ijc1IiBmaWxsPSIjMDAwIiByeD0iMTYiLz4KICAgIDxwYXRoIGZpbGw9InVybCgjYSkiIGZpbGwtcnVsZT0ibm9uemVybyIgZD0iTTYxLjQ0IDBhMTMuNzE0IDEzLjcxNCAwIDAgMSA5LjY4IDQuMDEgMTMuNjYxIDEzLjY2MSAwIDAgMSA0LjAwOCA5LjY2OHY0Ny42NDZhMTMuNjYgMTMuNjYgMCAwIDEtNC4wMDcgOS42NjZBMTMuNzEzIDEzLjcxMyAwIDAgMSA2MS40NCA3NUgxMy42ODZhMTMuNzEzIDEzLjcxMyAwIDAgMS05LjY4LTQuMDFBMTMuNjYgMTMuNjYgMCAwIDEgMCA2MS4zMjRWMTMuNjc4YzAtMy42MjUgMS40NC03LjEwMiA0LjAwNy05LjY2N0ExMy43MTQgMTMuNzE0IDAgMCAxIDEzLjY4NyAwWk0yMC4wNjMgNDYuMjMxaC00LjgyNWExMC4wMzIgMTAuMDMyIDAgMCAwIDIuOTQ2IDcuMDg2IDEwLjA3IDEwLjA3IDAgMCAwIDcuMSAyLjk0MiAxMC4wNjUgMTAuMDY1IDAgMCAwIDcuMTA4LTIuOTM1IDEwLjAzIDEwLjAzIDAgMCAwIDIuOTQ2LTcuMDkzaC00LjgyNGE1LjIwNyA1LjIwNyAwIDAgMS0xLjUzIDMuNjg4IDUuMjI1IDUuMjI1IDAgMCAxLTMuNjk2IDEuNTI4IDUuMjM0IDUuMjM0IDAgMCAxLTMuNjk1LTEuNTI4IDUuMjEzIDUuMjEzIDAgMCAxLTEuNTMtMy42ODhaTTU0LjMzIDMzLjcxNmExMS43NjMgMTEuNzYzIDAgMCAwLTEyLjc5OSAyLjUzOEExMS42OTcgMTEuNjk3IDAgMCAwIDM4Ljk5IDQ5LjAzYTExLjcyMyAxMS43MjMgMCAwIDAgNC4zMjggNS4yNTkgMTEuNzU3IDExLjc1NyAwIDAgMCA2LjUyNiAxLjk3IDExLjc2NiAxMS43NjYgMCAwIDAgOC4yOS0zLjQzNSAxMS43MiAxMS43MiAwIDAgMCAzLjQ0Mi04LjI3NCAxMS43MDIgMTEuNzAyIDAgMCAwLTEuOTc1LTYuNTE0IDExLjczNiAxMS43MzYgMCAwIDAtNS4yNjktNC4zMlptLTQuNDg4IDMuOTJhNi45MzcgNi45MzcgMCAwIDEgNC45IDIuMDI1IDYuOTEgNi45MSAwIDAgMSAyLjAyOCA0Ljg5MiA2Ljg5NyA2Ljg5NyAwIDAgMS0xLjE3IDMuODM0IDYuOTMyIDYuOTMyIDAgMCAxLTEwLjY0MyAxLjA0MiA2LjkwMiA2LjkwMiAwIDAgMS0xLjUtNy41MjIgNi45MDkgNi45MDkgMCAwIDEgMi41NDQtMy4xIDYuOTI4IDYuOTI4IDAgMCAxIDMuODQxLTEuMTY3Wm0uMTcgNC41NTJhMi40MzEgMi40MzEgMCAwIDAtMi4yNDEgMS4xNTQgMi40MTggMi40MTggMCAwIDAtLjM1NiAxLjI1NyAyLjM5NSAyLjM5NSAwIDAgMCAxLjYxOSAyLjI5djEuNzUzaDEuNjE4di0xLjc1NGEyLjQyNyAyLjQyNyAwIDAgMCAxLjU5NC0xLjk1IDIuNDE4IDIuNDE4IDAgMCAwLTEtMi4zMSAyLjQzMSAyLjQzMSAwIDAgMC0xLjIzNC0uNDRabS0yMC4yMi0yMi41NTJhMTEuNzYyIDExLjc2MiAwIDAgMC0xMi43OTYgMi41MzEgMTEuNjk3IDExLjY5NyAwIDAgMC0yLjU1NCAxMi43NjkgMTEuNzIzIDExLjcyMyAwIDAgMCA0LjMyIDUuMjYyIDExLjc1NyAxMS43NTcgMCAwIDAgMTQuODI1LTEuNDQ2IDExLjcxNyAxMS43MTcgMCAwIDAgMy40NDUtOC4yODQgMTEuNzAzIDExLjcwMyAwIDAgMC0xLjk3NC02LjUxMiAxMS43MzYgMTEuNzM2IDAgMCAwLTUuMjY2LTQuMzJabS00LjUxIDMuOTE3YTYuOTQ1IDYuOTQ1IDAgMCAxIDQuODk3IDIuMDI5IDYuOTE4IDYuOTE4IDAgMCAxIDIuMDMyIDQuODg2IDYuOTA2IDYuOTA2IDAgMCAxLTEuMTY4IDMuODQyIDYuOTQgNi45NCAwIDAgMS0xMC42NiAxLjA0OCA2LjkxMSA2LjkxMSAwIDAgMS0xLjUtNy41MzYgNi45MTggNi45MTggMCAwIDEgMi41NS0zLjEwMyA2LjkzNyA2LjkzNyAwIDAgMSAzLjg1LTEuMTY2Wm0yNC41Ni00LjgxYTEwLjA1OSAxMC4wNTkgMCAwIDAtNy4xMDMgMi45NCAxMC4wMiAxMC4wMiAwIDAgMC0yLjk0IDcuMDkgOS45IDkuOSAwIDAgMCAxLjIzIDQuNzk1IDEzLjU3NSAxMy41NzUgMCAwIDEgNC4yMTQtMi4zMjIgNS4wODIgNS4wODIgMCAwIDEtLjYyNS0yLjQ3NyA1LjIwNiA1LjIwNiAwIDAgMSAxLjUwMy0zLjczNiA1LjIyMyA1LjIyMyAwIDAgMSAzLjcyMi0xLjU1NCA1LjIzNCA1LjIzNCAwIDAgMSAzLjcyIDEuNTU0IDUuMjEzIDUuMjEzIDAgMCAxIDEuNTA1IDMuNzM2IDUuMjc5IDUuMjc5IDAgMCAxLS42MjMgMi40NzMgMTMuNTc0IDEzLjU3NCAwIDAgMSA0LjIxMyAyLjMyMiA5LjkwMyA5LjkwMyAwIDAgMCAxLjIzLTQuNzk1IDEwLjAzMiAxMC4wMzIgMCAwIDAtMi45NDYtNy4wODYgMTAuMDcgMTAuMDcgMCAwIDAtNy4xLTIuOTRabS0yMy43NSA3Ljk5aC0xLjYxN3YxLjc1YTIuNDE5IDIuNDE5IDAgMCAwLTEuNTgyIDIuNjg3IDIuNDE0IDIuNDE0IDAgMCAwIDIuMzkgMi4wMDYgMi40NSAyLjQ1IDAgMCAwIDEuNTU1LS41NzQgMi40MTQgMi40MTQgMCAwIDAtLjc0Ni00LjExOXYtMS43NVoiLz4KICA8L2c+Cjwvc3ZnPgo=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ne.Unsupported&&ua(()=>{var t;return(t=window.coin98)!=null&&t.sol?(this._readyState=ne.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){var e;return!!((e=this._wallet)!=null&&e.isConnected())}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Installed)throw new Ki;this._connecting=!0;const e=window.coin98.sol;let t;try{t=(await e.connect())[0]}catch(r){throw new Ps(r==null?void 0:r.message,r)}let i;try{i=new ei(t)}catch(r){throw new Pr(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch(t){this.emit("error",new la(t==null?void 0:t.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{const i=await t.request({method:"sol_sign",params:[e]}),r=new ei(i.publicKey),n=dl.decode(i.signature);return e.addSignature(r,_.Buffer.from(n)),e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Fe;try{const i=await t.request({method:"sol_signAllTransactions",params:[e]}),r=new ei(i.publicKey),n=i.signatures;return e.map((o,a)=>{const l=dl.decode(n[a]);return o.addSignature(r,_.Buffer.from(l)),o})}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Fe;try{const i=await t.request({method:"sol_signMessage",params:[e]});return dl.decode(i.signature)}catch(i){throw new ha(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const kv="Nightly";class jv extends da{constructor(){super(),this.name=kv,this.url="https://nightly.app",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iOTYiIGhlaWdodD0iOTYiIHZpZXdCb3g9IjAgMCA5NiA5NiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQ4IDk2Qzc0LjUwOTcgOTYgOTYgNzQuNTA5NyA5NiA0OEM5NiAyMS40OTAzIDc0LjUwOTcgMCA0OCAwQzIxLjQ5MDMgMCAwIDIxLjQ5MDMgMCA0OEMwIDc0LjUwOTcgMjEuNDkwMyA5NiA0OCA5NloiIGZpbGw9IiM2RDczRjgiLz4KPHBhdGggZD0iTTQ4IDg1LjYzNTZDNDggODUuNjM1NiA1Mi40NTMzIDg1LjYzNTYgNTUuNDQgODIuNTg2N0M1OC45MTU1IDc5LjI4MDEgNTcuMzUxMSA3NS40MzEyIDYyLjI3NTUgNzEuNDMxMkM2Ni45ODY2IDY3LjY0NDUgNzIuOTI0NCA3MC4zMzc5IDcyLjkyNDQgNzAuMzM3OUM3Ny4wMjIyIDYyLjEyNDUgNzQuNzkxMSA1Mi41NjkgNzQuNzkxMSA1Mi41NjlDODEuNzY4OCAzNC4yNTc5IDc1Ljk2NDQgMjEuMTU1NyA3NC40NDQ0IDE3LjM2MDFDNjkuNDQ4OCAyNC4zMzc5IDYzLjE5MTEgMjkuMTczNCA1NS43OTU1IDMyLjQwOUM1My4yMjY2IDMxLjcwNjggNTAuNTk1NSAzMS4zMzM0IDQ4IDMxLjM2MDFDNDUuNDEzMyAzMS4zMzM0IDQyLjc3MzMgMzEuNzA2OCA0MC4yMDQ0IDMyLjQwOUMzMi44MTc3IDI5LjE2NDUgMjYuNTUxMSAyNC4zMzc5IDIxLjU1NTUgMTcuMzYwMUMyMC4wMzU1IDIxLjE1NTcgMTQuMjMxMSAzNC4yNTc5IDIxLjIwODkgNTIuNTY5QzIxLjIwODkgNTIuNTY5IDE4Ljk3NzggNjIuMTI0NSAyMy4wNzU1IDcwLjMzNzlDMjMuMDc1NSA3MC4zMzc5IDI5LjAxMzMgNjcuNjQ0NSAzMy43MjQ0IDcxLjQzMTJDMzguNjU3NyA3NS40MzEyIDM3LjA4NDQgNzkuMjgwMSA0MC41NiA4Mi41ODY3QzQzLjU0NjYgODUuNjM1NiA0OCA4NS42MzU2IDQ4IDg1LjYzNTZaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNNDIuNDc5OSA2NS4yOThDNDIuMjkzMyA1OS4yMTggMzYuMzAyMSA1Ny4yNjI0IDMyLjIxMzMgNTkuODIyNEMzMi4yMTMzIDU5LjgyMjQgMzIuODUzMyA2Mi40MzU4IDM1LjgzOTkgNjMuNzUxM0MzOC4yNzU1IDY0LjgyNjkgMzkuMzI0NCA2My4zODY5IDQyLjQ3OTkgNjUuMjk4WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNMjIuNDk3NyAyMy4wOTM1QzIwLjA4ODggMzEuNTQ2OCAyMS4xMjg4IDQyLjI0MDIgMjQuOTMzMyA1MC4wMjY5QzI4LjgyNjYgNDcuMjcxMyAzMi45MTU1IDQzLjAxMzUgMzUuMDkzMyAzOC41MDY5QzI5Ljk2NDQgMzQuNzExMyAyNS42NjIyIDMxLjEwMjQgMjIuNDk3NyAyMy4wOTM1WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNTMuNTE5OSA2NS4yOThDNTMuNzA2NiA1OS4yMTggNTkuNjk3NyA1Ny4yNjI0IDYzLjc4NjYgNTkuODIyNEM2My43ODY2IDU5LjgyMjQgNjMuMTQ2NiA2Mi40MzU4IDYwLjE1OTkgNjMuNzUxM0M1Ny43MjQzIDY0LjgyNjkgNTYuNjc1NSA2My4zODY5IDUzLjUxOTkgNjUuMjk4WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNzMuNTAyMiAyMy4wOTM1Qzc1LjkxMTEgMzEuNTQ2OCA3NC44NzExIDQyLjI0MDIgNzEuMDY2NiA1MC4wMjY5QzY3LjE3MzMgNDcuMjcxMyA2My4wODQ0IDQzLjAxMzUgNjAuOTA2NiAzOC41MDY5QzY2LjAzNTUgMzQuNzExMyA3MC4zMzc3IDMxLjEwMjQgNzMuNTAyMiAyMy4wOTM1WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNDcuOTk5OSA4NS4zMDY5QzUwLjE0MDQgODUuMzA2OSA1MS44NzU1IDgzLjc3ODcgNTEuODc1NSA4MS44OTM2QzUxLjg3NTUgODAuMDA4NCA1MC4xNDA0IDc4LjQ4MDIgNDcuOTk5OSA3OC40ODAyQzQ1Ljg1OTUgNzguNDgwMiA0NC4xMjQ0IDgwLjAwODQgNDQuMTI0NCA4MS44OTM2QzQ0LjEyNDQgODMuNzc4NyA0NS44NTk1IDg1LjMwNjkgNDcuOTk5OSA4NS4zMDY5WiIgZmlsbD0iIzdCODFGOSIvPgo8L3N2Zz4K",this.supportedTransactionVersions=new Set(["legacy",0]),this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.NotDetected,this._connecting=!1,this._publicKey=null,this._wallet=null,this._readyState!==ne.Unsupported&&ua(()=>{var e;return(e=window==null?void 0:window.nightly)!=null&&e.solana?(this._readyState=ne.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get connecting(){return this._connecting}get readyState(){return this._readyState}get publicKey(){return this._publicKey}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Installed)throw new Ki;this._connecting=!0;const e=window.nightly.solana;try{await e.connect()}catch(i){throw new Fc(i==null?void 0:i.message,i)}if(e.publicKey.toString()==="11111111111111111111111111111111")throw new Ps;let t;try{t=new ei(e.publicKey.toBytes())}catch(i){throw new Pr(i==null?void 0:i.message,i)}this._wallet=e,this._publicKey=t,this.emit("connect",t)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch{this.emit("error",new Om)}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signTransaction(e)}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signAllTransactions(e)}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Fe;try{return t.signMessage(new TextDecoder().decode(e))}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const ud="solana:mainnet",Rv="solana:devnet",Lv="solana:testnet",Uv="solana:localnet",zv="Solong";class Fv extends Nu{constructor(e={}){super(),this.name=zv,this.url="https://solongwallet.io",this.icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAGlklEQVR4Ae3bA5DsyhfH8TNr49r2/du2bdu2bdu2zcdNrm3b9toz533rvctUn3Umk9p01WfdvVW/6nROBxJVS1rSkpa0pCUtaUlLWtKSpl4VXos3GJ4sujQFuUKfWl+qT730arzB8Ex9YksKcgXjFOCVeIPhBYydB8mawQ+yiGC8n0EN6zAVcgXhpQjoq1DDdsyDAAB9Pwo1HMC9INk0FIM8Bt1Qh9WohQQCvD+BtEMdtmC8I7y5aIE67MV0SBwDvB3qsE/UHwMJIpC/QB1OYiLEEeCPoQ7nMRcSwwDrao3Zl8aTIEGEUYlL0IAMXuQOr66UvsegDm+ExDJAPNiafSg0AlyIbmjAWX1aQzEkiH6T0QkNaEdpnAN8NNRhPcSF9e9el2ebBhyAuNBvGtLQgIuQOAd4D6jDMRQbM3AmOqEBDfq0xjJIEP3GohkakEFVjAP0y401sAsLnAE+pb6EsC5AA9J4sHsG+kX0PQR1eFJ8AwTWQh0+DjFm4a1Qh2/AOoz/BHX4ZdwD/CDU4aioX2GUMW+AOnB2bqiBBDHe86EOTYw5GRKJwQ/ijUM91OGTxgysxSmowzeNw7j08m5DHX4l7Igg2TY0g9hbLBZ+f7oxC98CdWjDvYzD+MVQh07GfEQsZyDgVWA71OGvorfnQQCAcqaYUFZDHW6j/itAoB70GcergzqsEa0rhGTTEA7mP0koK4xdyeOMmvBBhJU2zsjPMw7lu9O3zShpXheHk4hhcZ4w26AOG4RSxDiUfwZ12KdPqy+FBDHeV6EOZxizIg6HsMGbiQ5jdjzBXRfeefGg3tgbv9BYC0fhZE7sjUMY9Pf9rdcI5XtQh39BjBA/C3VYnM0zcgiDek+GOhzh93mQoMs7kIxze/eMhnxIEOPNM9bcFtTEeAb6I419axu/m2CsgxU4Aw1A/UxIUM/bO/9+cVkDDd5x42x8N1iH8Taow0NhHcZLoQ5Pi/MMzDMW+DTu7g6vIY9AdkAdHmaUMyn6roA6PD22AeLB6DbWplHG7LubfY+kfiIkiH5T0AJ1uFtMA1xUzOc1UIclzvCeXF+o7DygDlvds29RgVVzYj+K4xhgEX4NdcjgecE++rSL+ZdLmIxRB77Ose7l4XPIQB3eF8M60C/n8++ghltE/QLIFfqUiyUE8kOoYSW7jmLIFXeN4X0NaajDDlG/NG6XswrxKdxu+G/weh27j3wCej9uN9zEOjc3sObl4S243XBLhDfWE0mAMQjwZfhxDng7pG/8Sj4/ER/Gd/BdfBhPRGW2A/wxNAfcBOnFCHwZZ6GGs/gqapMAb/QEnIT20Uk8IQkQeB7aof3UihcM9wDvhyboANHXv1+IdWBOB2hsIftto+iSPEif8aGPcjrA50GHyPMiOIT9B/N5apaMgQT8D2poxMdwt8s+hkao4X9ZDxBTIdHwy/h8AeqQxhMhAU9BB9ThPMqHTYCYjU6owy3uPstSfL4Z6uZPC+Mk8gOomz8DEg3vXshAHb4MMXwZarhXGDPwa739w2j48623BPAniOFPUMPsMAL8INTw9AgDrLZOCmjFPEjA3WD1aUJVGAG+CGr4ECRCy6GGg3iyaF0+n/PwFByEGpaJ+qkw1sB7QA3/hUTozdBetFymvXhTWGVMOc7bp36/FhKRamNW9dcxZmpZiI+32ad+vAQSoWejGzpAXXh22Fek3wY1rDD2kVnijR3ExYQMPgkJOUB/nFW0Is3vnw6JhlHX9a4N70Iq/ACBv0MNu7J9WxHw7jaA2deFOtw32zeVHtHLWvMN0dtSkOzwS3spYy7iH1hx2d/wYdyTvnkR3BdeQjjerVBDN14JyZIfQWH5RC7e1rw32npZV54LCc+SPD5/HgqYD3WW5+gTqt6X+rA4v0701hRkKF0+bL+HTM9Hgv/MHH60wyvHWigsafwA1ZAhMguLoL34kbDcQEI1uAH8mcbuxPHImf8i5EMGxqvER9EI7cUqVMTl0Y6HoxHaBzvxNkyC9EEe7oEv4Sy0D/YQ+IS4ver1JNT38z7sWnwbb8TT8Cg8Gs/Gu/Ar7EEXtI/2ud7Ni0GAYCbiJDQiazA57k9nTcdqaJb9UtSvitXbmjavCJ9AMzRkJ/B80boUJBLhDe7Nw1/QCR1i9fgKRg6HByzvjZ/hInQQMjiCT2PSMHxC1a/l8wvwGxyG9kEaW/EtPI4xiiE5JcLrd6PxcLwM78SH8EG8Fc/H/UUXVUByGh8SSYBJgEmASYCJJMAkwBi6A3xCqZhiBz8+AAAAAElFTkSuQmCC",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ne.Unsupported&&ua(()=>window.solong?(this._readyState=ne.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){var e;return!!((e=this._wallet)!=null&&e.currentAccount)}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Installed)throw new Ki;this._connecting=!0;const e=window.solong;let t;try{t=await e.selectAccount()}catch(r){throw new Ps(r==null?void 0:r.message,r)}let i;try{i=new ei(t)}catch(r){throw new Pr(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){this._wallet&&(this._wallet=null,this._publicKey=null),this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signTransaction(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const qv="Torus";class Bv extends da{constructor({params:e={showTorusButton:!1}}={params:{showTorusButton:!1}}){super(),this.name=qv,this.url="https://tor.us",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzMiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMyAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYuNSIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzAzNjRGRiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTExLjIxODYgOS40OTIxOUMxMC40NTM5IDkuNDkyMTkgOS44MzM5OCAxMC4xMTIxIDkuODMzOTggMTAuODc2OFYxMi40ODk4QzkuODMzOTggMTMuMjU0NSAxMC40NTM5IDEzLjg3NDQgMTEuMjE4NiAxMy44NzQ0SDEzLjY2ODRWMjIuODk3NkMxMy42Njg0IDIzLjY2MjMgMTQuMjg4MyAyNC4yODIyIDE1LjA1MyAyNC4yODIySDE2LjY2NkMxNy40MzA3IDI0LjI4MjIgMTguMDUwNiAyMy42NjIzIDE4LjA1MDYgMjIuODk3NlYxMi41MDE1QzE4LjA1MDYgMTIuNDk3NiAxOC4wNTA2IDEyLjQ5MzcgMTguMDUwNiAxMi40ODk4VjEwLjg3NjhDMTguMDUwNiAxMC4xMTIxIDE3LjQzMDcgOS40OTIxOSAxNi42NjYgOS40OTIxOUgxNS4wNTNIMTEuMjE4NloiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0yMS4zMzc2IDEzLjg3NDRDMjIuNTQ3NyAxMy44NzQ0IDIzLjUyODcgMTIuODkzNCAyMy41Mjg3IDExLjY4MzNDMjMuNTI4NyAxMC40NzMyIDIyLjU0NzcgOS40OTIxOSAyMS4zMzc2IDkuNDkyMTlDMjAuMTI3NSA5LjQ5MjE5IDE5LjE0NjUgMTAuNDczMiAxOS4xNDY1IDExLjY4MzNDMTkuMTQ2NSAxMi44OTM0IDIwLjEyNzUgMTMuODc0NCAyMS4zMzc2IDEzLjg3NDRaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.Loadable,this._connecting=!1,this._wallet=null,this._publicKey=null,this._params=e}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){var e;return!!((e=this._wallet)!=null&&e.isLoggedIn)}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Loadable)throw new Ki;this._connecting=!0;let e;try{e=(await Vo(async()=>{const{default:n}=await import("./solanaEmbed.esm-Mnq6o_qa.js");return{default:n}},__vite__mapDeps([0,1,2,3,4,5]))).default}catch(n){throw new Nv(n==null?void 0:n.message,n)}let t;try{t=window.torus||new e}catch(n){throw new Cn(n==null?void 0:n.message,n)}if(!t.isInitialized)try{await t.init(this._params)}catch(n){throw new Fc(n==null?void 0:n.message,n)}let i;try{i=await t.login()}catch(n){throw new Ps(n==null?void 0:n.message,n)}let r;try{r=new ei(i[0])}catch(n){throw new Pr(n==null?void 0:n.message,n)}this._wallet=t,this._publicKey=r,this.emit("connect",r)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{e.isLoggedIn&&await e.cleanUp()}catch(t){this.emit("error",new la(t==null?void 0:t.message,t))}}this.emit("disconnect")}async sendTransaction(e,t,i={}){try{const r=this._wallet;if(!r)throw new Fe;try{const{signers:n,...o}=i;e=await this.prepareTransaction(e,t,o),n!=null&&n.length&&e.partialSign(...n),o.preflightCommitment=o.preflightCommitment||t.commitment;const{signature:a}=await r.signAndSendTransaction(e,o);return a}catch(n){throw n instanceof jt?n:new ur(n==null?void 0:n.message,n)}}catch(r){throw this.emit("error",r),r}}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signTransaction(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signAllTransactions(e)||e}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Fe;try{return await t.signMessage(e)}catch(i){throw new ha(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}function pl(s){switch(s){case"processed":case"confirmed":case"finalized":case void 0:return s;case"recent":return"processed";case"single":case"singleGossip":return"confirmed";case"max":case"root":return"finalized";default:return}}const Hv="https://api.mainnet-beta.solana.com";function Wv(s){return s.includes(Hv)?ud:/\bdevnet\b/i.test(s)?Rv:/\btestnet\b/i.test(s)?Lv:/\blocalhost\b/i.test(s)||/\b127\.0\.0\.1\b/.test(s)?Uv:ud}var Ic;(function(s){s.Mainnet="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",s.Devnet="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",s.Deprecated_Mainnet="solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",s.Deprecated_Devnet="solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"})(Ic||(Ic={}));var $s;(function(s){s.signTransaction="solana_signTransaction",s.signMessage="solana_signMessage",s.signAndSendTransaction="solana_signAndSendTransaction",s.signAndSendAllTransactions="solana_signAndSendAllTransactions",s.signAllTransactions="solana_signAllTransactions"})($s||($s={}));const pt={Mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Deprecated_Mainnet:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",Deprecated_Devnet:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"};let Vv=class extends bs{constructor(e){super()}};const dd=E.FIVE_SECONDS,qs={pulse:"heartbeat_pulse"};let jm=class Rm extends Vv{constructor(e){super(e),this.events=new kt.EventEmitter,this.interval=dd,this.interval=(e==null?void 0:e.interval)||dd}static async init(e){const t=new Rm(e);return await t.init(),t}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),E.toMiliseconds(this.interval))}pulse(){this.events.emit(qs.pulse)}};function Kv(s){return!s||typeof s.then!="function"?Promise.resolve(s):s}function yt(s,...e){try{return Kv(s(...e))}catch(t){return Promise.reject(t)}}function Gv(s){const e=typeof s;return s===null||e!=="object"&&e!=="function"}function Yv(s){const e=Object.getPrototypeOf(s);return!e||e.isPrototypeOf(Object)}function tc(s){if(Gv(s))return String(s);if(Yv(s)||Array.isArray(s))return JSON.stringify(s);if(typeof s.toJSON=="function")return tc(s.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const mh="base64:";function Qv(s){return typeof s=="string"?s:mh+Xv(s)}function Zv(s){return typeof s!="string"||!s.startsWith(mh)?s:Jv(s.slice(mh.length))}function Jv(s){return globalThis.Buffer?_.Buffer.from(s,"base64"):Uint8Array.from(globalThis.atob(s),e=>e.codePointAt(0))}function Xv(s){return globalThis.Buffer?_.Buffer.from(s).toString("base64"):globalThis.btoa(String.fromCodePoint(...s))}function ts(s){var e;return s&&((e=s.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function e0(...s){return ts(s.join(":"))}function Ta(s){return s=ts(s),s?s+":":""}function t0(s,e){if(e===void 0)return!0;let t=0,i=s.indexOf(":");for(;i>-1;)t++,i=s.indexOf(":",i+1);return t<=e}function s0(s,e){return e?s.startsWith(e)&&s[s.length-1]!=="$":s[s.length-1]!=="$"}const i0="memory",r0=()=>{const s=new Map;return{name:i0,getInstance:()=>s,hasItem(e){return s.has(e)},getItem(e){return s.get(e)??null},getItemRaw(e){return s.get(e)??null},setItem(e,t){s.set(e,t)},setItemRaw(e,t){s.set(e,t)},removeItem(e){s.delete(e)},getKeys(){return[...s.keys()]},clear(){s.clear()},dispose(){s.clear()}}};function n0(s={}){const e={mounts:{"":s.driver||r0()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=c=>{for(const h of e.mountpoints)if(c.startsWith(h))return{base:h,relativeKey:c.slice(h.length),driver:e.mounts[h]};return{base:"",relativeKey:c,driver:e.mounts[""]}},i=(c,h)=>e.mountpoints.filter(u=>u.startsWith(c)||h&&c.startsWith(u)).map(u=>({relativeBase:c.length>u.length?c.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(c,h)=>{if(e.watching){h=ts(h);for(const u of e.watchListeners)u(c,h)}},n=async()=>{if(!e.watching){e.watching=!0;for(const c in e.mounts)e.unwatch[c]=await pd(e.mounts[c],r,c)}},o=async()=>{if(e.watching){for(const c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},a=(c,h,u)=>{const d=new Map,p=g=>{let f=d.get(g.base);return f||(f={driver:g.driver,base:g.base,items:[]},d.set(g.base,f)),f};for(const g of c){const f=typeof g=="string",y=ts(f?g:g.key),w=f?void 0:g.value,m=f||!g.options?h:{...h,...g.options},b=t(y);p(b).items.push({key:y,value:w,relativeKey:b.relativeKey,options:m})}return Promise.all([...d.values()].map(g=>u(g))).then(g=>g.flat())},l={hasItem(c,h={}){c=ts(c);const{relativeKey:u,driver:d}=t(c);return yt(d.hasItem,u,h)},getItem(c,h={}){c=ts(c);const{relativeKey:u,driver:d}=t(c);return yt(d.getItem,u,h).then(p=>Di(p))},getItems(c,h={}){return a(c,h,u=>u.driver.getItems?yt(u.driver.getItems,u.items.map(d=>({key:d.relativeKey,options:d.options})),h).then(d=>d.map(p=>({key:e0(u.base,p.key),value:Di(p.value)}))):Promise.all(u.items.map(d=>yt(u.driver.getItem,d.relativeKey,d.options).then(p=>({key:d.key,value:Di(p)})))))},getItemRaw(c,h={}){c=ts(c);const{relativeKey:u,driver:d}=t(c);return d.getItemRaw?yt(d.getItemRaw,u,h):yt(d.getItem,u,h).then(p=>Zv(p))},async setItem(c,h,u={}){if(h===void 0)return l.removeItem(c);c=ts(c);const{relativeKey:d,driver:p}=t(c);p.setItem&&(await yt(p.setItem,d,tc(h),u),p.watch||r("update",c))},async setItems(c,h){await a(c,h,async u=>{if(u.driver.setItems)return yt(u.driver.setItems,u.items.map(d=>({key:d.relativeKey,value:tc(d.value),options:d.options})),h);u.driver.setItem&&await Promise.all(u.items.map(d=>yt(u.driver.setItem,d.relativeKey,tc(d.value),d.options)))})},async setItemRaw(c,h,u={}){if(h===void 0)return l.removeItem(c,u);c=ts(c);const{relativeKey:d,driver:p}=t(c);if(p.setItemRaw)await yt(p.setItemRaw,d,h,u);else if(p.setItem)await yt(p.setItem,d,Qv(h),u);else return;p.watch||r("update",c)},async removeItem(c,h={}){typeof h=="boolean"&&(h={removeMeta:h}),c=ts(c);const{relativeKey:u,driver:d}=t(c);d.removeItem&&(await yt(d.removeItem,u,h),(h.removeMeta||h.removeMata)&&await yt(d.removeItem,u+"$",h),d.watch||r("remove",c))},async getMeta(c,h={}){typeof h=="boolean"&&(h={nativeOnly:h}),c=ts(c);const{relativeKey:u,driver:d}=t(c),p=Object.create(null);if(d.getMeta&&Object.assign(p,await yt(d.getMeta,u,h)),!h.nativeOnly){const g=await yt(d.getItem,u+"$",h).then(f=>Di(f));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(p,g))}return p},setMeta(c,h,u={}){return this.setItem(c+"$",h,u)},removeMeta(c,h={}){return this.removeItem(c+"$",h)},async getKeys(c,h={}){var y;c=Ta(c);const u=i(c,!0);let d=[];const p=[];let g=!0;for(const w of u){(y=w.driver.flags)!=null&&y.maxDepth||(g=!1);const m=await yt(w.driver.getKeys,w.relativeBase,h);for(const b of m){const I=w.mountpoint+ts(b);d.some(N=>I.startsWith(N))||p.push(I)}d=[w.mountpoint,...d.filter(b=>!b.startsWith(w.mountpoint))]}const f=h.maxDepth!==void 0&&!g;return p.filter(w=>(!f||t0(w,h.maxDepth))&&s0(w,c))},async clear(c,h={}){c=Ta(c),await Promise.all(i(c,!1).map(async u=>{if(u.driver.clear)return yt(u.driver.clear,u.relativeBase,h);if(u.driver.removeItem){const d=await u.driver.getKeys(u.relativeBase||"",h);return Promise.all(d.map(p=>u.driver.removeItem(p,h)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>gd(c)))},async watch(c){return await n(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(h=>h!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,h){if(c=Ta(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((u,d)=>d.length-u.length)),e.mounts[c]=h,e.watching&&Promise.resolve(pd(h,r,c)).then(u=>{e.unwatch[c]=u}).catch(console.error),l},async unmount(c,h=!0){var u,d;c=Ta(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&((d=(u=e.unwatch)[c])==null||d.call(u),delete e.unwatch[c]),h&&await gd(e.mounts[c]),e.mountpoints=e.mountpoints.filter(p=>p!==c),delete e.mounts[c])},getMount(c=""){c=ts(c)+":";const h=t(c);return{driver:h.driver,base:h.base}},getMounts(c="",h={}){return c=ts(c),i(c,h.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(c,h={})=>l.getKeys(c,h),get:(c,h={})=>l.getItem(c,h),set:(c,h,u={})=>l.setItem(c,h,u),has:(c,h={})=>l.hasItem(c,h),del:(c,h={})=>l.removeItem(c,h),remove:(c,h={})=>l.removeItem(c,h)};return l}function pd(s,e,t){return s.watch?s.watch((i,r)=>e(i,t+r)):()=>{}}async function gd(s){typeof s.dispose=="function"&&await yt(s.dispose)}const o0="idb-keyval";var a0=(s={})=>{const e=s.base&&s.base.length>0?`${s.base}:`:"",t=r=>e+r;let i;return s.dbName&&s.storeName&&(i=Im(s.dbName,s.storeName)),{name:o0,options:s,async hasItem(r){return!(typeof await bc(t(r),i)>"u")},async getItem(r){return await bc(t(r),i)??null},setItem(r,n){return _m(t(r),n,i)},removeItem(r){return Nm(t(r),i)},getKeys(){return Am(i)},clear(){return Em(i)}}};const c0="WALLET_CONNECT_V2_INDEXED_DB",l0="keyvaluestorage";let h0=class{constructor(){this.indexedDb=n0({driver:a0({dbName:c0,storeName:l0})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,Sr(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var gl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof _.global<"u"?_.global:typeof self<"u"?self:{},sc={exports:{}};(function(){let s;function e(){}s=e,s.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},s.prototype.setItem=function(t,i){this[t]=String(i)},s.prototype.removeItem=function(t){delete this[t]},s.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(i){t[i]=void 0,delete t[i]})},s.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},s.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof gl<"u"&&gl.localStorage?sc.exports=gl.localStorage:typeof window<"u"&&window.localStorage?sc.exports=window.localStorage:sc.exports=new e})();function u0(s){var e;return[s[0],wi((e=s[1])!=null?e:"")]}let d0=class{constructor(){this.localStorage=sc.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(u0)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return wi(t)}async setItem(e,t){this.localStorage.setItem(e,Sr(t))}async removeItem(e){this.localStorage.removeItem(e)}};const p0="wc_storage_version",fd=1,g0=async(s,e,t)=>{const i=p0,r=await e.getItem(i);if(r&&r>=fd){t(e);return}const n=await s.getKeys();if(!n.length){t(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const l=a.toLowerCase();if(l.includes("wc@")||l.includes("walletconnect")||l.includes("wc_")||l.includes("wallet_connect")){const c=await s.getItem(a);await e.setItem(a,c),o.push(a)}}await e.setItem(i,fd),t(e),f0(s,o)},f0=async(s,e)=>{e.length&&e.forEach(async t=>{await s.removeItem(t)})};let m0=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new d0;this.storage=e;try{const t=new h0;g0(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}};var w0=Object.defineProperty,y0=(s,e,t)=>e in s?w0(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,md=(s,e,t)=>y0(s,typeof e!="symbol"?e+"":e,t);let b0=class extends bs{constructor(e){super(),this.opts=e,md(this,"protocol","wc"),md(this,"version",2)}};var v0=Object.defineProperty,I0=(s,e,t)=>e in s?v0(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,E0=(s,e,t)=>I0(s,e+"",t);let A0=class extends bs{constructor(e,t){super(),this.core=e,this.logger=t,E0(this,"records",new Map)}},N0=class{constructor(e,t){this.logger=e,this.core=t}},_0=class extends bs{constructor(e,t){super(),this.relayer=e,this.logger=t}},C0=class extends bs{constructor(e){super()}},S0=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},$0=class extends bs{constructor(e,t){super(),this.relayer=e,this.logger=t}},P0=class extends bs{constructor(e,t){super(),this.core=e,this.logger=t}},T0=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},M0=class{constructor(e,t){this.projectId=e,this.logger=t}},O0=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};function Go(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function wd(s){return Go(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const Lm="2.23.2";let ro={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${Lm}`},qc=class wh extends Error{constructor(e,t={}){var a;const i=(()=>{var l;return t.cause instanceof wh?t.cause.details:(l=t.cause)!=null&&l.message?t.cause.message:t.details})(),r=t.cause instanceof wh&&t.cause.docsPath||t.docsPath,n=(a=ro.getDocsUrl)==null?void 0:a.call(ro,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...ro.version?[`Version: ${ro.version}`]:[]].join(`
3
+ `);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Lm}walk(e){return Um(this,e)}};function Um(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?Um(s.cause,e):e?null:s}let zm=class extends qc{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}};function Gn(s,{dir:e,size:t=32}={}){return typeof s=="string"?x0(s,{dir:e,size:t}):D0(s,{dir:e,size:t})}function x0(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new zm({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function D0(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new zm({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}let k0=class extends qc{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}},j0=class extends qc{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function Yn(s,{size:e}){if(wd(s)>e)throw new j0({givenSize:wd(s),maxSize:e})}function yh(s,e={}){const{signed:t}=e;e.size&&Yn(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function R0(s,e={}){return Number(yh(s,e))}const L0=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function bh(s,e={}){return typeof s=="number"||typeof s=="bigint"?qm(s,e):typeof s=="string"?F0(s,e):typeof s=="boolean"?U0(s,e):Fm(s,e)}function U0(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(Yn(t,{size:e.size}),Gn(t,{size:e.size})):t}function Fm(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=L0[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(Yn(i,{size:e.size}),Gn(i,{dir:"right",size:e.size})):i}function qm(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const l=typeof s=="bigint"?"n":"";throw new k0({max:n?`${n}${l}`:void 0,min:`${o}${l}`,signed:t,size:i,value:`${s}${l}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?Gn(a,{size:i}):a}const z0=new TextEncoder;function F0(s,e={}){const t=z0.encode(s);return Fm(t,e)}const q0=new TextEncoder;function B0(s,e={}){return typeof s=="number"||typeof s=="bigint"?W0(s,e):typeof s=="boolean"?H0(s,e):Go(s)?Bm(s,e):Hm(s,e)}function H0(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(Yn(t,{size:e.size}),Gn(t,{size:e.size})):t}const ri={zero:48,nine:57,A:65,F:70,a:97,f:102};function yd(s){if(s>=ri.zero&&s<=ri.nine)return s-ri.zero;if(s>=ri.A&&s<=ri.F)return s-(ri.A-10);if(s>=ri.a&&s<=ri.f)return s-(ri.a-10)}function Bm(s,e={}){let t=s;e.size&&(Yn(t,{size:e.size}),t=Gn(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const l=yd(i.charCodeAt(a++)),c=yd(i.charCodeAt(a++));if(l===void 0||c===void 0)throw new qc(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=l*16+c}return n}function W0(s,e){const t=qm(s,e);return Bm(t)}function Hm(s,e={}){const t=q0.encode(s);return typeof e.size=="number"?(Yn(t,{size:e.size}),Gn(t,{dir:"right",size:e.size})):t}function Ec(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function V0(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Bc(s,...e){if(!V0(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function uF(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ec(s.outputLen),Ec(s.blockLen)}function bd(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function K0(s,e){Bc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Ma=BigInt(2**32-1),vd=BigInt(32);function G0(s,e=!1){return e?{h:Number(s&Ma),l:Number(s>>vd&Ma)}:{h:Number(s>>vd&Ma)|0,l:Number(s&Ma)|0}}function Y0(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=G0(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const Q0=(s,e,t)=>s<<t|e>>>32-t,Z0=(s,e,t)=>e<<t|s>>>32-t,J0=(s,e,t)=>e<<t-32|s>>>64-t,X0=(s,e,t)=>s<<t-32|e>>>64-t,Lr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function eI(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function dF(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function pF(s,e){return s<<32-e|s>>>e}const Id=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function tI(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Ed(s){for(let e=0;e<s.length;e++)s[e]=tI(s[e])}function sI(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Wm(s){return typeof s=="string"&&(s=sI(s)),Bc(s),s}function gF(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Bc(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}let iI=class{clone(){return this._cloneInto()}};function rI(s){const e=i=>s().update(Wm(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function mF(s=32){if(Lr&&typeof Lr.getRandomValues=="function")return Lr.getRandomValues(new Uint8Array(s));if(Lr&&typeof Lr.randomBytes=="function")return Lr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Vm=[],Km=[],Gm=[],nI=BigInt(0),no=BigInt(1),oI=BigInt(2),aI=BigInt(7),cI=BigInt(256),lI=BigInt(113);for(let s=0,e=no,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Vm.push(2*(5*i+t)),Km.push((s+1)*(s+2)/2%64);let r=nI;for(let n=0;n<7;n++)e=(e<<no^(e>>aI)*lI)%cI,e&oI&&(r^=no<<(no<<BigInt(n))-no);Gm.push(r)}const[hI,uI]=Y0(Gm,!0),Ad=(s,e,t)=>t>32?J0(s,e,t):Q0(s,e,t),Nd=(s,e,t)=>t>32?X0(s,e,t):Z0(s,e,t);function dI(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,l=(o+2)%10,c=t[l],h=t[l+1],u=Ad(c,h,1)^t[a],d=Nd(c,h,1)^t[a+1];for(let p=0;p<50;p+=10)s[o+p]^=u,s[o+p+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Km[o],l=Ad(r,n,a),c=Nd(r,n,a),h=Vm[o];r=s[h],n=s[h+1],s[h]=l,s[h+1]=c}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=hI[i],s[1]^=uI[i]}t.fill(0)}let pI=class Ym extends iI{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Ec(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=eI(this.state)}keccak(){Id||Ed(this.state32),dI(this.state32,this.rounds),Id||Ed(this.state32),this.posOut=0,this.pos=0}update(e){bd(this);const{blockLen:t,state:i}=this;e=Wm(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){bd(this,!1),Bc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ec(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(K0(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:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Ym(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const gI=(s,e,t)=>rI(()=>new pI(e,s,t)),fI=gI(1,136,256/8);function Qm(s,e){const t=e||"hex",i=fI(Go(s,{strict:!1})?B0(s):s);return t==="bytes"?i:bh(i)}let mI=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}};const fl=new mI(8192);function wI(s,e){if(fl.has(`${s}.${e}`))return fl.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=Qm(Hm(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return fl.set(`${s}.${e}`,n),n}function yI(s){const e=Qm(`0x${s.substring(4)}`).substring(26);return wI(`0x${e}`)}async function bI({hash:s,signature:e}){const t=Go(s)?s:bh(s),{secp256k1:i}=await Vo(async()=>{const{secp256k1:o}=await import("./secp256k1-CBh6eQLF.js");return{secp256k1:o}},__vite__mapDeps([6,1,2,7,8,9,10,3,4]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:c,s:h,v:u,yParity:d}=e,p=Number(d??u),g=_d(p);return new i.Signature(yh(c),yh(h)).addRecoveryBit(g)}const o=Go(e)?e:bh(e),a=R0(`0x${o.slice(130)}`),l=_d(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(l)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function _d(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function vI({hash:s,signature:e}){return yI(await bI({hash:s,signature:e}))}var Zm=cv(),II={};const Jm=":";function On(s){const[e,t]=s.split(Jm);return{namespace:e,reference:t}}function EI(s){const[e,t,i]=s.split(Jm);return{namespace:e,reference:t,address:i}}function Xm(s,e){return s.includes(":")?[s]:e.chains||[]}const AI="ReactNative",fs={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},NI="js";function Ac(){return typeof _.process<"u"&&typeof _.process.versions<"u"&&typeof _.process.versions.node<"u"}function Gi(){return!Vi()&&!!zc()&&navigator.product===AI}function _I(){return Gi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="android"}function CI(){return Gi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="ios"}function pa(){return!Ac()&&!!zc()&&!!Vi()}function ga(){return Gi()?fs.reactNative:Ac()?fs.node:pa()?fs.browser:fs.unknown}function Cd(){var s;try{return Gi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Application)<"u"?(s=_.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function SI(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function ew(){return Tm()||{name:"",description:"",url:"",icons:[""]}}function $I(){if(ga()===fs.reactNative&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"){const{OS:t,Version:i}=_.global.Platform;return[t,i].join("-")}const s=Sm();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function PI(){var s;const e=ga();return e===fs.browser?[e,((s=Mm())==null?void 0:s.host)||"unknown"].join(":"):e}function tw(s,e,t){const i=$I(),r=PI();return[[s,e].join("-"),[NI,t].join("-"),i,r].join("/")}function TI({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:l}){const c=t.split("?"),h=tw(s,e,i),u={auth:r,ua:h,projectId:n,useOnCloseEvent:o,packageName:l||void 0,bundleId:a||void 0},d=SI(c[1]||"",u);return c[0]+"?"+d}function dr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function sw(s){return Object.fromEntries(s.entries())}function iw(s){return new Map(Object.entries(s))}function rr(s=E.FIVE_MINUTES,e){const t=E.toMiliseconds(s||E.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,l)=>{if(o)return a(o);n=setTimeout(()=>{const c=new Error(e);o=Promise.reject(c),l(c)},t),i=a,r=l})}}function ki(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function rw(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.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: ${s}`)}function MI(s){return rw("topic",s)}function OI(s){return rw("id",s)}function nw(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function ut(s,e){return E.fromMiliseconds(Date.now()+E.toMiliseconds(s))}function Si(s){return Date.now()>=E.toMiliseconds(s)}function Ie(s,e){return`${s}${e?`:${e}`:""}`}function ic(s=[],e=[]){return[...new Set([...s,...e])]}async function xI({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=DI(n,s,e),a=ga();if(a===fs.browser){if(!((i=Vi())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}kI(o)}else a===fs.reactNative&&typeof(_.global==null?void 0:_.global.Linking)<"u"&&await _.global.Linking.openURL(o)}catch(r){console.error(r)}}function DI(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${UI(i,!0)}`}else r=`${r}/wc?${i}`;return r}function kI(s){let e="_self";LI()?e="_top":(RI()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function jI(s,e){let t="";try{if(pa()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Sd(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function $d(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function _u(){return typeof _.process<"u"&&II.IS_VITEST==="true"}function RI(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function LI(){try{return window.self!==window.top}catch{return!1}}function UI(s,e=!1){const t=_.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function ow(s){return _.Buffer.from(s,"base64").toString("utf-8")}function zI(s){return new Promise(e=>setTimeout(e,s))}function Yo(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function FI(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Hc(s,...e){if(!FI(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Cu(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Yo(s.outputLen),Yo(s.blockLen)}function Rn(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function aw(s,e){Hc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Oa=BigInt(2**32-1),Pd=BigInt(32);function qI(s,e=!1){return e?{h:Number(s&Oa),l:Number(s>>Pd&Oa)}:{h:Number(s>>Pd&Oa)|0,l:Number(s&Oa)|0}}function BI(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=qI(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const HI=(s,e,t)=>s<<t|e>>>32-t,WI=(s,e,t)=>e<<t|s>>>32-t,VI=(s,e,t)=>e<<t-32|s>>>64-t,KI=(s,e,t)=>s<<t-32|e>>>64-t,Ur=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function GI(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function ml(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Bs(s,e){return s<<32-e|s>>>e}const Td=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function YI(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Md(s){for(let e=0;e<s.length;e++)s[e]=YI(s[e])}function QI(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Ln(s){return typeof s=="string"&&(s=QI(s)),Hc(s),s}let Su=class{clone(){return this._cloneInto()}};function cw(s){const e=i=>s().update(Ln(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function fa(s=32){if(Ur&&typeof Ur.getRandomValues=="function")return Ur.getRandomValues(new Uint8Array(s));if(Ur&&typeof Ur.randomBytes=="function")return Ur.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const lw=[],hw=[],uw=[],ZI=BigInt(0),oo=BigInt(1),JI=BigInt(2),XI=BigInt(7),e1=BigInt(256),t1=BigInt(113);for(let s=0,e=oo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],lw.push(2*(5*i+t)),hw.push((s+1)*(s+2)/2%64);let r=ZI;for(let n=0;n<7;n++)e=(e<<oo^(e>>XI)*t1)%e1,e&JI&&(r^=oo<<(oo<<BigInt(n))-oo);uw.push(r)}const[s1,i1]=BI(uw,!0),Od=(s,e,t)=>t>32?VI(s,e,t):HI(s,e,t),xd=(s,e,t)=>t>32?KI(s,e,t):WI(s,e,t);function r1(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,l=(o+2)%10,c=t[l],h=t[l+1],u=Od(c,h,1)^t[a],d=xd(c,h,1)^t[a+1];for(let p=0;p<50;p+=10)s[o+p]^=u,s[o+p+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=hw[o],l=Od(r,n,a),c=xd(r,n,a),h=lw[o];r=s[h],n=s[h+1],s[h]=l,s[h+1]=c}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=s1[i],s[1]^=i1[i]}t.fill(0)}let n1=class dw extends Su{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Yo(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=GI(this.state)}keccak(){Td||Md(this.state32),r1(this.state32,this.rounds),Td||Md(this.state32),this.posOut=0,this.pos=0}update(e){Rn(this);const{blockLen:t,state:i}=this;e=Ln(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Rn(this,!1),Hc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Yo(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(aw(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:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new dw(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const o1=(s,e,t)=>cw(()=>new n1(e,s,t)),a1=o1(1,136,256/8),c1="https://rpc.walletconnect.org/v1";function pw(s){const e=`Ethereum Signed Message:
4
4
  ${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+_.Buffer.from(a1(t)).toString("hex")}async function l1(s,e,t,i,r,n){switch(t.t){case"eip191":return await h1(s,e,t.s);case"eip1271":return await u1(s,e,t.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function h1(s,e,t){return(await vI({hash:pw(e),signature:t})).toLowerCase()===s.toLowerCase()}async function u1(s,e,t,i,r,n){const o=On(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",l="0000000000000000000000000000000000000000000000000000000000000040",c="0000000000000000000000000000000000000000000000000000000000000041",h=t.substring(2),u=pw(e).substring(2),d=a+u+l+c+h,p=await fetch(`${n||c1}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:d1(),jsonrpc:"2.0",method:"eth_call",params:[{to:s,data:d},"latest"]})}),{result:g}=await p.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function d1(){return Date.now()+Math.floor(Math.random()*1e3)}var p1=Object.defineProperty,g1=Object.defineProperties,f1=Object.getOwnPropertyDescriptors,Dd=Object.getOwnPropertySymbols,m1=Object.prototype.hasOwnProperty,w1=Object.prototype.propertyIsEnumerable,kd=(s,e,t)=>e in s?p1(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,y1=(s,e)=>{for(var t in e||(e={}))m1.call(e,t)&&kd(s,t,e[t]);if(Dd)for(var t of Dd(e))w1.call(e,t)&&kd(s,t,e[t]);return s},b1=(s,e)=>g1(s,f1(e));const v1="did:pkh:",$u=s=>s==null?void 0:s.split(":"),I1=s=>{const e=s&&$u(s);if(e)return s.includes(v1)?e[3]:e[1]},vh=s=>{const e=s&&$u(s);if(e)return e[2]+":"+e[3]},Nc=s=>{const e=s&&$u(s);if(e)return e.pop()};async function jd(s){const{cacao:e,projectId:t}=s,{s:i,p:r}=e,n=gw(r,r.iss),o=Nc(r.iss);return await l1(o,n,i,vh(r.iss),t)}const gw=(s,e)=>{const t=`${s.domain} wants you to sign in with your Ethereum account:`,i=Nc(e);if(!s.aud&&!s.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=s.statement||void 0;const n=`URI: ${s.aud||s.uri}`,o=`Version: ${s.version}`,a=`Chain ID: ${I1(e)}`,l=`Nonce: ${s.nonce}`,c=`Issued At: ${s.iat}`,h=s.exp?`Expiration Time: ${s.exp}`:void 0,u=s.nbf?`Not Before: ${s.nbf}`:void 0,d=s.requestId?`Request ID: ${s.requestId}`:void 0,p=s.resources?`Resources:${s.resources.map(f=>`
5
5
  - ${f}`).join("")}`:void 0,g=rc(s.resources);if(g){const f=Qo(g);r=T1(r,f)}return[t,i,"",r,"",n,o,a,l,c,h,u,d,p].filter(f=>f!=null).join(`
6
- `)};function E1(s){return _.Buffer.from(JSON.stringify(s)).toString("base64")}function A1(s){return JSON.parse(_.Buffer.from(s,"base64").toString("utf-8"))}function yr(s){if(!s)throw new Error("No recap provided, value is undefined");if(!s.att)throw new Error("No `att` property found");const e=Object.keys(s.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=s.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(r=>{const n=i[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function N1(s,e,t,i={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[s]:_1(e,t,i)}}}function _1(s,e,t={}){e=e==null?void 0:e.sort((r,n)=>r.localeCompare(n));const i=e.map(r=>({[`${s}/${r}`]:[t]}));return Object.assign({},...i)}function fw(s){return yr(s),`urn:recap:${E1(s).replace(/=/g,"")}`}function Qo(s){const e=A1(s.replace("urn:recap:",""));return yr(e),e}function C1(s,e,t){const i=N1(s,e,t);return fw(i)}function S1(s){return s&&s.includes("urn:recap:")}function $1(s,e){const t=Qo(s),i=Qo(e),r=P1(t,i);return fw(r)}function P1(s,e){yr(s),yr(e);const t=Object.keys(s.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),i={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=s.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,l)=>a.localeCompare(l)).forEach(a=>{var l,c;i.att[r]=b1(y1({},i.att[r]),{[a]:((l=s.att[r])==null?void 0:l[a])||((c=e.att[r])==null?void 0:c[a])})})}),i}function T1(s="",e){yr(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(s.includes(t))return s;const i=[];let r=0;Object.keys(e.att).forEach(a=>{const l=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));l.sort((u,d)=>u.action.localeCompare(d.action));const c={};l.forEach(u=>{c[u.ability]||(c[u.ability]=[]),c[u.ability].push(u.action)});const h=Object.keys(c).map(u=>(r++,`(${r}) '${u}': '${c[u].join("', '")}' for '${a}'.`));i.push(h.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${s?s+" ":""}${o}`}function Rd(s){var e;const t=Qo(s);yr(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function Ld(s){const e=Qo(s);yr(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(r=>{var n;(n=r==null?void 0:r[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function rc(s){if(!s)return;const e=s==null?void 0:s[s.length-1];return S1(e)?e:void 0}function wl(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function mw(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ds(s,...e){if(!mw(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Ud(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function M1(s,e){ds(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function zd(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}const zi=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),O1=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),x1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!x1)throw new Error("Non little-endian hardware is not supported");function D1(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Ih(s){if(typeof s=="string")s=D1(s);else if(mw(s))s=Eh(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function k1(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function j1(s,e){if(s.length!==e.length)return!1;let t=0;for(let i=0;i<s.length;i++)t|=s[i]^e[i];return t===0}const R1=(s,e)=>{function t(i,...r){if(ds(i),s.nonceLength!==void 0){const c=r[0];if(!c)throw new Error("nonce / iv required");s.varSizeNonce?ds(c):ds(c,s.nonceLength)}const n=s.tagLength;n&&r[1]!==void 0&&ds(r[1]);const o=e(i,...r),a=(c,h)=>{if(h!==void 0){if(c!==2)throw new Error("cipher output not supported");ds(h)}};let l=!1;return{encrypt(c,h){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ds(c),a(o.encrypt.length,h),o.encrypt(c,h)},decrypt(c,h){if(ds(c),n&&c.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,h),o.decrypt(c,h)}}}return Object.assign(t,s),t};function Fd(s,e,t=!0){if(e===void 0)return new Uint8Array(s);if(e.length!==s)throw new Error("invalid output length, expected "+s+", got: "+e.length);if(t&&!L1(e))throw new Error("invalid output, must be aligned");return e}function qd(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);s.setUint32(e+4,o,i),s.setUint32(e+0,a,i)}function L1(s){return s.byteOffset%4===0}function Eh(s){return Uint8Array.from(s)}function Un(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}const ww=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),U1=ww("expand 16-byte k"),z1=ww("expand 32-byte k"),F1=zi(U1),q1=zi(z1);function de(s,e){return s<<e|s>>>32-e}function Ah(s){return s.byteOffset%4===0}const xa=64,B1=16,yw=2**32-1,Bd=new Uint32Array;function H1(s,e,t,i,r,n,o,a){const l=r.length,c=new Uint8Array(xa),h=zi(c),u=Ah(r)&&Ah(n),d=u?zi(r):Bd,p=u?zi(n):Bd;for(let g=0;g<l;o++){if(s(e,t,i,h,o,a),o>=yw)throw new Error("arx: counter overflow");const f=Math.min(xa,l-g);if(u&&f===xa){const y=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,m;w<B1;w++)m=y+w,p[m]=d[m]^h[w];g+=xa;continue}for(let y=0,w;y<f;y++)w=g+y,n[w]=r[w]^c[y];g+=f}}function W1(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=k1({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return wl(r),wl(o),zd(n),zd(t),(a,l,c,h,u=0)=>{ds(a),ds(l),ds(c);const d=c.length;if(h===void 0&&(h=new Uint8Array(d)),ds(h),wl(u),u<0||u>=yw)throw new Error("arx: counter overflow");if(h.length<d)throw new Error(`arx: output (${h.length}) is shorter than data (${d})`);const p=[];let g=a.length,f,y;if(g===32)p.push(f=Eh(a)),y=q1;else if(g===16&&t)f=new Uint8Array(32),f.set(a),f.set(a,16),y=F1,p.push(f);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Ah(l)||p.push(l=Eh(l));const w=zi(f);if(i){if(l.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(y,w,zi(l.subarray(0,16)),w),l=l.subarray(16)}const m=16-r;if(m!==l.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const I=new Uint8Array(12);I.set(l,n?0:12-l.length),l=I,p.push(l)}const b=zi(l);return H1(s,y,w,b,c,h,u,o),Un(...p),h}}const _t=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let V1=class{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=Ih(e),ds(e,32);const t=_t(e,0),i=_t(e,2),r=_t(e,4),n=_t(e,6),o=_t(e,8),a=_t(e,10),l=_t(e,12),c=_t(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|r<<6)&7939,this.r[3]=(r>>>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|l<<5)&8065,this.r[8]=(l>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let h=0;h<8;h++)this.pad[h]=_t(e,16+2*h)}process(e,t,i=!1){const r=i?0:2048,{h:n,r:o}=this,a=o[0],l=o[1],c=o[2],h=o[3],u=o[4],d=o[5],p=o[6],g=o[7],f=o[8],y=o[9],w=_t(e,t+0),m=_t(e,t+2),b=_t(e,t+4),I=_t(e,t+6),N=_t(e,t+8),$=_t(e,t+10),P=_t(e,t+12),O=_t(e,t+14);let C=n[0]+(w&8191),T=n[1]+((w>>>13|m<<3)&8191),S=n[2]+((m>>>10|b<<6)&8191),R=n[3]+((b>>>7|I<<9)&8191),L=n[4]+((I>>>4|N<<12)&8191),q=n[5]+(N>>>1&8191),B=n[6]+((N>>>14|$<<2)&8191),U=n[7]+(($>>>11|P<<5)&8191),H=n[8]+((P>>>8|O<<8)&8191),W=n[9]+(O>>>5|r),A=0,z=A+C*a+T*(5*y)+S*(5*f)+R*(5*g)+L*(5*p);A=z>>>13,z&=8191,z+=q*(5*d)+B*(5*u)+U*(5*h)+H*(5*c)+W*(5*l),A+=z>>>13,z&=8191;let Y=A+C*l+T*a+S*(5*y)+R*(5*f)+L*(5*g);A=Y>>>13,Y&=8191,Y+=q*(5*p)+B*(5*d)+U*(5*u)+H*(5*h)+W*(5*c),A+=Y>>>13,Y&=8191;let K=A+C*c+T*l+S*a+R*(5*y)+L*(5*f);A=K>>>13,K&=8191,K+=q*(5*g)+B*(5*p)+U*(5*d)+H*(5*u)+W*(5*h),A+=K>>>13,K&=8191;let be=A+C*h+T*c+S*l+R*a+L*(5*y);A=be>>>13,be&=8191,be+=q*(5*f)+B*(5*g)+U*(5*p)+H*(5*d)+W*(5*u),A+=be>>>13,be&=8191;let oe=A+C*u+T*h+S*c+R*l+L*a;A=oe>>>13,oe&=8191,oe+=q*(5*y)+B*(5*f)+U*(5*g)+H*(5*p)+W*(5*d),A+=oe>>>13,oe&=8191;let Oe=A+C*d+T*u+S*h+R*c+L*l;A=Oe>>>13,Oe&=8191,Oe+=q*a+B*(5*y)+U*(5*f)+H*(5*g)+W*(5*p),A+=Oe>>>13,Oe&=8191;let lt=A+C*p+T*d+S*u+R*h+L*c;A=lt>>>13,lt&=8191,lt+=q*l+B*a+U*(5*y)+H*(5*f)+W*(5*g),A+=lt>>>13,lt&=8191;let Be=A+C*g+T*p+S*d+R*u+L*h;A=Be>>>13,Be&=8191,Be+=q*c+B*l+U*a+H*(5*y)+W*(5*f),A+=Be>>>13,Be&=8191;let Qe=A+C*f+T*g+S*p+R*d+L*u;A=Qe>>>13,Qe&=8191,Qe+=q*h+B*c+U*l+H*a+W*(5*y),A+=Qe>>>13,Qe&=8191;let He=A+C*y+T*f+S*g+R*p+L*d;A=He>>>13,He&=8191,He+=q*u+B*h+U*c+H*l+W*a,A+=He>>>13,He&=8191,A=(A<<2)+A|0,A=A+z|0,z=A&8191,A=A>>>13,Y+=A,n[0]=z,n[1]=Y,n[2]=K,n[3]=be,n[4]=oe,n[5]=Oe,n[6]=lt,n[7]=Be,n[8]=Qe,n[9]=He}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,i[0]=e[0]+5,r=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+r,r=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;Un(i)}update(e){Ud(this);const{buffer:t,blockLen:i}=this;e=Ih(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){for(;i<=r-n;n+=i)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Un(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ud(this),M1(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}};function K1(s){const e=(i,r)=>s(r).update(Ih(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const G1=K1(s=>new V1(s));function Y1(s,e,t,i,r,n=20){let o=s[0],a=s[1],l=s[2],c=s[3],h=e[0],u=e[1],d=e[2],p=e[3],g=e[4],f=e[5],y=e[6],w=e[7],m=r,b=t[0],I=t[1],N=t[2],$=o,P=a,O=l,C=c,T=h,S=u,R=d,L=p,q=g,B=f,U=y,H=w,W=m,A=b,z=I,Y=N;for(let be=0;be<n;be+=2)$=$+T|0,W=de(W^$,16),q=q+W|0,T=de(T^q,12),$=$+T|0,W=de(W^$,8),q=q+W|0,T=de(T^q,7),P=P+S|0,A=de(A^P,16),B=B+A|0,S=de(S^B,12),P=P+S|0,A=de(A^P,8),B=B+A|0,S=de(S^B,7),O=O+R|0,z=de(z^O,16),U=U+z|0,R=de(R^U,12),O=O+R|0,z=de(z^O,8),U=U+z|0,R=de(R^U,7),C=C+L|0,Y=de(Y^C,16),H=H+Y|0,L=de(L^H,12),C=C+L|0,Y=de(Y^C,8),H=H+Y|0,L=de(L^H,7),$=$+S|0,Y=de(Y^$,16),U=U+Y|0,S=de(S^U,12),$=$+S|0,Y=de(Y^$,8),U=U+Y|0,S=de(S^U,7),P=P+R|0,W=de(W^P,16),H=H+W|0,R=de(R^H,12),P=P+R|0,W=de(W^P,8),H=H+W|0,R=de(R^H,7),O=O+L|0,A=de(A^O,16),q=q+A|0,L=de(L^q,12),O=O+L|0,A=de(A^O,8),q=q+A|0,L=de(L^q,7),C=C+T|0,z=de(z^C,16),B=B+z|0,T=de(T^B,12),C=C+T|0,z=de(z^C,8),B=B+z|0,T=de(T^B,7);let K=0;i[K++]=o+$|0,i[K++]=a+P|0,i[K++]=l+O|0,i[K++]=c+C|0,i[K++]=h+T|0,i[K++]=u+S|0,i[K++]=d+R|0,i[K++]=p+L|0,i[K++]=g+q|0,i[K++]=f+B|0,i[K++]=y+U|0,i[K++]=w+H|0,i[K++]=m+W|0,i[K++]=b+A|0,i[K++]=I+z|0,i[K++]=N+Y|0}const Q1=W1(Y1,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Z1=new Uint8Array(16),Hd=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(Z1.subarray(t))},J1=new Uint8Array(32);function Wd(s,e,t,i,r){const n=s(e,t,J1),o=G1.create(n);r&&Hd(o,r),Hd(o,i);const a=new Uint8Array(16),l=O1(a);qd(l,0,BigInt(r?r.length:0),!0),qd(l,8,BigInt(i.length),!0),o.update(a);const c=o.digest();return Un(n,a),c}const X1=s=>(e,t,i)=>({encrypt(r,n){const o=r.length;n=Fd(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);s(e,t,a,a,1);const l=Wd(s,e,t,a,i);return n.set(l,o),Un(l),n},decrypt(r,n){n=Fd(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),l=Wd(s,e,t,o,i);if(!j1(a,l))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),Un(l),n}}),bw=R1({blockSize:64,nonceLength:12,tagLength:16},X1(Q1));let vw=class extends Su{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Cu(e);const i=Ln(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return Rn(this),this.iHash.update(e),this}digestInto(e){Rn(this),Hc(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:i,finished:r,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Pu=(s,e,t)=>new vw(s,e).update(t).digest();Pu.create=(s,e)=>new vw(s,e);function eE(s,e,t){return Cu(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Pu(s,Ln(t),Ln(e))}const yl=new Uint8Array([0]),Vd=new Uint8Array;function tE(s,e,t,i=32){if(Cu(s),Yo(i),i>255*s.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/s.outputLen);t===void 0&&(t=Vd);const n=new Uint8Array(r*s.outputLen),o=Pu.create(s,e),a=o._cloneInto(),l=new Uint8Array(o.outputLen);for(let c=0;c<r;c++)yl[0]=c+1,a.update(c===0?Vd:l).update(t).update(yl).digestInto(l),n.set(l,s.outputLen*c),o._cloneInto(a);return o.destroy(),a.destroy(),l.fill(0),yl.fill(0),n.slice(0,i)}const sE=(s,e,t,i,r)=>tE(s,eE(s,e,t),i,r);function iE(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),l=i?4:0,c=i?0:4;s.setUint32(e+l,o,i),s.setUint32(e+c,a,i)}function rE(s,e,t){return s&e^~s&t}function nE(s,e,t){return s&e^s&t^e&t}let oE=class extends Su{constructor(e,t,i,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ml(this.buffer)}update(e){Rn(this);const{view:t,buffer:i,blockLen:r}=this;e=Ln(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const l=ml(e);for(;r<=n-o;o+=r)this.process(l,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Rn(this),aw(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(i,0),o=0);for(let u=o;u<r;u++)t[u]=0;iE(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=ml(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=l/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)a.setUint32(4*u,h[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:r,finished:n,destroyed:o,pos:a}=this;return e.length=r,e.pos=a,e.finished=n,e.destroyed=o,r%t&&e.buffer.set(i),e}};const aE=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]),bi=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),vi=new Uint32Array(64);let cE=class extends oE{constructor(){super(64,32,8,!1),this.A=bi[0]|0,this.B=bi[1]|0,this.C=bi[2]|0,this.D=bi[3]|0,this.E=bi[4]|0,this.F=bi[5]|0,this.G=bi[6]|0,this.H=bi[7]|0}get(){const{A:e,B:t,C:i,D:r,E:n,F:o,G:a,H:l}=this;return[e,t,i,r,n,o,a,l]}set(e,t,i,r,n,o,a,l){this.A=e|0,this.B=t|0,this.C=i|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=l|0}process(e,t){for(let u=0;u<16;u++,t+=4)vi[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const d=vi[u-15],p=vi[u-2],g=Bs(d,7)^Bs(d,18)^d>>>3,f=Bs(p,17)^Bs(p,19)^p>>>10;vi[u]=f+vi[u-7]+g+vi[u-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:l,G:c,H:h}=this;for(let u=0;u<64;u++){const d=Bs(a,6)^Bs(a,11)^Bs(a,25),p=h+d+rE(a,l,c)+aE[u]+vi[u]|0,g=(Bs(i,2)^Bs(i,13)^Bs(i,22))+nE(i,r,n)|0;h=c,c=l,l=a,a=o+p|0,o=n,n=r,r=i,i=p+g|0}i=i+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,l=l+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(i,r,n,o,a,l,c,h)}roundClean(){vi.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const Wc=cw(()=>new cE);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Iw=BigInt(0);function Tu(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ew(s){if(!Tu(s))throw new Error("Uint8Array expected")}const lE=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function hE(s){Ew(s);let e="";for(let t=0;t<s.length;t++)e+=lE[s[t]];return e}function uE(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Iw:BigInt("0x"+s)}const ni={_0:48,_9:57,A:65,F:70,a:97,f:102};function Kd(s){if(s>=ni._0&&s<=ni._9)return s-ni._0;if(s>=ni.A&&s<=ni.F)return s-(ni.A-10);if(s>=ni.a&&s<=ni.f)return s-(ni.a-10)}function Aw(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=Kd(s.charCodeAt(n)),a=Kd(s.charCodeAt(n+1));if(o===void 0||a===void 0){const l=s[n]+s[n+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+n)}i[r]=o*16+a}return i}function Gd(s){return Ew(s),uE(hE(Uint8Array.from(s).reverse()))}function dE(s,e){return Aw(s.toString(16).padStart(e*2,"0"))}function pE(s,e){return dE(s,e).reverse()}function Yd(s,e,t){let i;if(typeof e=="string")try{i=Aw(e)}catch(n){throw new Error(s+" must be hex string or Uint8Array, cause: "+n)}else if(Tu(e))i=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");const r=i.length;if(typeof t=="number"&&r!==t)throw new Error(s+" of length "+t+" expected, got "+r);return i}const bl=s=>typeof s=="bigint"&&Iw<=s;function gE(s,e,t){return bl(s)&&bl(e)&&bl(t)&&e<=s&&s<t}function Qd(s,e,t,i){if(!gE(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const fE={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||Tu(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function mE(s,e,t={}){const i=(r,n,o)=>{const a=fE[n];if(typeof a!="function")throw new Error("invalid validator function");const l=s[r];if(!(o&&l===void 0)&&!a(l,s))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+l)};for(const[r,n]of Object.entries(e))i(r,n,!1);for(const[r,n]of Object.entries(t))i(r,n,!0);return s}const Sn=BigInt(0),Da=BigInt(1);function Nw(s,e){const t=s%e;return t>=Sn?t:e+t}function wE(s,e,t){if(e<Sn)throw new Error("invalid exponent, negatives unsupported");if(t<=Sn)throw new Error("invalid modulus");if(t===Da)return Sn;let i=Da;for(;e>Sn;)e&Da&&(i=i*s%t),s=s*s%t,e>>=Da;return i}function Us(s,e,t){let i=s;for(;e-- >Sn;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const zr=BigInt(0),vl=BigInt(1);function yE(s){return mE(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function bE(s){const e=yE(s),{P:t}=e,i=m=>Nw(m,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),l=e.powPminus2||(m=>wE(m,t-BigInt(2),t));function c(m,b,I){const N=i(m*(b-I));return b=i(b-N),I=i(I+N),[b,I]}const h=(e.a-BigInt(2))/BigInt(4);function u(m,b){Qd("u",m,zr,t),Qd("scalar",b,zr,t);const I=b,N=m;let $=vl,P=zr,O=m,C=vl,T=zr,S;for(let L=BigInt(r-1);L>=zr;L--){const q=I>>L&vl;T^=q,S=c(T,$,O),$=S[0],O=S[1],S=c(T,P,C),P=S[0],C=S[1],T=q;const B=$+P,U=i(B*B),H=$-P,W=i(H*H),A=U-W,z=O+C,Y=O-C,K=i(Y*B),be=i(z*H),oe=K+be,Oe=K-be;O=i(oe*oe),C=i(N*i(Oe*Oe)),$=i(U*W),P=i(A*(U+i(h*A)))}S=c(T,$,O),$=S[0],O=S[1],S=c(T,P,C),P=S[0],C=S[1];const R=l(P);return i($*R)}function d(m){return pE(i(m),n)}function p(m){const b=Yd("u coordinate",m,n);return o===32&&(b[31]&=127),Gd(b)}function g(m){const b=Yd("scalar",m),I=b.length;if(I!==n&&I!==o){let N=""+n+" or "+o;throw new Error("invalid scalar, expected "+N+" bytes, got "+I)}return Gd(a(b))}function f(m,b){const I=p(b),N=g(m),$=u(I,N);if($===zr)throw new Error("invalid private or public key received");return d($)}const y=d(e.Gu);function w(m){return f(m,y)}return{scalarMult:f,scalarMultBase:w,getSharedSecret:(m,b)=>f(m,b),getPublicKey:m=>w(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:y}}const Nh=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const vE=BigInt(1),Zd=BigInt(2),IE=BigInt(3),EE=BigInt(5);BigInt(8);function AE(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=Nh,o=s*s%n*s%n,a=Us(o,Zd,n)*o%n,l=Us(a,vE,n)*s%n,c=Us(l,EE,n)*l%n,h=Us(c,e,n)*c%n,u=Us(h,t,n)*h%n,d=Us(u,i,n)*u%n,p=Us(d,r,n)*d%n,g=Us(p,r,n)*d%n,f=Us(g,e,n)*c%n;return{pow_p_5_8:Us(f,Zd,n)*s%n,b2:o}}function NE(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const _h=bE({P:Nh,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=Nh,{pow_p_5_8:t,b2:i}=AE(s);return Nw(Us(t,IE,e)*i,e)},adjustScalarBytes:NE,randomBytes:fa}),_w="base10",Bt="base16",ji="base64pad",ao="base64url",ma="utf8",Cw=0,gi=1,wa=2,_E=0,Jd=1,jo=12,Mu=32;function CE(){const s=_h.utils.randomPrivateKey(),e=_h.getPublicKey(s);return{privateKey:Ae(s,Bt),publicKey:Ae(e,Bt)}}function Ch(){const s=fa(Mu);return Ae(s,Bt)}function SE(s,e){const t=_h.getSharedSecret(Ge(s,Bt),Ge(e,Bt)),i=sE(Wc,t,void 0,void 0,Mu);return Ae(i,Bt)}function nc(s){const e=Wc(Ge(s,Bt));return Ae(e,Bt)}function di(s){const e=Wc(Ge(s,ma));return Ae(e,Bt)}function Sw(s){return Ge(`${s}`,_w)}function br(s){return Number(Ae(s,_w))}function $E(s){const e=Sw(typeof s.type<"u"?s.type:Cw);if(br(e)===gi&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?Ge(s.senderPublicKey,Bt):void 0,i=typeof s.iv<"u"?Ge(s.iv,Bt):fa(jo),r=Ge(s.symKey,Bt),n=bw(r,i).encrypt(Ge(s.message,ma));return $w({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function PE(s){const e=Ge(s.symKey,Bt),{sealed:t,iv:i}=Zo(s),r=bw(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return Ae(r,ma)}function TE(s,e){const t=Sw(wa),i=fa(jo),r=Ge(s,ma);return $w({type:t,sealed:r,iv:i,encoding:e})}function ME(s,e){const{sealed:t}=Zo({encoded:s,encoding:e});return Ae(t,ma)}function $w(s){const{encoding:e=ji}=s;if(br(s.type)===wa)return Ae(Mn([s.type,s.sealed]),e);if(br(s.type)===gi){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ae(Mn([s.type,s.senderPublicKey,s.iv,s.sealed]),e)}return Ae(Mn([s.type,s.iv,s.sealed]),e)}function Zo(s){const{encoded:e,encoding:t=ji}=s,i=Ge(e,t),r=i.slice(_E,Jd),n=Jd;if(br(r)===gi){const c=n+Mu,h=c+jo,u=i.slice(n,c),d=i.slice(c,h),p=i.slice(h);return{type:r,sealed:p,iv:d,senderPublicKey:u}}if(br(r)===wa){const c=i.slice(n),h=fa(jo);return{type:r,sealed:c,iv:h}}const o=n+jo,a=i.slice(n,o),l=i.slice(o);return{type:r,sealed:l,iv:a}}function OE(s,e){const t=Zo({encoded:s,encoding:e==null?void 0:e.encoding});return Pw({type:br(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Ae(t.senderPublicKey,Bt):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Pw(s){const e=(s==null?void 0:s.type)||Cw;if(e===gi){if(typeof(s==null?void 0:s.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(s==null?void 0:s.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:s==null?void 0:s.senderPublicKey,receiverPublicKey:s==null?void 0:s.receiverPublicKey}}function Xd(s){return s.type===gi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function ep(s){return s.type===wa}function xE(s){return new Zm.ec("p256").keyFromPublic({x:_.Buffer.from(s.x,"base64").toString("hex"),y:_.Buffer.from(s.y,"base64").toString("hex")},"hex")}function DE(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function kE(s){return _.Buffer.from(DE(s),"base64")}function jE(s,e){const[t,i,r]=s.split("."),n=kE(r);if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32).toString("hex"),a=n.slice(32,64).toString("hex"),l=`${t}.${i}`,c=Wc(l),h=xE(e),u=Ae(c,Bt);if(!h.verify(u,{r:o,s:a}))throw new Error("Invalid signature");return jn(s).payload}const RE="irn";function _c(s){return(s==null?void 0:s.relay)||{protocol:RE}}function $o(s){const e=$m[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function LE(s,e="-"){const t={},i="relay"+e;return Object.keys(s).forEach(r=>{if(r.startsWith(i)){const n=r.replace(i,""),o=s[r];t[n]=o}}),t}function tp(s){if(!s.includes("wc:")){const c=ow(s);c!=null&&c.includes("wc:")&&(s=c)}s=s.includes("wc://")?s.replace("wc://",""):s,s=s.includes("wc:")?s.replace("wc:",""):s;const e=s.indexOf(":"),t=s.indexOf("?")!==-1?s.indexOf("?"):void 0,i=s.substring(0,e),r=s.substring(e+1,t).split("@"),n=typeof t<"u"?s.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((c,h)=>{a[h]=c});const l=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:UE(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:LE(a),methods:l,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function UE(s){return s.startsWith("//")?s.substring(2):s}function zE(s,e="-"){const t="relay",i={};return Object.keys(s).forEach(r=>{const n=r,o=t+e+n;s[n]&&(i[o]=s[n])}),i}function sp(s){const e=new URLSearchParams,t=zE(s.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",s.symKey),s.expiryTimestamp&&e.set("expiryTimestamp",s.expiryTimestamp.toString()),s.methods&&e.set("methods",s.methods.join(","));const i=e.toString();return`${s.protocol}:${s.topic}@${s.version}?${i}`}function ka(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function Qn(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function FE(s){const e=[];return Object.values(s).forEach(t=>{e.push(...Qn(t.accounts))}),e}function qE(s,e){const t=[];return Object.values(s).forEach(i=>{Qn(i.accounts).includes(e)&&t.push(...i.methods)}),t}function BE(s,e){const t=[];return Object.values(s).forEach(i=>{Qn(i.accounts).includes(e)&&t.push(...i.events)}),t}function Ou(s){return s.includes(":")}function Po(s){return Ou(s)?s.split(":")[0]:s}function HE(s){const e={};return s==null||s.forEach(t=>{var i;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(i=e[r].chains)==null||i.push(`${r}:${n}`)}),e}function ip(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=HE(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=ic(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const WE={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}},VE={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 k(s,e){const{message:t,code:i}=VE[s];return{message:e?`${t} ${e}`:t,code:i}}function Te(s,e){const{message:t,code:i}=WE[s];return{message:e?`${t} ${e}`:t,code:i}}function vr(s,e){return!!Array.isArray(s)}function Jo(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function Kt(s){return typeof s>"u"}function it(s,e){return e&&Kt(s)?!0:typeof s=="string"&&!!s.trim().length}function xu(s,e){return e&&Kt(s)?!0:typeof s=="number"&&!isNaN(s)}function KE(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return dr(r,i)?(i.forEach(o=>{const{accounts:a,methods:l,events:c}=s.namespaces[o],h=Qn(a),u=t[o];(!dr(Xm(o,u),h)||!dr(u.methods,l)||!dr(u.events,c))&&(n=!1)}),n):!1}function Cc(s){return it(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function GE(s){if(it(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Cc(t)}}return!1}function YE(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(it(s,!1)){if(e(s))return!0;const t=ow(s);return e(t)}}catch{}return!1}function QE(s){var e;return(e=s==null?void 0:s.proposer)==null?void 0:e.publicKey}function ZE(s){return s==null?void 0:s.topic}function JE(s,e){let t=null;return it(s==null?void 0:s.publicKey,!1)||(t=k("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function rp(s){let e=!0;return vr(s)?s.length&&(e=s.every(t=>it(t,!1))):e=!1,e}function XE(s,e,t){let i=null;return vr(e)&&e.length?e.forEach(r=>{i||Cc(r)||(i=Te("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Cc(s)||(i=Te("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function eA(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=XE(r,Xm(r,n),`${e} ${t}`);o&&(i=o)}),i}function tA(s,e){let t=null;return vr(s)?s.forEach(i=>{t||GE(i)||(t=Te("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Te("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function sA(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=tA(i==null?void 0:i.accounts,`${e} namespace`);r&&(t=r)}),t}function iA(s,e){let t=null;return rp(s==null?void 0:s.methods)?rp(s==null?void 0:s.events)||(t=Te("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Te("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function Tw(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=iA(i,`${e}, namespace`);r&&(t=r)}),t}function rA(s,e,t){let i=null;if(s&&Jo(s)){const r=Tw(s,e);r&&(i=r);const n=eA(s,e,t);n&&(i=n)}else i=k("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function Il(s,e){let t=null;if(s&&Jo(s)){const i=Tw(s,e);i&&(t=i);const r=sA(s,e);r&&(t=r)}else t=k("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Mw(s){return it(s.protocol,!0)}function nA(s,e){let t=!1;return s?s&&vr(s)&&s.length&&s.forEach(i=>{t=Mw(i)}):t=!0,t}function oA(s){return typeof s=="number"}function is(s){return typeof s<"u"&&typeof s!==null}function aA(s){return!(!s||typeof s!="object"||!s.code||!xu(s.code,!1)||!s.message||!it(s.message,!1))}function cA(s){return!(Kt(s)||!it(s.method,!1))}function lA(s){return!(Kt(s)||Kt(s.result)&&Kt(s.error)||!xu(s.id,!1)||!it(s.jsonrpc,!1))}function hA(s){return!(Kt(s)||!it(s.name,!1))}function np(s,e){return!(!Cc(e)||!FE(s).includes(e))}function uA(s,e,t){return it(t,!1)?qE(s,e).includes(t):!1}function dA(s,e,t){return it(t,!1)?BE(s,e).includes(t):!1}function op(s,e,t){let i=null;const r=pA(s),n=gA(e),o=Object.keys(r),a=Object.keys(n),l=ap(Object.keys(s)),c=ap(Object.keys(e)),h=l.filter(u=>!c.includes(u));return h.length&&(i=k("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
6
+ `)};function E1(s){return _.Buffer.from(JSON.stringify(s)).toString("base64")}function A1(s){return JSON.parse(_.Buffer.from(s,"base64").toString("utf-8"))}function yr(s){if(!s)throw new Error("No recap provided, value is undefined");if(!s.att)throw new Error("No `att` property found");const e=Object.keys(s.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=s.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(r=>{const n=i[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function N1(s,e,t,i={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[s]:_1(e,t,i)}}}function _1(s,e,t={}){e=e==null?void 0:e.sort((r,n)=>r.localeCompare(n));const i=e.map(r=>({[`${s}/${r}`]:[t]}));return Object.assign({},...i)}function fw(s){return yr(s),`urn:recap:${E1(s).replace(/=/g,"")}`}function Qo(s){const e=A1(s.replace("urn:recap:",""));return yr(e),e}function C1(s,e,t){const i=N1(s,e,t);return fw(i)}function S1(s){return s&&s.includes("urn:recap:")}function $1(s,e){const t=Qo(s),i=Qo(e),r=P1(t,i);return fw(r)}function P1(s,e){yr(s),yr(e);const t=Object.keys(s.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),i={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=s.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,l)=>a.localeCompare(l)).forEach(a=>{var l,c;i.att[r]=b1(y1({},i.att[r]),{[a]:((l=s.att[r])==null?void 0:l[a])||((c=e.att[r])==null?void 0:c[a])})})}),i}function T1(s="",e){yr(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(s.includes(t))return s;const i=[];let r=0;Object.keys(e.att).forEach(a=>{const l=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));l.sort((u,d)=>u.action.localeCompare(d.action));const c={};l.forEach(u=>{c[u.ability]||(c[u.ability]=[]),c[u.ability].push(u.action)});const h=Object.keys(c).map(u=>(r++,`(${r}) '${u}': '${c[u].join("', '")}' for '${a}'.`));i.push(h.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${s?s+" ":""}${o}`}function Rd(s){var e;const t=Qo(s);yr(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function Ld(s){const e=Qo(s);yr(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(r=>{var n;(n=r==null?void 0:r[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function rc(s){if(!s)return;const e=s==null?void 0:s[s.length-1];return S1(e)?e:void 0}function wl(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function mw(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ds(s,...e){if(!mw(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Ud(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function M1(s,e){ds(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function zd(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}const zi=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),O1=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),x1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!x1)throw new Error("Non little-endian hardware is not supported");function D1(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Ih(s){if(typeof s=="string")s=D1(s);else if(mw(s))s=Eh(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function k1(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function j1(s,e){if(s.length!==e.length)return!1;let t=0;for(let i=0;i<s.length;i++)t|=s[i]^e[i];return t===0}const R1=(s,e)=>{function t(i,...r){if(ds(i),s.nonceLength!==void 0){const c=r[0];if(!c)throw new Error("nonce / iv required");s.varSizeNonce?ds(c):ds(c,s.nonceLength)}const n=s.tagLength;n&&r[1]!==void 0&&ds(r[1]);const o=e(i,...r),a=(c,h)=>{if(h!==void 0){if(c!==2)throw new Error("cipher output not supported");ds(h)}};let l=!1;return{encrypt(c,h){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ds(c),a(o.encrypt.length,h),o.encrypt(c,h)},decrypt(c,h){if(ds(c),n&&c.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,h),o.decrypt(c,h)}}}return Object.assign(t,s),t};function Fd(s,e,t=!0){if(e===void 0)return new Uint8Array(s);if(e.length!==s)throw new Error("invalid output length, expected "+s+", got: "+e.length);if(t&&!L1(e))throw new Error("invalid output, must be aligned");return e}function qd(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);s.setUint32(e+4,o,i),s.setUint32(e+0,a,i)}function L1(s){return s.byteOffset%4===0}function Eh(s){return Uint8Array.from(s)}function Un(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}const ww=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),U1=ww("expand 16-byte k"),z1=ww("expand 32-byte k"),F1=zi(U1),q1=zi(z1);function de(s,e){return s<<e|s>>>32-e}function Ah(s){return s.byteOffset%4===0}const xa=64,B1=16,yw=2**32-1,Bd=new Uint32Array;function H1(s,e,t,i,r,n,o,a){const l=r.length,c=new Uint8Array(xa),h=zi(c),u=Ah(r)&&Ah(n),d=u?zi(r):Bd,p=u?zi(n):Bd;for(let g=0;g<l;o++){if(s(e,t,i,h,o,a),o>=yw)throw new Error("arx: counter overflow");const f=Math.min(xa,l-g);if(u&&f===xa){const y=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,m;w<B1;w++)m=y+w,p[m]=d[m]^h[w];g+=xa;continue}for(let y=0,w;y<f;y++)w=g+y,n[w]=r[w]^c[y];g+=f}}function W1(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=k1({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return wl(r),wl(o),zd(n),zd(t),(a,l,c,h,u=0)=>{ds(a),ds(l),ds(c);const d=c.length;if(h===void 0&&(h=new Uint8Array(d)),ds(h),wl(u),u<0||u>=yw)throw new Error("arx: counter overflow");if(h.length<d)throw new Error(`arx: output (${h.length}) is shorter than data (${d})`);const p=[];let g=a.length,f,y;if(g===32)p.push(f=Eh(a)),y=q1;else if(g===16&&t)f=new Uint8Array(32),f.set(a),f.set(a,16),y=F1,p.push(f);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Ah(l)||p.push(l=Eh(l));const w=zi(f);if(i){if(l.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(y,w,zi(l.subarray(0,16)),w),l=l.subarray(16)}const m=16-r;if(m!==l.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const I=new Uint8Array(12);I.set(l,n?0:12-l.length),l=I,p.push(l)}const b=zi(l);return H1(s,y,w,b,c,h,u,o),Un(...p),h}}const _t=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let V1=class{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=Ih(e),ds(e,32);const t=_t(e,0),i=_t(e,2),r=_t(e,4),n=_t(e,6),o=_t(e,8),a=_t(e,10),l=_t(e,12),c=_t(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|r<<6)&7939,this.r[3]=(r>>>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|l<<5)&8065,this.r[8]=(l>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let h=0;h<8;h++)this.pad[h]=_t(e,16+2*h)}process(e,t,i=!1){const r=i?0:2048,{h:n,r:o}=this,a=o[0],l=o[1],c=o[2],h=o[3],u=o[4],d=o[5],p=o[6],g=o[7],f=o[8],y=o[9],w=_t(e,t+0),m=_t(e,t+2),b=_t(e,t+4),I=_t(e,t+6),N=_t(e,t+8),$=_t(e,t+10),P=_t(e,t+12),O=_t(e,t+14);let C=n[0]+(w&8191),T=n[1]+((w>>>13|m<<3)&8191),S=n[2]+((m>>>10|b<<6)&8191),R=n[3]+((b>>>7|I<<9)&8191),L=n[4]+((I>>>4|N<<12)&8191),q=n[5]+(N>>>1&8191),B=n[6]+((N>>>14|$<<2)&8191),U=n[7]+(($>>>11|P<<5)&8191),H=n[8]+((P>>>8|O<<8)&8191),W=n[9]+(O>>>5|r),A=0,z=A+C*a+T*(5*y)+S*(5*f)+R*(5*g)+L*(5*p);A=z>>>13,z&=8191,z+=q*(5*d)+B*(5*u)+U*(5*h)+H*(5*c)+W*(5*l),A+=z>>>13,z&=8191;let Y=A+C*l+T*a+S*(5*y)+R*(5*f)+L*(5*g);A=Y>>>13,Y&=8191,Y+=q*(5*p)+B*(5*d)+U*(5*u)+H*(5*h)+W*(5*c),A+=Y>>>13,Y&=8191;let K=A+C*c+T*l+S*a+R*(5*y)+L*(5*f);A=K>>>13,K&=8191,K+=q*(5*g)+B*(5*p)+U*(5*d)+H*(5*u)+W*(5*h),A+=K>>>13,K&=8191;let be=A+C*h+T*c+S*l+R*a+L*(5*y);A=be>>>13,be&=8191,be+=q*(5*f)+B*(5*g)+U*(5*p)+H*(5*d)+W*(5*u),A+=be>>>13,be&=8191;let oe=A+C*u+T*h+S*c+R*l+L*a;A=oe>>>13,oe&=8191,oe+=q*(5*y)+B*(5*f)+U*(5*g)+H*(5*p)+W*(5*d),A+=oe>>>13,oe&=8191;let Oe=A+C*d+T*u+S*h+R*c+L*l;A=Oe>>>13,Oe&=8191,Oe+=q*a+B*(5*y)+U*(5*f)+H*(5*g)+W*(5*p),A+=Oe>>>13,Oe&=8191;let lt=A+C*p+T*d+S*u+R*h+L*c;A=lt>>>13,lt&=8191,lt+=q*l+B*a+U*(5*y)+H*(5*f)+W*(5*g),A+=lt>>>13,lt&=8191;let Be=A+C*g+T*p+S*d+R*u+L*h;A=Be>>>13,Be&=8191,Be+=q*c+B*l+U*a+H*(5*y)+W*(5*f),A+=Be>>>13,Be&=8191;let Qe=A+C*f+T*g+S*p+R*d+L*u;A=Qe>>>13,Qe&=8191,Qe+=q*h+B*c+U*l+H*a+W*(5*y),A+=Qe>>>13,Qe&=8191;let He=A+C*y+T*f+S*g+R*p+L*d;A=He>>>13,He&=8191,He+=q*u+B*h+U*c+H*l+W*a,A+=He>>>13,He&=8191,A=(A<<2)+A|0,A=A+z|0,z=A&8191,A=A>>>13,Y+=A,n[0]=z,n[1]=Y,n[2]=K,n[3]=be,n[4]=oe,n[5]=Oe,n[6]=lt,n[7]=Be,n[8]=Qe,n[9]=He}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,i[0]=e[0]+5,r=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+r,r=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;Un(i)}update(e){Ud(this);const{buffer:t,blockLen:i}=this;e=Ih(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){for(;i<=r-n;n+=i)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Un(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ud(this),M1(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}};function K1(s){const e=(i,r)=>s(r).update(Ih(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const G1=K1(s=>new V1(s));function Y1(s,e,t,i,r,n=20){let o=s[0],a=s[1],l=s[2],c=s[3],h=e[0],u=e[1],d=e[2],p=e[3],g=e[4],f=e[5],y=e[6],w=e[7],m=r,b=t[0],I=t[1],N=t[2],$=o,P=a,O=l,C=c,T=h,S=u,R=d,L=p,q=g,B=f,U=y,H=w,W=m,A=b,z=I,Y=N;for(let be=0;be<n;be+=2)$=$+T|0,W=de(W^$,16),q=q+W|0,T=de(T^q,12),$=$+T|0,W=de(W^$,8),q=q+W|0,T=de(T^q,7),P=P+S|0,A=de(A^P,16),B=B+A|0,S=de(S^B,12),P=P+S|0,A=de(A^P,8),B=B+A|0,S=de(S^B,7),O=O+R|0,z=de(z^O,16),U=U+z|0,R=de(R^U,12),O=O+R|0,z=de(z^O,8),U=U+z|0,R=de(R^U,7),C=C+L|0,Y=de(Y^C,16),H=H+Y|0,L=de(L^H,12),C=C+L|0,Y=de(Y^C,8),H=H+Y|0,L=de(L^H,7),$=$+S|0,Y=de(Y^$,16),U=U+Y|0,S=de(S^U,12),$=$+S|0,Y=de(Y^$,8),U=U+Y|0,S=de(S^U,7),P=P+R|0,W=de(W^P,16),H=H+W|0,R=de(R^H,12),P=P+R|0,W=de(W^P,8),H=H+W|0,R=de(R^H,7),O=O+L|0,A=de(A^O,16),q=q+A|0,L=de(L^q,12),O=O+L|0,A=de(A^O,8),q=q+A|0,L=de(L^q,7),C=C+T|0,z=de(z^C,16),B=B+z|0,T=de(T^B,12),C=C+T|0,z=de(z^C,8),B=B+z|0,T=de(T^B,7);let K=0;i[K++]=o+$|0,i[K++]=a+P|0,i[K++]=l+O|0,i[K++]=c+C|0,i[K++]=h+T|0,i[K++]=u+S|0,i[K++]=d+R|0,i[K++]=p+L|0,i[K++]=g+q|0,i[K++]=f+B|0,i[K++]=y+U|0,i[K++]=w+H|0,i[K++]=m+W|0,i[K++]=b+A|0,i[K++]=I+z|0,i[K++]=N+Y|0}const Q1=W1(Y1,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Z1=new Uint8Array(16),Hd=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(Z1.subarray(t))},J1=new Uint8Array(32);function Wd(s,e,t,i,r){const n=s(e,t,J1),o=G1.create(n);r&&Hd(o,r),Hd(o,i);const a=new Uint8Array(16),l=O1(a);qd(l,0,BigInt(r?r.length:0),!0),qd(l,8,BigInt(i.length),!0),o.update(a);const c=o.digest();return Un(n,a),c}const X1=s=>(e,t,i)=>({encrypt(r,n){const o=r.length;n=Fd(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);s(e,t,a,a,1);const l=Wd(s,e,t,a,i);return n.set(l,o),Un(l),n},decrypt(r,n){n=Fd(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),l=Wd(s,e,t,o,i);if(!j1(a,l))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),Un(l),n}}),bw=R1({blockSize:64,nonceLength:12,tagLength:16},X1(Q1));let vw=class extends Su{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Cu(e);const i=Ln(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return Rn(this),this.iHash.update(e),this}digestInto(e){Rn(this),Hc(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:i,finished:r,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Pu=(s,e,t)=>new vw(s,e).update(t).digest();Pu.create=(s,e)=>new vw(s,e);function eE(s,e,t){return Cu(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Pu(s,Ln(t),Ln(e))}const yl=new Uint8Array([0]),Vd=new Uint8Array;function tE(s,e,t,i=32){if(Cu(s),Yo(i),i>255*s.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/s.outputLen);t===void 0&&(t=Vd);const n=new Uint8Array(r*s.outputLen),o=Pu.create(s,e),a=o._cloneInto(),l=new Uint8Array(o.outputLen);for(let c=0;c<r;c++)yl[0]=c+1,a.update(c===0?Vd:l).update(t).update(yl).digestInto(l),n.set(l,s.outputLen*c),o._cloneInto(a);return o.destroy(),a.destroy(),l.fill(0),yl.fill(0),n.slice(0,i)}const sE=(s,e,t,i,r)=>tE(s,eE(s,e,t),i,r);function iE(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),l=i?4:0,c=i?0:4;s.setUint32(e+l,o,i),s.setUint32(e+c,a,i)}function rE(s,e,t){return s&e^~s&t}function nE(s,e,t){return s&e^s&t^e&t}let oE=class extends Su{constructor(e,t,i,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ml(this.buffer)}update(e){Rn(this);const{view:t,buffer:i,blockLen:r}=this;e=Ln(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const l=ml(e);for(;r<=n-o;o+=r)this.process(l,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Rn(this),aw(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(i,0),o=0);for(let u=o;u<r;u++)t[u]=0;iE(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=ml(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=l/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)a.setUint32(4*u,h[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:r,finished:n,destroyed:o,pos:a}=this;return e.length=r,e.pos=a,e.finished=n,e.destroyed=o,r%t&&e.buffer.set(i),e}};const aE=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]),bi=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),vi=new Uint32Array(64);let cE=class extends oE{constructor(){super(64,32,8,!1),this.A=bi[0]|0,this.B=bi[1]|0,this.C=bi[2]|0,this.D=bi[3]|0,this.E=bi[4]|0,this.F=bi[5]|0,this.G=bi[6]|0,this.H=bi[7]|0}get(){const{A:e,B:t,C:i,D:r,E:n,F:o,G:a,H:l}=this;return[e,t,i,r,n,o,a,l]}set(e,t,i,r,n,o,a,l){this.A=e|0,this.B=t|0,this.C=i|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=l|0}process(e,t){for(let u=0;u<16;u++,t+=4)vi[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const d=vi[u-15],p=vi[u-2],g=Bs(d,7)^Bs(d,18)^d>>>3,f=Bs(p,17)^Bs(p,19)^p>>>10;vi[u]=f+vi[u-7]+g+vi[u-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:l,G:c,H:h}=this;for(let u=0;u<64;u++){const d=Bs(a,6)^Bs(a,11)^Bs(a,25),p=h+d+rE(a,l,c)+aE[u]+vi[u]|0,g=(Bs(i,2)^Bs(i,13)^Bs(i,22))+nE(i,r,n)|0;h=c,c=l,l=a,a=o+p|0,o=n,n=r,r=i,i=p+g|0}i=i+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,l=l+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(i,r,n,o,a,l,c,h)}roundClean(){vi.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const Wc=cw(()=>new cE);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Iw=BigInt(0);function Tu(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ew(s){if(!Tu(s))throw new Error("Uint8Array expected")}const lE=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function hE(s){Ew(s);let e="";for(let t=0;t<s.length;t++)e+=lE[s[t]];return e}function uE(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Iw:BigInt("0x"+s)}const ni={_0:48,_9:57,A:65,F:70,a:97,f:102};function Kd(s){if(s>=ni._0&&s<=ni._9)return s-ni._0;if(s>=ni.A&&s<=ni.F)return s-(ni.A-10);if(s>=ni.a&&s<=ni.f)return s-(ni.a-10)}function Aw(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=Kd(s.charCodeAt(n)),a=Kd(s.charCodeAt(n+1));if(o===void 0||a===void 0){const l=s[n]+s[n+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+n)}i[r]=o*16+a}return i}function Gd(s){return Ew(s),uE(hE(Uint8Array.from(s).reverse()))}function dE(s,e){return Aw(s.toString(16).padStart(e*2,"0"))}function pE(s,e){return dE(s,e).reverse()}function Yd(s,e,t){let i;if(typeof e=="string")try{i=Aw(e)}catch(n){throw new Error(s+" must be hex string or Uint8Array, cause: "+n)}else if(Tu(e))i=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");const r=i.length;if(typeof t=="number"&&r!==t)throw new Error(s+" of length "+t+" expected, got "+r);return i}const bl=s=>typeof s=="bigint"&&Iw<=s;function gE(s,e,t){return bl(s)&&bl(e)&&bl(t)&&e<=s&&s<t}function Qd(s,e,t,i){if(!gE(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const fE={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||Tu(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function mE(s,e,t={}){const i=(r,n,o)=>{const a=fE[n];if(typeof a!="function")throw new Error("invalid validator function");const l=s[r];if(!(o&&l===void 0)&&!a(l,s))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+l)};for(const[r,n]of Object.entries(e))i(r,n,!1);for(const[r,n]of Object.entries(t))i(r,n,!0);return s}const Sn=BigInt(0),Da=BigInt(1);function Nw(s,e){const t=s%e;return t>=Sn?t:e+t}function wE(s,e,t){if(e<Sn)throw new Error("invalid exponent, negatives unsupported");if(t<=Sn)throw new Error("invalid modulus");if(t===Da)return Sn;let i=Da;for(;e>Sn;)e&Da&&(i=i*s%t),s=s*s%t,e>>=Da;return i}function Us(s,e,t){let i=s;for(;e-- >Sn;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const zr=BigInt(0),vl=BigInt(1);function yE(s){return mE(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function bE(s){const e=yE(s),{P:t}=e,i=m=>Nw(m,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),l=e.powPminus2||(m=>wE(m,t-BigInt(2),t));function c(m,b,I){const N=i(m*(b-I));return b=i(b-N),I=i(I+N),[b,I]}const h=(e.a-BigInt(2))/BigInt(4);function u(m,b){Qd("u",m,zr,t),Qd("scalar",b,zr,t);const I=b,N=m;let $=vl,P=zr,O=m,C=vl,T=zr,S;for(let L=BigInt(r-1);L>=zr;L--){const q=I>>L&vl;T^=q,S=c(T,$,O),$=S[0],O=S[1],S=c(T,P,C),P=S[0],C=S[1],T=q;const B=$+P,U=i(B*B),H=$-P,W=i(H*H),A=U-W,z=O+C,Y=O-C,K=i(Y*B),be=i(z*H),oe=K+be,Oe=K-be;O=i(oe*oe),C=i(N*i(Oe*Oe)),$=i(U*W),P=i(A*(U+i(h*A)))}S=c(T,$,O),$=S[0],O=S[1],S=c(T,P,C),P=S[0],C=S[1];const R=l(P);return i($*R)}function d(m){return pE(i(m),n)}function p(m){const b=Yd("u coordinate",m,n);return o===32&&(b[31]&=127),Gd(b)}function g(m){const b=Yd("scalar",m),I=b.length;if(I!==n&&I!==o){let N=""+n+" or "+o;throw new Error("invalid scalar, expected "+N+" bytes, got "+I)}return Gd(a(b))}function f(m,b){const I=p(b),N=g(m),$=u(I,N);if($===zr)throw new Error("invalid private or public key received");return d($)}const y=d(e.Gu);function w(m){return f(m,y)}return{scalarMult:f,scalarMultBase:w,getSharedSecret:(m,b)=>f(m,b),getPublicKey:m=>w(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:y}}const Nh=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const vE=BigInt(1),Zd=BigInt(2),IE=BigInt(3),EE=BigInt(5);BigInt(8);function AE(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=Nh,o=s*s%n*s%n,a=Us(o,Zd,n)*o%n,l=Us(a,vE,n)*s%n,c=Us(l,EE,n)*l%n,h=Us(c,e,n)*c%n,u=Us(h,t,n)*h%n,d=Us(u,i,n)*u%n,p=Us(d,r,n)*d%n,g=Us(p,r,n)*d%n,f=Us(g,e,n)*c%n;return{pow_p_5_8:Us(f,Zd,n)*s%n,b2:o}}function NE(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const _h=bE({P:Nh,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=Nh,{pow_p_5_8:t,b2:i}=AE(s);return Nw(Us(t,IE,e)*i,e)},adjustScalarBytes:NE,randomBytes:fa}),_w="base10",Bt="base16",ji="base64pad",ao="base64url",ma="utf8",Cw=0,gi=1,wa=2,_E=0,Jd=1,jo=12,Mu=32;function CE(){const s=_h.utils.randomPrivateKey(),e=_h.getPublicKey(s);return{privateKey:Ae(s,Bt),publicKey:Ae(e,Bt)}}function Ch(){const s=fa(Mu);return Ae(s,Bt)}function SE(s,e){const t=_h.getSharedSecret(Ge(s,Bt),Ge(e,Bt)),i=sE(Wc,t,void 0,void 0,Mu);return Ae(i,Bt)}function nc(s){const e=Wc(Ge(s,Bt));return Ae(e,Bt)}function di(s){const e=Wc(Ge(s,ma));return Ae(e,Bt)}function Sw(s){return Ge(`${s}`,_w)}function br(s){return Number(Ae(s,_w))}function $E(s){const e=Sw(typeof s.type<"u"?s.type:Cw);if(br(e)===gi&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?Ge(s.senderPublicKey,Bt):void 0,i=typeof s.iv<"u"?Ge(s.iv,Bt):fa(jo),r=Ge(s.symKey,Bt),n=bw(r,i).encrypt(Ge(s.message,ma));return $w({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function PE(s){const e=Ge(s.symKey,Bt),{sealed:t,iv:i}=Zo(s),r=bw(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return Ae(r,ma)}function TE(s,e){const t=Sw(wa),i=fa(jo),r=Ge(s,ma);return $w({type:t,sealed:r,iv:i,encoding:e})}function ME(s,e){const{sealed:t}=Zo({encoded:s,encoding:e});return Ae(t,ma)}function $w(s){const{encoding:e=ji}=s;if(br(s.type)===wa)return Ae(Mn([s.type,s.sealed]),e);if(br(s.type)===gi){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ae(Mn([s.type,s.senderPublicKey,s.iv,s.sealed]),e)}return Ae(Mn([s.type,s.iv,s.sealed]),e)}function Zo(s){const{encoded:e,encoding:t=ji}=s,i=Ge(e,t),r=i.slice(_E,Jd),n=Jd;if(br(r)===gi){const c=n+Mu,h=c+jo,u=i.slice(n,c),d=i.slice(c,h),p=i.slice(h);return{type:r,sealed:p,iv:d,senderPublicKey:u}}if(br(r)===wa){const c=i.slice(n),h=fa(jo);return{type:r,sealed:c,iv:h}}const o=n+jo,a=i.slice(n,o),l=i.slice(o);return{type:r,sealed:l,iv:a}}function OE(s,e){const t=Zo({encoded:s,encoding:e==null?void 0:e.encoding});return Pw({type:br(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Ae(t.senderPublicKey,Bt):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Pw(s){const e=(s==null?void 0:s.type)||Cw;if(e===gi){if(typeof(s==null?void 0:s.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(s==null?void 0:s.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:s==null?void 0:s.senderPublicKey,receiverPublicKey:s==null?void 0:s.receiverPublicKey}}function Xd(s){return s.type===gi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function ep(s){return s.type===wa}function xE(s){return new Zm.ec("p256").keyFromPublic({x:_.Buffer.from(s.x,"base64").toString("hex"),y:_.Buffer.from(s.y,"base64").toString("hex")},"hex")}function DE(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function kE(s){return _.Buffer.from(DE(s),"base64")}function jE(s,e){const[t,i,r]=s.split("."),n=kE(r);if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32).toString("hex"),a=n.slice(32,64).toString("hex"),l=`${t}.${i}`,c=Wc(l),h=xE(e),u=Ae(c,Bt);if(!h.verify(u,{r:o,s:a}))throw new Error("Invalid signature");return jn(s).payload}const RE="irn";function _c(s){return(s==null?void 0:s.relay)||{protocol:RE}}function $o(s){const e=Cm[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function LE(s,e="-"){const t={},i="relay"+e;return Object.keys(s).forEach(r=>{if(r.startsWith(i)){const n=r.replace(i,""),o=s[r];t[n]=o}}),t}function tp(s){if(!s.includes("wc:")){const c=ow(s);c!=null&&c.includes("wc:")&&(s=c)}s=s.includes("wc://")?s.replace("wc://",""):s,s=s.includes("wc:")?s.replace("wc:",""):s;const e=s.indexOf(":"),t=s.indexOf("?")!==-1?s.indexOf("?"):void 0,i=s.substring(0,e),r=s.substring(e+1,t).split("@"),n=typeof t<"u"?s.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((c,h)=>{a[h]=c});const l=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:UE(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:LE(a),methods:l,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function UE(s){return s.startsWith("//")?s.substring(2):s}function zE(s,e="-"){const t="relay",i={};return Object.keys(s).forEach(r=>{const n=r,o=t+e+n;s[n]&&(i[o]=s[n])}),i}function sp(s){const e=new URLSearchParams,t=zE(s.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",s.symKey),s.expiryTimestamp&&e.set("expiryTimestamp",s.expiryTimestamp.toString()),s.methods&&e.set("methods",s.methods.join(","));const i=e.toString();return`${s.protocol}:${s.topic}@${s.version}?${i}`}function ka(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function Qn(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function FE(s){const e=[];return Object.values(s).forEach(t=>{e.push(...Qn(t.accounts))}),e}function qE(s,e){const t=[];return Object.values(s).forEach(i=>{Qn(i.accounts).includes(e)&&t.push(...i.methods)}),t}function BE(s,e){const t=[];return Object.values(s).forEach(i=>{Qn(i.accounts).includes(e)&&t.push(...i.events)}),t}function Ou(s){return s.includes(":")}function Po(s){return Ou(s)?s.split(":")[0]:s}function HE(s){const e={};return s==null||s.forEach(t=>{var i;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(i=e[r].chains)==null||i.push(`${r}:${n}`)}),e}function ip(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=HE(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=ic(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const WE={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}},VE={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 k(s,e){const{message:t,code:i}=VE[s];return{message:e?`${t} ${e}`:t,code:i}}function Te(s,e){const{message:t,code:i}=WE[s];return{message:e?`${t} ${e}`:t,code:i}}function vr(s,e){return!!Array.isArray(s)}function Jo(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function Kt(s){return typeof s>"u"}function it(s,e){return e&&Kt(s)?!0:typeof s=="string"&&!!s.trim().length}function xu(s,e){return e&&Kt(s)?!0:typeof s=="number"&&!isNaN(s)}function KE(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return dr(r,i)?(i.forEach(o=>{const{accounts:a,methods:l,events:c}=s.namespaces[o],h=Qn(a),u=t[o];(!dr(Xm(o,u),h)||!dr(u.methods,l)||!dr(u.events,c))&&(n=!1)}),n):!1}function Cc(s){return it(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function GE(s){if(it(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Cc(t)}}return!1}function YE(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(it(s,!1)){if(e(s))return!0;const t=ow(s);return e(t)}}catch{}return!1}function QE(s){var e;return(e=s==null?void 0:s.proposer)==null?void 0:e.publicKey}function ZE(s){return s==null?void 0:s.topic}function JE(s,e){let t=null;return it(s==null?void 0:s.publicKey,!1)||(t=k("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function rp(s){let e=!0;return vr(s)?s.length&&(e=s.every(t=>it(t,!1))):e=!1,e}function XE(s,e,t){let i=null;return vr(e)&&e.length?e.forEach(r=>{i||Cc(r)||(i=Te("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Cc(s)||(i=Te("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function eA(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=XE(r,Xm(r,n),`${e} ${t}`);o&&(i=o)}),i}function tA(s,e){let t=null;return vr(s)?s.forEach(i=>{t||GE(i)||(t=Te("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Te("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function sA(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=tA(i==null?void 0:i.accounts,`${e} namespace`);r&&(t=r)}),t}function iA(s,e){let t=null;return rp(s==null?void 0:s.methods)?rp(s==null?void 0:s.events)||(t=Te("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Te("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function Tw(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=iA(i,`${e}, namespace`);r&&(t=r)}),t}function rA(s,e,t){let i=null;if(s&&Jo(s)){const r=Tw(s,e);r&&(i=r);const n=eA(s,e,t);n&&(i=n)}else i=k("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function Il(s,e){let t=null;if(s&&Jo(s)){const i=Tw(s,e);i&&(t=i);const r=sA(s,e);r&&(t=r)}else t=k("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Mw(s){return it(s.protocol,!0)}function nA(s,e){let t=!1;return s?s&&vr(s)&&s.length&&s.forEach(i=>{t=Mw(i)}):t=!0,t}function oA(s){return typeof s=="number"}function is(s){return typeof s<"u"&&typeof s!==null}function aA(s){return!(!s||typeof s!="object"||!s.code||!xu(s.code,!1)||!s.message||!it(s.message,!1))}function cA(s){return!(Kt(s)||!it(s.method,!1))}function lA(s){return!(Kt(s)||Kt(s.result)&&Kt(s.error)||!xu(s.id,!1)||!it(s.jsonrpc,!1))}function hA(s){return!(Kt(s)||!it(s.name,!1))}function np(s,e){return!(!Cc(e)||!FE(s).includes(e))}function uA(s,e,t){return it(t,!1)?qE(s,e).includes(t):!1}function dA(s,e,t){return it(t,!1)?BE(s,e).includes(t):!1}function op(s,e,t){let i=null;const r=pA(s),n=gA(e),o=Object.keys(r),a=Object.keys(n),l=ap(Object.keys(s)),c=ap(Object.keys(e)),h=l.filter(u=>!c.includes(u));return h.length&&(i=k("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
7
7
  Required: ${h.toString()}
8
8
  Received: ${Object.keys(e).toString()}`)),dr(o,a)||(i=k("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces.
9
9
  Required: ${o.toString()}
10
10
  Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||i)return;const d=Qn(e[u].accounts);d.includes(u)||(i=k("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${u}
11
11
  Required: ${u}
12
- Approved: ${d.toString()}`))}),o.forEach(u=>{i||(dr(r[u].methods,n[u].methods)?dr(r[u].events,n[u].events)||(i=k("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):i=k("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),i}function pA(s){const e={};return Object.keys(s).forEach(t=>{var i;t.includes(":")?e[t]=s[t]:(i=s[t].chains)==null||i.forEach(r=>{e[r]={methods:s[t].methods,events:s[t].events}})}),e}function ap(s){return[...new Set(s.map(e=>e.includes(":")?e.split(":")[0]:e))]}function gA(s){const e={};return Object.keys(s).forEach(t=>{if(t.includes(":"))e[t]=s[t];else{const i=Qn(s[t].accounts);i==null||i.forEach(r=>{e[r]={accounts:s[t].accounts.filter(n=>n.includes(`${r}:`)),methods:s[t].methods,events:s[t].events}})}}),e}function fA(s,e){return xu(s,!1)&&s<=e.max&&s>=e.min}function cp(){const s=ga();return new Promise(e=>{switch(s){case fs.browser:e(mA());break;case fs.reactNative:e(wA());break;case fs.node:e(yA());break;default:e(!0)}})}function mA(){return pa()&&(navigator==null?void 0:navigator.onLine)}async function wA(){if(Gi()&&typeof _.global<"u"&&_.global!=null&&_.global.NetInfo){const s=await(_.global==null?void 0:_.global.NetInfo.fetch());return s==null?void 0:s.isConnected}return!0}function yA(){return!0}function bA(s){switch(ga()){case fs.browser:vA(s);break;case fs.reactNative:IA(s);break}}function vA(s){!Gi()&&pa()&&(window.addEventListener("online",()=>s(!0)),window.addEventListener("offline",()=>s(!1)))}function IA(s){var e;Gi()&&typeof _.global<"u"&&_.global!=null&&_.global.NetInfo&&((e=_.global)==null||e.NetInfo.addEventListener(t=>s(t==null?void 0:t.isConnected)))}const El={};let co=class{static get(e){return El[e]}static set(e,t){El[e]=t}static delete(e){delete El[e]}},Ye=class extends bv{constructor(e){super(e),this.events=new kt.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(Gt(e.method,e.params||[],e.id||gs().toString()),t)}async requestStrict(e,t){return new Promise(async(i,r)=>{if(!this.connection.connected)try{await this.open()}catch(n){r(n)}this.events.on(`${e.id}`,n=>{st(n)?r(n.error):i(n.result)});try{await this.connection.send(e,t)}catch(n){r(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),$r(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const EA=()=>typeof WebSocket<"u"?WebSocket:typeof _.global<"u"&&typeof _.global.WebSocket<"u"?_.global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),AA=()=>typeof WebSocket<"u"||typeof _.global<"u"&&typeof _.global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",lp=s=>s.split("?")[0],hp=10,NA=EA();let Ow=class{constructor(e){if(this.url=e,this.events=new kt.EventEmitter,this.registering=!1,!cd(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,t)=>{if(typeof this.socket>"u"){t(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Sr(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!cd(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,r)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),r(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return r(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,i)=>{const r=vv.isReactNative()?void 0:{rejectUnauthorized:!Iv(e)},n=new NA(e,[],r);AA()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),t(n)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?wi(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),r=i.message||i.toString(),n=ca(e,r);this.events.emit("payload",n)}parseError(e,t=this.url){return Ev(e,lp(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>hp&&this.events.setMaxListeners(hp)}emitError(e){const t=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${lp(this.url)}`));return this.events.emit("register_error",t),t}};const xw="wc",Dw=2,Sh="core",si=`${xw}@2:${Sh}:`,_A={logger:"error"},CA={database:":memory:"},SA="crypto",up="client_ed25519_seed",$A=E.ONE_DAY,PA="keychain",TA="0.3",MA="messages",OA="0.3",dp=E.SIX_HOURS,xA="publisher",kw="irn",DA="error",jw="wss://relay.walletconnect.org",kA="relayer",It={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},jA="_subscription",Is={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},RA=.1,$h="2.19.0",Ve={link_mode:"link_mode",relay:"relay"},LA="0.3",UA="WALLETCONNECT_CLIENT_ID",pp="WALLETCONNECT_LINK_MODE_APPS",hs={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},zA="subscription",FA="0.3",qA=E.FIVE_SECONDS*1e3,BA="pairing",HA="0.3",lo={wc_pairingDelete:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:E.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:E.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:E.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:E.ONE_DAY,prompt:!1,tag:0},res:{ttl:E.ONE_DAY,prompt:!1,tag:0}}},cr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Os={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},WA="history",VA="0.3",KA="expirer",Cs={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},GA="0.3",YA="verify-api",QA="https://verify.walletconnect.com",Rw="https://verify.walletconnect.org",Ro=Rw,ZA=`${Ro}/v3`,JA=[QA,Rw],XA="echo",eN="https://echo.walletconnect.com",Zs={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},hi={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"},xs={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"},Xi={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"},er={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},ho={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},tN=.1,sN="event-client",iN=86400,rN="https://pulse.walletconnect.org/batch";function nN(s,e){if(s.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var r=0;r<s.length;r++){var n=s.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=s.length,l=s.charAt(0),c=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var f=0,y=0,w=0,m=g.length;w!==m&&g[w]===0;)w++,f++;for(var b=(m-w)*h+1>>>0,I=new Uint8Array(b);w!==m;){for(var N=g[w],$=0,P=b-1;(N!==0||$<y)&&P!==-1;P--,$++)N+=256*I[P]>>>0,I[P]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");y=$,w++}for(var O=b-y;O!==b&&I[O]===0;)O++;for(var C=l.repeat(f);O<b;++O)C+=s.charAt(I[O]);return C}function d(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var f=0;if(g[f]!==" "){for(var y=0,w=0;g[f]===l;)y++,f++;for(var m=(g.length-f)*c+1>>>0,b=new Uint8Array(m);g[f];){var I=t[g.charCodeAt(f)];if(I===255)return;for(var N=0,$=m-1;(I!==0||N<w)&&$!==-1;$--,N++)I+=a*b[$]>>>0,b[$]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");w=N,f++}if(g[f]!==" "){for(var P=m-w;P!==m&&b[P]===0;)P++;for(var O=new Uint8Array(y+(m-P)),C=y;P!==m;)O[C++]=b[P++];return O}}}function p(g){var f=d(g);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:p}}var oN=nN,aN=oN;const Lw=s=>{if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);throw new Error("Unknown type, must be binary type")},cN=s=>new TextEncoder().encode(s),lN=s=>new TextDecoder().decode(s);let hN=class{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},uN=class{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Uw(this,e)}},dN=class{constructor(e){this.decoders=e}or(e){return Uw(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Uw=(s,e)=>new dN({...s.decoders||{[s.prefix]:s},...e.decoders||{[e.prefix]:e}});let pN=class{constructor(e,t,i,r){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=r,this.encoder=new hN(e,t,i),this.decoder=new uN(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Vc=({name:s,prefix:e,encode:t,decode:i})=>new pN(s,e,t,i),ya=({prefix:s,name:e,alphabet:t})=>{const{encode:i,decode:r}=aN(t,e);return Vc({prefix:s,name:e,encode:i,decode:n=>Lw(r(n))})},gN=(s,e,t,i)=>{const r={};for(let h=0;h<e.length;++h)r[e[h]]=h;let n=s.length;for(;s[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,l=0,c=0;for(let h=0;h<n;++h){const u=r[s[h]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);l=l<<t|u,a+=t,a>=8&&(a-=8,o[c++]=255&l>>a)}if(a>=t||255&l<<8-a)throw new SyntaxError("Unexpected end of data");return o},fN=(s,e,t)=>{const i=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Rt=({name:s,prefix:e,bitsPerChar:t,alphabet:i})=>Vc({prefix:e,name:s,encode(r){return fN(r,i,t)},decode(r){return gN(r,i,t,s)}}),mN=Vc({prefix:"\0",name:"identity",encode:s=>lN(s),decode:s=>cN(s)});var wN=Object.freeze({__proto__:null,identity:mN});const yN=Rt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var bN=Object.freeze({__proto__:null,base2:yN});const vN=Rt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var IN=Object.freeze({__proto__:null,base8:vN});const EN=ya({prefix:"9",name:"base10",alphabet:"0123456789"});var AN=Object.freeze({__proto__:null,base10:EN});const NN=Rt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_N=Rt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var CN=Object.freeze({__proto__:null,base16:NN,base16upper:_N});const SN=Rt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$N=Rt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),PN=Rt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),TN=Rt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),MN=Rt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ON=Rt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xN=Rt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),DN=Rt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),kN=Rt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var jN=Object.freeze({__proto__:null,base32:SN,base32upper:$N,base32pad:PN,base32padupper:TN,base32hex:MN,base32hexupper:ON,base32hexpad:xN,base32hexpadupper:DN,base32z:kN});const RN=ya({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),LN=ya({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var UN=Object.freeze({__proto__:null,base36:RN,base36upper:LN});const zN=ya({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),FN=ya({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qN=Object.freeze({__proto__:null,base58btc:zN,base58flickr:FN});const BN=Rt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),HN=Rt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),WN=Rt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),VN=Rt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var KN=Object.freeze({__proto__:null,base64:BN,base64pad:HN,base64url:WN,base64urlpad:VN});const zw=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),GN=zw.reduce((s,e,t)=>(s[t]=e,s),[]),YN=zw.reduce((s,e,t)=>(s[e.codePointAt(0)]=t,s),[]);function QN(s){return s.reduce((e,t)=>(e+=GN[t],e),"")}function ZN(s){const e=[];for(const t of s){const i=YN[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const JN=Vc({prefix:"🚀",name:"base256emoji",encode:QN,decode:ZN});var XN=Object.freeze({__proto__:null,base256emoji:JN}),e_=Fw,gp=128,t_=-128,s_=Math.pow(2,31);function Fw(s,e,t){e=e||[],t=t||0;for(var i=t;s>=s_;)e[t++]=s&255|gp,s/=128;for(;s&t_;)e[t++]=s&255|gp,s>>>=7;return e[t]=s|0,Fw.bytes=t-i+1,e}var i_=Ph,r_=128,fp=127;function Ph(s,i){var t=0,i=i||0,r=0,n=i,o,a=s.length;do{if(n>=a)throw Ph.bytes=0,new RangeError("Could not decode varint");o=s[n++],t+=r<28?(o&fp)<<r:(o&fp)*Math.pow(2,r),r+=7}while(o>=r_);return Ph.bytes=n-i,t}var n_=Math.pow(2,7),o_=Math.pow(2,14),a_=Math.pow(2,21),c_=Math.pow(2,28),l_=Math.pow(2,35),h_=Math.pow(2,42),u_=Math.pow(2,49),d_=Math.pow(2,56),p_=Math.pow(2,63),g_=function(s){return s<n_?1:s<o_?2:s<a_?3:s<c_?4:s<l_?5:s<h_?6:s<u_?7:s<d_?8:s<p_?9:10},f_={encode:e_,decode:i_,encodingLength:g_},qw=f_;const mp=(s,e,t=0)=>(qw.encode(s,e,t),e),wp=s=>qw.encodingLength(s),Th=(s,e)=>{const t=e.byteLength,i=wp(s),r=i+wp(t),n=new Uint8Array(r+t);return mp(s,n,0),mp(t,n,i),n.set(e,r),new m_(s,t,e,n)};let m_=class{constructor(e,t,i,r){this.code=e,this.size=t,this.digest=i,this.bytes=r}};const Bw=({name:s,code:e,encode:t})=>new w_(s,e,t);let w_=class{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Th(this.code,t):t.then(i=>Th(this.code,i))}else throw Error("Unknown type, must be binary type")}};const Hw=s=>async e=>new Uint8Array(await crypto.subtle.digest(s,e)),y_=Bw({name:"sha2-256",code:18,encode:Hw("SHA-256")}),b_=Bw({name:"sha2-512",code:19,encode:Hw("SHA-512")});var v_=Object.freeze({__proto__:null,sha256:y_,sha512:b_});const Ww=0,I_="identity",Vw=Lw,E_=s=>Th(Ww,Vw(s)),A_={code:Ww,name:I_,encode:Vw,digest:E_};var N_=Object.freeze({__proto__:null,identity:A_});new TextEncoder,new TextDecoder;const yp={...wN,...bN,...IN,...AN,...CN,...jN,...UN,...qN,...KN,...XN};({...v_,...N_});function __(s=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(s):new Uint8Array(s)}function Kw(s,e,t,i){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:i}}}const bp=Kw("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),Al=Kw("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);const e=__(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),C_={utf8:bp,"utf-8":bp,hex:yp.base16,latin1:Al,ascii:Al,binary:Al,...yp};function S_(s,e="utf8"){const t=C_[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(s,"utf8"):t.decoder.decode(`${t.prefix}${s}`)}var $_=Object.defineProperty,P_=(s,e,t)=>e in s?$_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Hs=(s,e,t)=>P_(s,typeof e!="symbol"?e+"":e,t);let T_=class{constructor(e,t){this.core=e,this.logger=t,Hs(this,"keychain",new Map),Hs(this,"name",PA),Hs(this,"version",TA),Hs(this,"initialized",!1),Hs(this,"storagePrefix",si),Hs(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Hs(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Hs(this,"set",async(i,r)=>{this.isInitialized(),this.keychain.set(i,r),await this.persist()}),Hs(this,"get",i=>{this.isInitialized();const r=this.keychain.get(i);if(typeof r>"u"){const{message:n}=k("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return r}),Hs(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Ne(t,this.name)}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,sw(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?iw(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var M_=Object.defineProperty,O_=(s,e,t)=>e in s?M_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ct=(s,e,t)=>O_(s,typeof e!="symbol"?e+"":e,t);let x_=class{constructor(e,t,i){this.core=e,this.logger=t,Ct(this,"name",SA),Ct(this,"keychain"),Ct(this,"randomSessionIdentifier",Ch()),Ct(this,"initialized",!1),Ct(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ct(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ct(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=vc(r);return Tm(n.publicKey)}),Ct(this,"generateKeyPair",()=>{this.isInitialized();const r=CE();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ct(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=vc(n),a=this.randomSessionIdentifier;return await Mm(a,r,$A,o)}),Ct(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),l=SE(a,n);return this.setSymKey(l,o)}),Ct(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||nc(r);return await this.keychain.set(o,r),o}),Ct(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ct(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ct(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Pw(o),l=Sr(n);if(ep(a))return TE(l,o==null?void 0:o.encoding);if(Xd(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;r=await this.generateSharedKey(d,p)}const c=this.getSymKey(r),{type:h,senderPublicKey:u}=a;return $E({type:h,symKey:c,message:l,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Ct(this,"decode",async(r,n,o)=>{this.isInitialized();const a=OE(n,o);if(ep(a)){const l=ME(n,o==null?void 0:o.encoding);return wi(l)}if(Xd(a)){const l=a.receiverPublicKey,c=a.senderPublicKey;r=await this.generateSharedKey(l,c)}try{const l=this.getSymKey(r),c=PE({symKey:l,encoded:n,encoding:o==null?void 0:o.encoding});return wi(c)}catch(l){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(l)}}),Ct(this,"getPayloadType",(r,n=ji)=>{const o=Zo({encoded:r,encoding:n});return br(o.type)}),Ct(this,"getPayloadSenderPublicKey",(r,n=ji)=>{const o=Zo({encoded:r,encoding:n});return o.senderPublicKey?Ae(o.senderPublicKey,Bt):void 0}),this.core=e,this.logger=Ne(t,this.name),this.keychain=i||new T_(this.core,this.logger)}get context(){return qe(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(up)}catch{e=Ch(),await this.keychain.set(up,e)}return S_(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var D_=Object.defineProperty,k_=(s,e,t)=>e in s?D_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ws=(s,e,t)=>k_(s,typeof e!="symbol"?e+"":e,t);let j_=class extends N0{constructor(e,t){super(e,t),this.logger=e,this.core=t,Ws(this,"messages",new Map),Ws(this,"name",MA),Ws(this,"version",OA),Ws(this,"initialized",!1),Ws(this,"storagePrefix",si),Ws(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),Ws(this,"set",async(i,r)=>{this.isInitialized();const n=di(r);let o=this.messages.get(i);return typeof o>"u"&&(o={}),typeof o[n]<"u"||(o[n]=r,this.messages.set(i,o),await this.persist()),n}),Ws(this,"get",i=>{this.isInitialized();let r=this.messages.get(i);return typeof r>"u"&&(r={}),r}),Ws(this,"has",(i,r)=>{this.isInitialized();const n=this.get(i),o=di(r);return typeof n[o]<"u"}),Ws(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()}),this.logger=Ne(e,this.name),this.core=t}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,sw(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?iw(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var R_=Object.defineProperty,L_=Object.defineProperties,U_=Object.getOwnPropertyDescriptors,vp=Object.getOwnPropertySymbols,z_=Object.prototype.hasOwnProperty,F_=Object.prototype.propertyIsEnumerable,Mh=(s,e,t)=>e in s?R_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ja=(s,e)=>{for(var t in e||(e={}))z_.call(e,t)&&Mh(s,t,e[t]);if(vp)for(var t of vp(e))F_.call(e,t)&&Mh(s,t,e[t]);return s},Nl=(s,e)=>L_(s,U_(e)),Ds=(s,e,t)=>Mh(s,typeof e!="symbol"?e+"":e,t);let q_=class extends _0{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Ds(this,"events",new kt.EventEmitter),Ds(this,"name",xA),Ds(this,"queue",new Map),Ds(this,"publishTimeout",E.toMiliseconds(E.ONE_MINUTE)),Ds(this,"initialPublishTimeout",E.toMiliseconds(E.ONE_SECOND*15)),Ds(this,"needsTransportRestart",!1),Ds(this,"publish",async(i,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:r,opts:n}});const a=(n==null?void 0:n.ttl)||dp,l=_c(n),c=(n==null?void 0:n.prompt)||!1,h=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||gs().toString(),d={topic:i,message:r,opts:{ttl:a,relay:l,prompt:c,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},p=`Failed to publish payload, please try again. id:${u} tag:${h}`;try{const g=new Promise(async f=>{const y=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(It.publish,y),f(d))};this.relayer.events.on(It.publish,y);const w=ki(new Promise((m,b)=>{this.rpcPublish({topic:i,message:r,ttl:a,prompt:c,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(m).catch(I=>{this.logger.warn(I,I==null?void 0:I.message),b(I)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${h}`);try{await w,this.events.removeListener(It.publish,y)}catch(m){this.queue.set(u,Nl(ja({},d),{attempt:1})),this.logger.warn(m,m==null?void 0:m.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:i,message:r,opts:n}}),await ki(g,this.publishTimeout,p)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(u)}}),Ds(this,"on",(i,r)=>{this.events.on(i,r)}),Ds(this,"once",(i,r)=>{this.events.once(i,r)}),Ds(this,"off",(i,r)=>{this.events.off(i,r)}),Ds(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.relayer=e,this.logger=Ne(t,this.name),this.registerEventListeners()}get context(){return qe(this.logger)}async rpcPublish(e){var t,i,r,n;const{topic:o,message:a,ttl:l=dp,prompt:c,tag:h,id:u,attestation:d,tvf:p}=e,g={method:$o(_c().protocol).publish,params:ja({topic:o,message:a,ttl:l,prompt:c,tag:h,attestation:d},p),id:u};Kt((t=g.params)==null?void 0:t.prompt)&&((i=g.params)==null||delete i.prompt),Kt((r=g.params)==null?void 0:r.tag)&&((n=g.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const f=await this.relayer.request(g);return this.relayer.events.emit(It.publish,e),this.logger.debug("Successfully Published Payload"),f}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,Nl(ja({},e),{attempt:i}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Nl(ja({},e),{topic:r,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(qs.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(It.connection_stalled);return}this.checkQueue()}),this.relayer.on(It.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}};var B_=Object.defineProperty,H_=(s,e,t)=>e in s?B_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Fr=(s,e,t)=>H_(s,typeof e!="symbol"?e+"":e,t);let W_=class{constructor(){Fr(this,"map",new Map),Fr(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),Fr(this,"get",e=>this.map.get(e)||[]),Fr(this,"exists",(e,t)=>this.get(e).includes(t)),Fr(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const r=i.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),Fr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}};var V_=Object.defineProperty,K_=Object.defineProperties,G_=Object.getOwnPropertyDescriptors,Ip=Object.getOwnPropertySymbols,Y_=Object.prototype.hasOwnProperty,Q_=Object.prototype.propertyIsEnumerable,Oh=(s,e,t)=>e in s?V_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,uo=(s,e)=>{for(var t in e||(e={}))Y_.call(e,t)&&Oh(s,t,e[t]);if(Ip)for(var t of Ip(e))Q_.call(e,t)&&Oh(s,t,e[t]);return s},_l=(s,e)=>K_(s,G_(e)),Pe=(s,e,t)=>Oh(s,typeof e!="symbol"?e+"":e,t);let Z_=class extends $0{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Pe(this,"subscriptions",new Map),Pe(this,"topicMap",new W_),Pe(this,"events",new kt.EventEmitter),Pe(this,"name",zA),Pe(this,"version",FA),Pe(this,"pending",new Map),Pe(this,"cached",[]),Pe(this,"initialized",!1),Pe(this,"pendingSubscriptionWatchLabel","pending_sub_watch_label"),Pe(this,"pollingInterval",20),Pe(this,"storagePrefix",si),Pe(this,"subscribeTimeout",E.toMiliseconds(E.ONE_MINUTE)),Pe(this,"initialSubscribeTimeout",E.toMiliseconds(E.ONE_SECOND*15)),Pe(this,"clientId"),Pe(this,"batchSubscribeTopicsLimit",500),Pe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Pe(this,"subscribe",async(i,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}});try{const n=_c(r),o={topic:i,relay:n,transportType:r==null?void 0:r.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,r);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),Pe(this,"unsubscribe",async(i,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(i,r.id,r):await this.unsubscribeByTopic(i,r)}),Pe(this,"isSubscribed",async i=>{if(this.topics.includes(i))return!0;const r=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((n,o)=>{const a=new E.Watch;a.start(r);const l=setInterval(()=>{(!this.pending.has(i)&&this.topics.includes(i)||this.cached.some(c=>c.topic===i))&&(clearInterval(l),a.stop(r),n(!0)),a.elapsed(r)>=qA&&(clearInterval(l),a.stop(r),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)}),Pe(this,"on",(i,r)=>{this.events.on(i,r)}),Pe(this,"once",(i,r)=>{this.events.once(i,r)}),Pe(this,"off",(i,r)=>{this.events.off(i,r)}),Pe(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),Pe(this,"start",async()=>{await this.onConnect()}),Pe(this,"stop",async()=>{await this.onDisconnect()}),Pe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Pe(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(r=>{i.push(r)}),await this.batchSubscribe(i)}),Pe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(qs.pulse,async()=>{await this.checkPending()}),this.events.on(hs.created,async i=>{const r=hs.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()}),this.events.on(hs.deleted,async i=>{const r=hs.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()})}),this.relayer=e,this.logger=Ne(t,this.name),this.clientId=""}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const r=_c(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Te("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,i){var r;(!i||(i==null?void 0:i.transportType)===Ve.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:$o(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=i==null?void 0:i.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===Ve.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(h=>this.logger.warn(h))},E.toMiliseconds(E.ONE_SECOND)),a;const l=new Promise(async h=>{const u=d=>{d.topic===e&&(this.events.removeListener(hs.created,u),h(d.id))};this.events.on(hs.created,u);try{const d=await ki(new Promise((p,g)=>{this.relayer.request(n).catch(f=>{this.logger.warn(f,f==null?void 0:f.message),g(f)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(hs.created,u),h(d)}catch{}}),c=await ki(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!c&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return c?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(It.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:$o(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await ki(new Promise(r=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(It.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:$o(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let r;try{r=await await ki(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(It.connection_stalled)}return r}rpcUnsubscribe(e,t,i){const r={method:$o(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,_l(uo({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,uo({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,uo({},t)),this.topicMap.set(t.topic,e),this.events.emit(hs.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=k("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(hs.deleted,_l(uo({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(hs.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(hs.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=k("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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 t=>_l(uo({},t),{id:await this.getSubscriptionId(t.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await zI(E.toMiliseconds(E.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=k("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 di(e+await this.getClientId())}};var J_=Object.defineProperty,Ep=Object.getOwnPropertySymbols,X_=Object.prototype.hasOwnProperty,eC=Object.prototype.propertyIsEnumerable,xh=(s,e,t)=>e in s?J_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ap=(s,e)=>{for(var t in e||(e={}))X_.call(e,t)&&xh(s,t,e[t]);if(Ep)for(var t of Ep(e))eC.call(e,t)&&xh(s,t,e[t]);return s},pe=(s,e,t)=>xh(s,typeof e!="symbol"?e+"":e,t);let tC=class extends C0{constructor(e){super(e),pe(this,"protocol","wc"),pe(this,"version",2),pe(this,"core"),pe(this,"logger"),pe(this,"events",new kt.EventEmitter),pe(this,"provider"),pe(this,"messages"),pe(this,"subscriber"),pe(this,"publisher"),pe(this,"name",kA),pe(this,"transportExplicitlyClosed",!1),pe(this,"initialized",!1),pe(this,"connectionAttemptInProgress",!1),pe(this,"relayUrl"),pe(this,"projectId"),pe(this,"packageName"),pe(this,"bundleId"),pe(this,"hasExperiencedNetworkDisruption",!1),pe(this,"pingTimeout"),pe(this,"heartBeatTimeout",E.toMiliseconds(E.THIRTY_SECONDS+E.FIVE_SECONDS)),pe(this,"reconnectTimeout"),pe(this,"connectPromise"),pe(this,"reconnectInProgress",!1),pe(this,"requestsInFlight",[]),pe(this,"connectTimeout",E.toMiliseconds(E.ONE_SECOND*15)),pe(this,"request",async t=>{var i,r;this.logger.debug("Publishing Request Payload");const n=t.id||gs().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((r=t.params)==null?void 0:r.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),pe(this,"resetPingTimeout",()=>{if(Ac())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,r;this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(r=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null||r.terminate()},this.heartBeatTimeout)}catch(t){this.logger.warn(t,t==null?void 0:t.message)}}),pe(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),pe(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(It.connect)}),pe(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),pe(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(It.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),pe(this,"registerProviderListeners",()=>{this.provider.on(Is.payload,this.onPayloadHandler),this.provider.on(Is.connect,this.onConnectHandler),this.provider.on(Is.disconnect,this.onDisconnectHandler),this.provider.on(Is.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ne(e.logger,this.name):Vn(yi({level:e.logger||DA})),this.messages=new j_(this.logger,e.core),this.subscriber=new Z_(this,this.logger),this.publisher=new q_(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||jw,this.projectId=e.projectId,_I()?this.packageName=Cd():CI()&&(this.bundleId=Cd()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return qe(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Ve.relay})}async subscribe(e,t){var i,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=t==null?void 0:t.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(r=t==null?void 0:t.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",l;const c=h=>{h.topic===e&&(this.subscriber.off(hs.created,c),l())};return await Promise.all([new Promise(h=>{l=h,this.subscriber.on(hs.created,c)}),new Promise(async(h,u)=>{a=await this.subscriber.subscribe(e,Ap({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&u(d)})||a,h()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await ki(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(t,i)=>{await this.connect(e).then(t).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await cp())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,r)=>i.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+(r==null?void 0:r.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const r=ut(E.FIVE_MINUTES),n={topic:i,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(It.message,e),await this.recordMessageEvent(e)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Is.disconnect,n),await ki(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off(Is.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const l=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Is.disconnect,l),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Is.disconnect,l)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const r=i;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(i=>setTimeout(i,E.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,r,n;if(Ac())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(i=this.provider)==null?void 0:i.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ye(new Ow(TI({sdkVersion:$h,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){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.warn(`Ignoring message for non-subscribed topic ${t}`),!0;const r=this.messages.has(t,i);return r&&this.logger.warn(`Ignoring duplicate message: ${i}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Kn(e)){if(!e.method.endsWith(jA))return;const t=e.params,{topic:i,message:r,publishedAt:n,attestation:o}=t.data,a={topic:i,message:r,publishedAt:n,transportType:Ve.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Ap({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else $r(e)&&this.events.emit(It.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(It.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=Vi(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Is.payload,this.onPayloadHandler),this.provider.off(Is.connect,this.onConnectHandler),this.provider.off(Is.disconnect,this.onDisconnectHandler),this.provider.off(Is.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await cp();bA(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(It.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},E.toMiliseconds(RA)))))}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}};var sC=Object.defineProperty,Np=Object.getOwnPropertySymbols,iC=Object.prototype.hasOwnProperty,rC=Object.prototype.propertyIsEnumerable,Dh=(s,e,t)=>e in s?sC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,_p=(s,e)=>{for(var t in e||(e={}))iC.call(e,t)&&Dh(s,t,e[t]);if(Np)for(var t of Np(e))rC.call(e,t)&&Dh(s,t,e[t]);return s},Qt=(s,e,t)=>Dh(s,typeof e!="symbol"?e+"":e,t);let Tr=class extends S0{constructor(e,t,i,r=si,n=void 0){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,Qt(this,"map",new Map),Qt(this,"version",LA),Qt(this,"cached",[]),Qt(this,"initialized",!1),Qt(this,"getKey"),Qt(this,"storagePrefix",si),Qt(this,"recentlyDeleted",[]),Qt(this,"recentlyDeletedLimit",200),Qt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Kt(o)?this.map.set(this.getKey(o),o):QE(o)?this.map.set(o.id,o):ZE(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Qt(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())}),Qt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Qt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(l=>Av(a[l],o[l]))):this.values)),Qt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const l=_p(_p({},this.getData(o)),a);this.map.set(o,l),await this.persist()}),Qt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Ne(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=k("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:i}=k("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=k("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var nC=Object.defineProperty,oC=(s,e,t)=>e in s?nC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ae=(s,e,t)=>oC(s,typeof e!="symbol"?e+"":e,t);let aC=class{constructor(e,t){this.core=e,this.logger=t,ae(this,"name",BA),ae(this,"version",HA),ae(this,"events",new Wn),ae(this,"pairings"),ae(this,"initialized",!1),ae(this,"storagePrefix",si),ae(this,"ignoredPayloadTypes",[gi]),ae(this,"registeredMethods",[]),ae(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ae(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),ae(this,"create",async i=>{this.isInitialized();const r=Ch(),n=await this.core.crypto.setSymKey(r),o=ut(E.FIVE_MINUTES),a={protocol:kw},l={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},c=sp({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(cr.create,l),this.core.expirer.set(n,o),await this.pairings.set(n,l),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:c}}),ae(this,"pair",async i=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[Zs.pairing_started]}});this.isValidPair(i,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:l,methods:c}=tp(i.uri);r.props.properties.topic=n,r.addTrace(Zs.pairing_uri_validation_success),r.addTrace(Zs.pairing_uri_not_expired);let h;if(this.pairings.keys.includes(n)){if(h=this.pairings.get(n),r.addTrace(Zs.existing_pairing),h.active)throw r.setError(hi.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(Zs.pairing_not_expired)}const u=l||ut(E.FIVE_MINUTES),d={topic:n,relay:a,expiry:u,active:!1,methods:c};this.core.expirer.set(n,u),await this.pairings.set(n,d),r.addTrace(Zs.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(cr.create,d),r.addTrace(Zs.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(Zs.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(hi.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw r.setError(hi.subscribe_pairing_topic_failure),p}return r.addTrace(Zs.subscribe_pairing_topic_success),d}),ae(this,"activate",async({topic:i})=>{this.isInitialized();const r=ut(E.FIVE_MINUTES);this.core.expirer.set(i,r),await this.pairings.update(i,{active:!0,expiry:r})}),ae(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=i;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:l}=rr();this.events.once(Ie("pairing_ping",n),({error:c})=>{c?l(c):a()}),await o()}}),ae(this,"updateExpiry",async({topic:i,expiry:r})=>{this.isInitialized(),await this.pairings.update(i,{expiry:r})}),ae(this,"updateMetadata",async({topic:i,metadata:r})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:r})}),ae(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ae(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:r}=i;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Te("USER_DISCONNECTED")),await this.deletePairing(r))}),ae(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=i,l=this.core.crypto.keychain.get(r);return sp({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:l,relay:n,expiryTimestamp:o,methods:a})}),ae(this,"sendRequest",async(i,r,n)=>{const o=Gt(r,n),a=await this.core.crypto.encode(i,o),l=lo[r].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,l),o.id}),ae(this,"sendResult",async(i,r,n)=>{const o=Vi(i,n),a=await this.core.crypto.encode(r,o),l=(await this.core.history.get(r,i)).request.method,c=lo[l].res;await this.core.relayer.publish(r,a,c),await this.core.history.resolve(o)}),ae(this,"sendError",async(i,r,n)=>{const o=ca(i,n),a=await this.core.crypto.encode(r,o),l=(await this.core.history.get(r,i)).request.method,c=lo[l]?lo[l].res:lo.unregistered_method.res;await this.core.relayer.publish(r,a,c),await this.core.history.resolve(o)}),ae(this,"deletePairing",async(i,r)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Te("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),r?Promise.resolve():this.core.expirer.del(i)])}),ae(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(r=>Si(r.expiry));await Promise.all(i.map(r=>this.deletePairing(r.topic)))}),ae(this,"onRelayEventRequest",i=>{const{topic:r,payload:n}=i;switch(n.method){case"wc_pairingPing":return this.onPairingPingRequest(r,n);case"wc_pairingDelete":return this.onPairingDeleteRequest(r,n);default:return this.onUnknownRpcMethodRequest(r,n)}}),ae(this,"onRelayEventResponse",async i=>{const{topic:r,payload:n}=i,o=(await this.core.history.get(r,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,n);default:return this.onUnknownRpcMethodResponse(o)}}),ae(this,"onPairingPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(cr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),ae(this,"onPairingPingResponse",(i,r)=>{const{id:n}=r;setTimeout(()=>{vt(r)?this.events.emit(Ie("pairing_ping",n),{}):st(r)&&this.events.emit(Ie("pairing_ping",n),{error:r.error})},500)}),ae(this,"onPairingDeleteRequest",async(i,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(cr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),ae(this,"onUnknownRpcMethodRequest",async(i,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Te("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),ae(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(Te("WC_METHOD_UNSUPPORTED",i))}),ae(this,"isValidPair",(i,r)=>{var n;if(!is(i)){const{message:a}=k("MISSING_OR_INVALID",`pair() params: ${i}`);throw r.setError(hi.malformed_pairing_uri),new Error(a)}if(!YE(i.uri)){const{message:a}=k("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw r.setError(hi.malformed_pairing_uri),new Error(a)}const o=tp(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=k("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(hi.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=k("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(hi.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&E.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(hi.pairing_expired);const{message:a}=k("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ae(this,"isValidPing",async i=>{if(!is(i)){const{message:n}=k("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),ae(this,"isValidDisconnect",async i=>{if(!is(i)){const{message:n}=k("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),ae(this,"isValidPairingTopic",async i=>{if(!it(i,!1)){const{message:r}=k("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(r)}if(!this.pairings.keys.includes(i)){const{message:r}=k("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(r)}if(Si(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:r}=k("EXPIRED",`pairing topic: ${i}`);throw new Error(r)}}),this.core=e,this.logger=Ne(t,this.name),this.pairings=new Tr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return qe(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(It.message,async e=>{const{topic:t,message:i,transportType:r}=e;if(!this.pairings.keys.includes(t)||r===Ve.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const n=await this.core.crypto.decode(t,i);try{Kn(n)?(this.core.history.set(t,n),this.onRelayEventRequest({topic:t,payload:n})):$r(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(Cs.expired,async e=>{const{topic:t}=nw(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(cr.expire,{topic:t}))})}};var cC=Object.defineProperty,lC=(s,e,t)=>e in s?cC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,St=(s,e,t)=>lC(s,typeof e!="symbol"?e+"":e,t);let hC=class extends A0{constructor(e,t){super(e,t),this.core=e,this.logger=t,St(this,"records",new Map),St(this,"events",new kt.EventEmitter),St(this,"name",WA),St(this,"version",VA),St(this,"cached",[]),St(this,"initialized",!1),St(this,"storagePrefix",si),St(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),St(this,"set",(i,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:i,request:{method:r.method,params:r.params||null},chainId:n,expiry:ut(E.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Os.created,o)}),St(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const r=await this.getRecord(i.id);typeof r.response>"u"&&(r.response=st(i)?{error:i.error}:{result:i.result},this.records.set(r.id,r),this.persist(),this.events.emit(Os.updated,r))}),St(this,"get",async(i,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:r}),await this.getRecord(r))),St(this,"delete",(i,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===i){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(Os.deleted,n)}}),this.persist()}),St(this,"exists",async(i,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===i:!1)),St(this,"on",(i,r)=>{this.events.on(i,r)}),St(this,"once",(i,r)=>{this.events.once(i,r)}),St(this,"off",(i,r)=>{this.events.off(i,r)}),St(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=Ne(t,this.name)}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:Gt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=k("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Os.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=k("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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(Os.created,e=>{const t=Os.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Os.updated,e=>{const t=Os.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Os.deleted,e=>{const t=Os.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(qs.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{E.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Os.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var uC=Object.defineProperty,dC=(s,e,t)=>e in s?uC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ut=(s,e,t)=>dC(s,typeof e!="symbol"?e+"":e,t);let pC=class extends P0{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ut(this,"expirations",new Map),Ut(this,"events",new kt.EventEmitter),Ut(this,"name",KA),Ut(this,"version",GA),Ut(this,"cached",[]),Ut(this,"initialized",!1),Ut(this,"storagePrefix",si),Ut(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ut(this,"has",i=>{try{const r=this.formatTarget(i);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ut(this,"set",(i,r)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(Cs.created,{target:n,expiration:o})}),Ut(this,"get",i=>{this.isInitialized();const r=this.formatTarget(i);return this.getExpiration(r)}),Ut(this,"del",i=>{if(this.isInitialized(),this.has(i)){const r=this.formatTarget(i),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Cs.deleted,{target:r,expiration:n})}}),Ut(this,"on",(i,r)=>{this.events.on(i,r)}),Ut(this,"once",(i,r)=>{this.events.once(i,r)}),Ut(this,"off",(i,r)=>{this.events.off(i,r)}),Ut(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=Ne(t,this.name)}get context(){return qe(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 MI(e);if(typeof e=="number")return OI(e);const{message:t}=k("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Cs.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=k("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:i}=k("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;E.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Cs.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(qs.pulse,()=>this.checkExpirations()),this.events.on(Cs.created,e=>{const t=Cs.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Cs.expired,e=>{const t=Cs.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Cs.deleted,e=>{const t=Cs.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var gC=Object.defineProperty,fC=(s,e,t)=>e in s?gC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,rt=(s,e,t)=>fC(s,typeof e!="symbol"?e+"":e,t);let mC=class extends T0{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,rt(this,"name",YA),rt(this,"abortController"),rt(this,"isDevEnv"),rt(this,"verifyUrlV3",ZA),rt(this,"storagePrefix",si),rt(this,"version",Dw),rt(this,"publicKey"),rt(this,"fetchPromise"),rt(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&E.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),rt(this,"register",async r=>{if(!pa()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=r,l=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const c=Wi(),h=this.startAbortTimer(E.ONE_SECOND*5),u=await new Promise((d,p)=>{const g=()=>{window.removeEventListener("message",y),c.body.removeChild(f),p("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const f=c.createElement("iframe");f.src=l,f.style.display="none",f.addEventListener("error",g,{signal:this.abortController.signal});const y=w=>{if(w.data&&typeof w.data=="string")try{const m=JSON.parse(w.data);if(m.type==="verify_attestation"){if(jn(m.attestation).payload.id!==o)return;clearInterval(h),c.body.removeChild(f),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",y),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};c.body.appendChild(f),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(c){this.logger.warn(c)}return""}),rt(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(jn(n).payload.id!==a)return;const c=await this.isValidJwtAttestation(n);if(c){if(!c.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return c}}if(!o)return;const l=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,l)}),rt(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(E.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),rt(this,"getVerifyUrl",r=>{let n=r||Ro;return JA.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Ro}`),n=Ro),n}),rt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(E.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),rt(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),rt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),rt(this,"isValidJwtAttestation",async r=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(r,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),rt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),rt(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 r=await this.fetchPromise;return this.fetchPromise=void 0,r}),rt(this,"validateAttestation",(r,n)=>{const o=jE(r,n.publicKey),a={hasExpired:E.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ne(t,this.name),this.abortController=new AbortController,this.isDevEnv=_u(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return qe(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),E.toMiliseconds(e))}};var wC=Object.defineProperty,yC=(s,e,t)=>e in s?wC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Cp=(s,e,t)=>yC(s,typeof e!="symbol"?e+"":e,t);let bC=class extends M0{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Cp(this,"context",XA),Cp(this,"registerDeviceToken",async i=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=i,l=`${eN}/${this.projectId}/clients`;await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=Ne(t,this.context)}};var vC=Object.defineProperty,Sp=Object.getOwnPropertySymbols,IC=Object.prototype.hasOwnProperty,EC=Object.prototype.propertyIsEnumerable,kh=(s,e,t)=>e in s?vC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,po=(s,e)=>{for(var t in e||(e={}))IC.call(e,t)&&kh(s,t,e[t]);if(Sp)for(var t of Sp(e))EC.call(e,t)&&kh(s,t,e[t]);return s},gt=(s,e,t)=>kh(s,typeof e!="symbol"?e+"":e,t);let AC=class extends O0{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,gt(this,"context",sN),gt(this,"storagePrefix",si),gt(this,"storageVersion",tN),gt(this,"events",new Map),gt(this,"shouldPersist",!1),gt(this,"init",async()=>{if(!_u())try{const r={eventId:$d(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:tw(this.core.relayer.protocol,this.core.relayer.version,$h)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),gt(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:l}}=r,c=$d(),h=this.core.projectId||"",u=Date.now(),d=po({eventId:c,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:l}},bundleId:h,domain:this.getAppDomain()},this.setMethods(c));return this.telemetryEnabled&&(this.events.set(c,d),this.shouldPersist=!0),d}),gt(this,"getEvent",r=>{const{eventId:n,topic:o}=r;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(l=>l.props.properties.topic===o);if(a)return po(po({},a),this.setMethods(a.eventId))}),gt(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),gt(this,"setEventListeners",()=>{this.core.heartbeat.on(qs.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{E.fromMiliseconds(Date.now())-E.fromMiliseconds(r.timestamp)>iN&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),gt(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),gt(this,"addTrace",(r,n)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(n),this.events.set(r,o),this.shouldPersist=!0)}),gt(this,"setError",(r,n)=>{const o=this.events.get(r);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),gt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),gt(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(n=>{this.events.set(n.eventId,po(po({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),gt(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[n,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const n of r)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),gt(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${rN}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${$h}${n}`,{method:"POST",body:JSON.stringify(r)})}),gt(this,"getAppDomain",()=>ew().url),this.logger=Ne(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}};var NC=Object.defineProperty,$p=Object.getOwnPropertySymbols,_C=Object.prototype.hasOwnProperty,CC=Object.prototype.propertyIsEnumerable,jh=(s,e,t)=>e in s?NC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Pp=(s,e)=>{for(var t in e||(e={}))_C.call(e,t)&&jh(s,t,e[t]);if($p)for(var t of $p(e))CC.call(e,t)&&jh(s,t,e[t]);return s},ke=(s,e,t)=>jh(s,typeof e!="symbol"?e+"":e,t);let SC=class Gw extends b0{constructor(e){var t;super(e),ke(this,"protocol",xw),ke(this,"version",Dw),ke(this,"name",Sh),ke(this,"relayUrl"),ke(this,"projectId"),ke(this,"customStoragePrefix"),ke(this,"events",new kt.EventEmitter),ke(this,"logger"),ke(this,"heartbeat"),ke(this,"relayer"),ke(this,"crypto"),ke(this,"storage"),ke(this,"history"),ke(this,"expirer"),ke(this,"pairing"),ke(this,"verify"),ke(this,"echoClient"),ke(this,"linkModeSupportedApps"),ke(this,"eventClient"),ke(this,"initialized",!1),ke(this,"logChunkController"),ke(this,"on",(o,a)=>this.events.on(o,a)),ke(this,"once",(o,a)=>this.events.once(o,a)),ke(this,"off",(o,a)=>this.events.off(o,a)),ke(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),ke(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:l})=>{if(!o||!a)return;const c={topic:o,message:a,publishedAt:Date.now(),transportType:Ve.link_mode};this.relayer.onLinkMessageEvent(c,{sessionExists:l})}),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||jw,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=yi({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:_A.logger,name:Sh}),{logger:r,chunkLoggerController:n}=Au({opts:i,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=n,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,a;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((a=this.logChunkController)==null||a.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ne(r,this.name),this.heartbeat=new jm,this.crypto=new x_(this,this.logger,e==null?void 0:e.keychain),this.history=new hC(this,this.logger),this.expirer=new pC(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new m0(Pp(Pp({},CA),e==null?void 0:e.storageOptions)),this.relayer=new tC({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new aC(this,this.logger),this.verify=new mC(this,this.logger,this.storage),this.echoClient=new bC(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new AC(this,this.logger,e==null?void 0:e.telemetryEnabled)}static async init(e){const t=new Gw(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(UA,i),t}get context(){return qe(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(pp,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(pp)||[],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}}};const $C=SC;var PC=Object.defineProperty,TC=(s,e,t)=>e in s?PC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Tp=(s,e,t)=>TC(s,typeof e!="symbol"?e+"":e,t);let MC=class{constructor(e){this.opts=e,Tp(this,"protocol","wc"),Tp(this,"version",2)}},OC=class{constructor(e){this.client=e}};const Yw="wc",Qw=2,Zw="client",Du=`${Yw}@${Qw}:${Zw}:`,Cl={name:Zw,logger:"error"},Mp="WALLETCONNECT_DEEPLINK_CHOICE",xC="proposal",Op="Proposal expired",DC="session",qr=E.SEVEN_DAYS,kC="engine",ft={wc_sessionPropose:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1104},res:{ttl:E.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1106},res:{ttl:E.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1112},res:{ttl:E.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1114},res:{ttl:E.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:E.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:E.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1119}}},Sl={min:E.FIVE_MINUTES,max:E.SEVEN_DAYS},Vs={idle:"IDLE",active:"ACTIVE"},xp={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},jC="request",RC=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],LC="wc",UC="auth",zC="authKeys",FC="pairingTopics",qC="requests",Kc=`${LC}@${1.5}:${UC}:`,oc=`${Kc}:PUB_KEY`;var BC=Object.defineProperty,HC=Object.defineProperties,WC=Object.getOwnPropertyDescriptors,Dp=Object.getOwnPropertySymbols,VC=Object.prototype.hasOwnProperty,KC=Object.prototype.propertyIsEnumerable,Rh=(s,e,t)=>e in s?BC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ze=(s,e)=>{for(var t in e||(e={}))VC.call(e,t)&&Rh(s,t,e[t]);if(Dp)for(var t of Dp(e))KC.call(e,t)&&Rh(s,t,e[t]);return s},Zt=(s,e)=>HC(s,WC(e)),x=(s,e,t)=>Rh(s,typeof e!="symbol"?e+"":e,t);let GC=class extends OC{constructor(e){super(e),x(this,"name",kC),x(this,"events",new Wn),x(this,"initialized",!1),x(this,"requestQueue",{state:Vs.idle,queue:[]}),x(this,"sessionRequestQueue",{state:Vs.idle,queue:[]}),x(this,"requestQueueDelay",E.ONE_SECOND),x(this,"expectedPairingMethodMap",new Map),x(this,"recentlyDeletedMap",new Map),x(this,"recentlyDeletedLimit",200),x(this,"relayMessageCache",[]),x(this,"pendingSessions",new Map),x(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(ft)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},E.toMiliseconds(this.requestQueueDelay)))}),x(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Zt(Ze({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,relays:l}=i;let c=r,h,u=!1;try{if(c){const N=this.client.core.pairing.pairings.get(c);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),u=N.active}}catch(N){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),N}if(!c||!u){const{topic:N,uri:$}=await this.client.core.pairing.create();c=N,h=$}if(!c){const{message:N}=k("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(N)}const d=await this.client.core.crypto.generateKeyPair(),p=ft.wc_sessionPropose.req.ttl||E.FIVE_MINUTES,g=ut(p),f=Zt(Ze({requiredNamespaces:n,optionalNamespaces:o,relays:l??[{protocol:kw}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:c},a&&{sessionProperties:a}),{id:qt()}),y=Ie("session_connect",f.id),{reject:w,resolve:m,done:b}=rr(p,Op),I=({id:N})=>{N===f.id&&(this.client.events.off("proposal_expire",I),this.pendingSessions.delete(f.id),this.events.emit(y,{error:{message:Op,code:0}}))};return this.client.events.on("proposal_expire",I),this.events.once(y,({error:N,session:$})=>{this.client.events.off("proposal_expire",I),N?w(N):$&&m($)}),await this.sendRequest({topic:c,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:h,approval:b}}),x(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}}),x(this,"approve",async t=>{var i,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=t==null?void 0:t.id)==null?void 0:i.toString(),trace:[xs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(O){throw o.setError(Xi.no_internet_connection),O}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(O){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(Xi.proposal_not_found),O}try{await this.isValidApprove(t)}catch(O){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Xi.session_approve_namespace_validation_failure),O}const{id:a,relayProtocol:l,namespaces:c,sessionProperties:h,sessionConfig:u}=t,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:f,optionalNamespaces:y}=d;let w=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:p});w||(w=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:xs.session_approve_started,properties:{topic:p,trace:[xs.session_approve_started,xs.session_namespaces_validation_success]}}));const m=await this.client.core.crypto.generateKeyPair(),b=g.publicKey,I=await this.client.core.crypto.generateSharedKey(m,b),N=Ze(Ze({relay:{protocol:l??"irn"},namespaces:c,controller:{publicKey:m,metadata:this.client.metadata},expiry:ut(qr)},h&&{sessionProperties:h}),u&&{sessionConfig:u}),$=Ve.relay;w.addTrace(xs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(I,{transportType:$})}catch(O){throw w.setError(Xi.subscribe_session_topic_failure),O}w.addTrace(xs.subscribe_session_topic_success);const P=Zt(Ze({},N),{topic:I,requiredNamespaces:f,optionalNamespaces:y,pairingTopic:p,acknowledged:!1,self:N.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:m,transportType:Ve.relay});await this.client.session.set(I,P),w.addTrace(xs.store_session);try{w.addTrace(xs.publishing_session_settle),await this.sendRequest({topic:I,method:"wc_sessionSettle",params:N,throwOnFailedPublish:!0}).catch(O=>{throw w==null||w.setError(Xi.session_settle_publish_failure),O}),w.addTrace(xs.session_settle_publish_success),w.addTrace(xs.publishing_session_approve),await this.sendResult({id:a,topic:p,result:{relay:{protocol:l??"irn"},responderPublicKey:m},throwOnFailedPublish:!0}).catch(O=>{throw w==null||w.setError(Xi.session_approve_publish_failure),O}),w.addTrace(xs.session_approve_publish_success)}catch(O){throw this.client.logger.error(O),this.client.session.delete(I,Te("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(I),O}return this.client.core.eventClient.deleteEvent({eventId:w.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:g.metadata}),await this.client.proposal.delete(a,Te("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(I,ut(qr)),{topic:I,acknowledged:()=>Promise.resolve(this.client.session.get(I))}}),x(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:r}=t;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&(await this.sendError({id:i,topic:n,error:r,rpcOpts:ft.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Te("USER_DISCONNECTED")))}),x(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:i,namespaces:r}=t,{done:n,resolve:o,reject:a}=rr(),l=qt(),c=gs().toString(),h=this.client.session.get(i).namespaces;return this.events.once(Ie("session_update",l),({error:u})=>{u?a(u):o()}),await this.client.session.update(i,{namespaces:r}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:l,relayRpcId:c}).catch(u=>{this.client.logger.error(u),this.client.session.update(i,{namespaces:h}),a(u)}),{acknowledged:n}}),x(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(l){throw this.client.logger.error("extend() -> isValidExtend() failed"),l}const{topic:i}=t,r=qt(),{done:n,resolve:o,reject:a}=rr();return this.events.once(Ie("session_extend",r),({error:l})=>{l?a(l):o()}),await this.setExpiry(i,ut(qr)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(l=>{a(l)}),{acknowledged:n}}),x(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:i,request:r,topic:n,expiry:o=ft.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===Ve.relay&&await this.confirmOnlineStateOrThrow();const l=qt(),c=gs().toString(),{done:h,resolve:u,reject:d}=rr(o,"Request expired. Please try again.");this.events.once(Ie("session_request",l),({error:w,result:m})=>{w?d(w):u(m)});const p="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:l,relayRpcId:c,topic:n,method:p,params:{request:Zt(Ze({},r),{expiryTimestamp:ut(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:l}),await h();const f={request:Zt(Ze({},r),{expiryTimestamp:ut(o)}),chainId:i},y=this.shouldSetTVF(p,f);return await Promise.all([new Promise(async w=>{await this.sendRequest(Ze({clientRpcId:l,relayRpcId:c,topic:n,method:p,params:f,expiry:o,throwOnFailedPublish:!0},y&&{tvf:this.getTVFParams(l,f)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:l}),w()}),new Promise(async w=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const b=await jI(this.client.core.storage,Mp);await xI({id:l,topic:n,wcDeepLink:b})}w()}),h()]).then(w=>w[2])}),x(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:r}=t,{id:n}=r,o=this.client.session.get(i);o.transportType===Ve.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);vt(r)?await this.sendResult({id:n,topic:i,result:r.result,throwOnFailedPublish:!0,appLink:a}):st(r)&&await this.sendError({id:n,topic:i,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),x(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:i}=t;if(this.client.session.keys.includes(i)){const r=qt(),n=gs().toString(),{done:o,resolve:a,reject:l}=rr();this.events.once(Ie("session_ping",r),({error:c})=>{c?l(c):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),x(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:r,chainId:n}=t,o=gs().toString(),a=qt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),x(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Te("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:r}=k("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(r)}}),x(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(i=>KE(i,t)))),x(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),x(this,"authenticate",async(t,i)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?Ve.link_mode:Ve.relay;o===Ve.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:l="",uri:c,domain:h,nonce:u,type:d,exp:p,nbf:g,methods:f=[],expiry:y}=t,w=[...t.resources||[]],{topic:m,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:b}});const I=await this.client.core.crypto.generateKeyPair(),N=nc(I);if(await Promise.all([this.client.auth.authKeys.set(oc,{responseTopic:N,publicKey:I}),this.client.auth.pairingTopics.set(N,{topic:N,pairingTopic:m})]),await this.client.core.relayer.subscribe(N,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),f.length>0){const{namespace:A}=On(a[0]);let z=C1(A,"request",f);rc(w)&&(z=$1(z,w.pop())),w.push(z)}const $=y&&y>ft.wc_sessionAuthenticate.req.ttl?y:ft.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:d??"caip122",chains:a,statement:l,aud:c,domain:h,version:"1",nonce:u,iat:new Date().toISOString(),exp:p,nbf:g,resources:w},requester:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:ut($)},O={eip155:{chains:a,methods:[...new Set(["personal_sign",...f])],events:["chainChanged","accountsChanged"]}},C={requiredNamespaces:{},optionalNamespaces:O,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:ut(ft.wc_sessionPropose.req.ttl),id:qt()},{done:T,resolve:S,reject:R}=rr($,"Request expired"),L=qt(),q=Ie("session_connect",C.id),B=Ie("session_request",L),U=async({error:A,session:z})=>{this.events.off(B,H),A?R(A):z&&S({session:z})},H=async A=>{var z,Y,K;if(await this.deletePendingAuthRequest(L,{message:"fulfilled",code:0}),A.error){const He=Te("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return A.error.code===He.code?void 0:(this.events.off(q,U),R(A.error.message))}await this.deleteProposal(C.id),this.events.off(q,U);const{cacaos:be,responder:oe}=A.result,Oe=[],lt=[];for(const He of be){await jd({cacao:He,projectId:this.client.core.projectId})||(this.client.logger.error(He,"Signature verification failed"),R(Te("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Qi}=He,Zi=rc(Qi.resources),so=[vh(Qi.iss)],cl=Nc(Qi.iss);if(Zi){const Ji=Rd(Zi),ll=Ld(Zi);Oe.push(...Ji),so.push(...ll)}for(const Ji of so)lt.push(`${Ji}:${cl}`)}const Be=await this.client.core.crypto.generateSharedKey(I,oe.publicKey);let Qe;Oe.length>0&&(Qe={topic:Be,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:oe,controller:oe.publicKey,expiry:ut(qr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:ip([...new Set(Oe)],[...new Set(lt)]),transportType:o},await this.client.core.relayer.subscribe(Be,{transportType:o}),await this.client.session.set(Be,Qe),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:oe.metadata}),Qe=this.client.session.get(Be)),(z=this.client.metadata.redirect)!=null&&z.linkMode&&(Y=oe.metadata.redirect)!=null&&Y.linkMode&&(K=oe.metadata.redirect)!=null&&K.universal&&i&&(this.client.core.addLinkModeSupportedApp(oe.metadata.redirect.universal),this.client.session.update(Be,{transportType:Ve.link_mode})),S({auths:be,session:Qe})};this.events.once(q,U),this.events.once(B,H);let W;try{if(n){const A=Gt("wc_sessionAuthenticate",P,L);this.client.core.history.set(m,A);const z=await this.client.core.crypto.encode("",A,{type:wa,encoding:ao});W=ka(i,m,z)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:P,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:L}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:C,expiry:ft.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:C.id})])}catch(A){throw this.events.off(q,U),this.events.off(B,H),A}return await this.setProposal(C.id,C),await this.setAuthRequest(L,{request:Zt(Ze({},P),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:W??b,response:T}}),x(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[er.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw n.setError(ho.no_internet_connection),y}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(ho.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Ve.relay;a===Ve.relay&&await this.confirmOnlineStateOrThrow();const l=o.requester.publicKey,c=await this.client.core.crypto.generateKeyPair(),h=nc(l),u={type:gi,receiverPublicKey:l,senderPublicKey:c},d=[],p=[];for(const y of r){if(!await jd({cacao:y,projectId:this.client.core.projectId})){n.setError(ho.invalid_cacao);const N=Te("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:h,error:N,encodeOpts:u}),new Error(N.message)}n.addTrace(er.cacaos_verified);const{p:w}=y,m=rc(w.resources),b=[vh(w.iss)],I=Nc(w.iss);if(m){const N=Rd(m),$=Ld(m);d.push(...N),b.push(...$)}for(const N of b)p.push(`${N}:${I}`)}const g=await this.client.core.crypto.generateSharedKey(c,l);n.addTrace(er.create_authenticated_session_topic);let f;if((d==null?void 0:d.length)>0){f={topic:g,acknowledged:!0,self:{publicKey:c,metadata:this.client.metadata},peer:{publicKey:l,metadata:o.requester.metadata},controller:l,expiry:ut(qr),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:ip([...new Set(d)],[...new Set(p)]),transportType:a},n.addTrace(er.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(y){throw n.setError(ho.subscribe_authenticated_session_topic_failure),y}n.addTrace(er.subscribe_authenticated_session_topic_success),await this.client.session.set(g,f),n.addTrace(er.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(er.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:i,result:{cacaos:r,responder:{publicKey:c,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw n.setError(ho.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:f}}),x(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:i,reason:r}=t,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===Ve.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),l=nc(o),c={type:gi,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:l,error:r,encodeOpts:c,rpcOpts:ft.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Te("USER_DISCONNECTED"))}),x(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:r}=t;return gw(i,r)}),x(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),x(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),r=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)===t.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),x(this,"deleteSession",async t=>{var i;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:l}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Te("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(l.publicKey)&&await this.client.core.crypto.deleteKeyPair(l.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Mp).catch(c=>this.client.logger.warn(c)),this.getPendingSessionRequests().forEach(c=>{c.topic===r&&this.deletePendingSessionRequest(c.id,Te("USER_DISCONNECTED"))}),r===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Vs.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),x(this,"deleteProposal",async(t,i)=>{if(i)try{const r=this.client.proposal.get(t),n=this.client.core.eventClient.getEvent({topic:r.pairingTopic});n==null||n.setError(Xi.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Te("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),x(this,"deletePendingSessionRequest",async(t,i,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==t),r&&(this.sessionRequestQueue.state=Vs.idle,this.client.events.emit("session_request_expire",{id:t}))}),x(this,"deletePendingAuthRequest",async(t,i,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)])}),x(this,"setExpiry",async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))}),x(this,"setProposal",async(t,i)=>{this.client.core.expirer.set(t,ut(ft.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),x(this,"setAuthRequest",async(t,i)=>{const{request:r,pairingTopic:n,transportType:o=Ve.relay}=i;this.client.core.expirer.set(t,r.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:t,pairingTopic:n,verifyContext:r.verifyContext,transportType:o})}),x(this,"setPendingSessionRequest",async t=>{const{id:i,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ut(ft.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:r,params:n,verifyContext:o})}),x(this,"sendRequest",async t=>{const{topic:i,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:l,throwOnFailedPublish:c,appLink:h,tvf:u}=t,d=Gt(r,n,l);let p;const g=!!h;try{const w=g?ao:ji;p=await this.client.core.crypto.encode(i,d,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),w}let f;if(RC.includes(r)){const w=di(JSON.stringify(d)),m=di(p);f=await this.client.core.verify.register({id:m,decryptedId:w})}const y=ft[r].req;if(y.attestation=f,o&&(y.ttl=o),a&&(y.id=a),this.client.core.history.set(i,d),g){const w=ka(h,i,p);await _.global.Linking.openURL(w,this.client.name)}else{const w=ft[r].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=Zt(Ze({},u),{correlationId:d.id}),c?(w.internal=Zt(Ze({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,w)):this.client.core.relayer.publish(i,p,w).catch(m=>this.client.logger.error(m))}return d.id}),x(this,"sendResult",async t=>{const{id:i,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:l}=t,c=Vi(i,n);let h;const u=l&&typeof(_.global==null?void 0:_.global.Linking)<"u";try{const g=u?ao:ji;h=await this.client.core.crypto.encode(r,c,Zt(Ze({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let d,p;try{d=await this.client.core.history.get(r,i);const g=d.request;try{this.shouldSetTVF(g.method,g.params)&&(p=this.getTVFParams(i,g.params,n))}catch(f){this.client.logger.warn("sendResult() -> getTVFParams() failed",f)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${i}) failed`),g}if(u){const g=ka(l,r,h);await _.global.Linking.openURL(g,this.client.name)}else{const g=d.request.method,f=ft[g].res;f.tvf=Zt(Ze({},p),{correlationId:i}),o?(f.internal=Zt(Ze({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,h,f)):this.client.core.relayer.publish(r,h,f).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(c)}),x(this,"sendError",async t=>{const{id:i,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:l}=t,c=ca(i,n);let h;const u=l&&typeof(_.global==null?void 0:_.global.Linking)<"u";try{const p=u?ao:ji;h=await this.client.core.crypto.encode(r,c,Zt(Ze({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),p}let d;try{d=await this.client.core.history.get(r,i)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${r}, ${i}) failed`),p}if(u){const p=ka(l,r,h);await _.global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,g=a||ft[p].res;this.client.core.relayer.publish(r,h,g)}await this.client.core.history.resolve(c)}),x(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(r=>{let n=!1;Si(r.expiry)&&(n=!0),this.client.core.crypto.keychain.has(r.topic)||(n=!0),n&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{Si(r.expiryTimestamp)&&i.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...i.map(r=>this.deleteProposal(r))])}),x(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),x(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Vs.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=Vs.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Vs.idle}),x(this,"processRequest",async t=>{const{topic:i,payload:r,attestation:n,transportType:o,encryptedId:a}=t,l=r.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:l}))switch(l){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,r);case"wc_sessionPing":return await this.onSessionPingRequest(i,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${l}`)}}),x(this,"onRelayEventResponse",async t=>{const{topic:i,payload:r,transportType:n}=t,o=(await this.client.core.history.get(i,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,r);case"wc_sessionExtend":return this.onSessionExtendResponse(i,r);case"wc_sessionPing":return this.onSessionPingResponse(i,r);case"wc_sessionRequest":return this.onSessionRequestResponse(i,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),x(this,"onRelayEventUnknownPayload",t=>{const{topic:i}=t,{message:r}=k("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),x(this,"shouldIgnorePairingRequest",t=>{const{topic:i,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),x(this,"onSessionProposeRequest",async t=>{const{topic:i,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:l}=r;try{const c=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),c==null||c.setError(hi.proposal_listener_not_found)),this.isValidConnect(Ze({},r.params));const h=a.expiryTimestamp||ut(ft.wc_sessionPropose.req.ttl),u=Ze({id:l,pairingTopic:i,expiryTimestamp:h},a);await this.setProposal(l,u);const d=await this.getVerifyContext({attestationId:n,hash:di(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});c==null||c.addTrace(Zs.emit_session_proposal),this.client.events.emit("session_proposal",{id:l,params:u,verifyContext:d})}catch(c){await this.sendError({id:l,topic:i,error:c,rpcOpts:ft.wc_sessionPropose.autoReject}),this.client.logger.error(c)}}),x(this,"onSessionProposeResponse",async(t,i,r)=>{const{id:n}=i;if(vt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const l=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const c=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:c});const h=await this.client.core.crypto.generateSharedKey(l,c);this.pendingSessions.set(n,{sessionTopic:h,pairingTopic:t,proposalId:n,publicKey:l});const u=await this.client.core.relayer.subscribe(h,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(st(i)){await this.client.proposal.delete(n,Te("USER_DISCONNECTED"));const o=Ie("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),x(this,"onSessionSettleRequest",async(t,i)=>{const{id:r,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:l,namespaces:c,sessionProperties:h,sessionConfig:u}=i.params,d=[...this.pendingSessions.values()].find(f=>f.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const p=this.client.proposal.get(d.proposalId),g=Zt(Ze(Ze({topic:t,relay:o,expiry:l,namespaces:c,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},h&&{sessionProperties:h}),u&&{sessionConfig:u}),{transportType:Ve.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(Ie("session_connect",d.proposalId),{session:g}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),x(this,"onSessionSettleResponse",async(t,i)=>{const{id:r}=i;vt(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Ie("session_approve",r),{})):st(i)&&(await this.client.session.delete(t,Te("USER_DISCONNECTED")),this.events.emit(Ie("session_approve",r),{error:i.error}))}),x(this,"onSessionUpdateRequest",async(t,i)=>{const{params:r,id:n}=i;try{const o=`${t}_session_update`,a=co.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:t,error:Te("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ze({topic:t},r));try{co.set(o,n),await this.client.session.update(t,{namespaces:r.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(l){throw co.delete(o),l}this.client.events.emit("session_update",{id:n,topic:t,params:r})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}}),x(this,"isRequestOutOfSync",(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3)),x(this,"onSessionUpdateResponse",(t,i)=>{const{id:r}=i,n=Ie("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ie("session_update",r),{}):st(i)&&this.events.emit(Ie("session_update",r),{error:i.error})}),x(this,"onSessionExtendRequest",async(t,i)=>{const{id:r}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ut(qr)),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),x(this,"onSessionExtendResponse",(t,i)=>{const{id:r}=i,n=Ie("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ie("session_extend",r),{}):st(i)&&this.events.emit(Ie("session_extend",r),{error:i.error})}),x(this,"onSessionPingRequest",async(t,i)=>{const{id:r}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),x(this,"onSessionPingResponse",(t,i)=>{const{id:r}=i,n=Ie("session_ping",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);setTimeout(()=>{vt(i)?this.events.emit(Ie("session_ping",r),{}):st(i)&&this.events.emit(Ie("session_ping",r),{error:i.error})},500)}),x(this,"onSessionDeleteRequest",async(t,i)=>{const{id:r}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(It.publish,async()=>{n(await this.deleteSession({topic:t,id:r}))})}),this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Te("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),x(this,"onSessionRequest",async t=>{var i,r,n;const{topic:o,payload:a,attestation:l,encryptedId:c,transportType:h}=t,{id:u,params:d}=a;try{await this.isValidRequest(Ze({topic:o},d));const p=this.client.session.get(o),g=await this.getVerifyContext({attestationId:l,hash:di(JSON.stringify(Gt("wc_sessionRequest",d,u))),encryptedId:c,metadata:p.peer.metadata,transportType:h}),f={id:u,topic:o,params:d,verifyContext:g};await this.setPendingSessionRequest(f),h===Ve.link_mode&&(i=p.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((r=p.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(p){await this.sendError({id:u,topic:o,error:p}),this.client.logger.error(p)}}),x(this,"onSessionRequestResponse",(t,i)=>{const{id:r}=i,n=Ie("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ie("session_request",r),{result:i.result}):st(i)&&this.events.emit(Ie("session_request",r),{error:i.error})}),x(this,"onSessionEventRequest",async(t,i)=>{const{id:r,params:n}=i;try{const o=`${t}_session_event_${n.event.name}`,a=co.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Ze({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),co.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),x(this,"onSessionAuthenticateResponse",(t,i)=>{const{id:r}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),vt(i)?this.events.emit(Ie("session_request",r),{result:i.result}):st(i)&&this.events.emit(Ie("session_request",r),{error:i.error})}),x(this,"onSessionAuthenticateRequest",async t=>{var i;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:l}=t;try{const{requester:c,authPayload:h,expiryTimestamp:u}=n.params,d=await this.getVerifyContext({attestationId:o,hash:di(JSON.stringify(n)),encryptedId:a,metadata:c.metadata,transportType:l}),p={requester:c,pairingTopic:r,id:n.id,authPayload:h,verifyContext:d,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:p,pairingTopic:r,transportType:l}),l===Ve.link_mode&&(i=c.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:d})}catch(c){this.client.logger.error(c);const h=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,l),p={type:gi,receiverPublicKey:h,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:c,encodeOpts:p,rpcOpts:ft.wc_sessionAuthenticate.autoReject,appLink:d})}}),x(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),x(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Vs.idle,this.processSessionRequestQueue()},E.toMiliseconds(this.requestQueueDelay))}),x(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:i})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=Ie("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Ie("session_request",n.request.id),{error:i})})}),x(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Vs.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Vs.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}}),x(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),x(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:Gt("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})}),x(this,"isValidConnect",async t=>{if(!is(t)){const{message:l}=k("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,relays:a}=t;if(Kt(i)||await this.isValidPairingTopic(i),!nA(a)){const{message:l}=k("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(l)}!Kt(r)&&Jo(r)!==0&&this.validateNamespaces(r,"requiredNamespaces"),!Kt(n)&&Jo(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Kt(o)||this.validateSessionProps(o,"sessionProperties")}),x(this,"validateNamespaces",(t,i)=>{const r=rA(t,"connect()",i);if(r)throw new Error(r.message)}),x(this,"isValidApprove",async t=>{if(!is(t))throw new Error(k("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:r,relayProtocol:n,sessionProperties:o}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const a=this.client.proposal.get(i),l=Il(r,"approve()");if(l)throw new Error(l.message);const c=op(a.requiredNamespaces,r,"approve()");if(c)throw new Error(c.message);if(!it(n,!0)){const{message:h}=k("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}Kt(o)||this.validateSessionProps(o,"sessionProperties")}),x(this,"isValidReject",async t=>{if(!is(t)){const{message:n}=k("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:r}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!aA(r)){const{message:n}=k("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),x(this,"isValidSessionSettleRequest",t=>{if(!is(t)){const{message:c}=k("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(c)}const{relay:i,controller:r,namespaces:n,expiry:o}=t;if(!Mw(i)){const{message:c}=k("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}const a=JE(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const l=Il(n,"onSessionSettleRequest()");if(l)throw new Error(l.message);if(Si(o)){const{message:c}=k("EXPIRED","onSessionSettleRequest()");throw new Error(c)}}),x(this,"isValidUpdate",async t=>{if(!is(t)){const{message:l}=k("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(l)}const{topic:i,namespaces:r}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=Il(r,"update()");if(o)throw new Error(o.message);const a=op(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),x(this,"isValidExtend",async t=>{if(!is(t)){const{message:r}=k("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),x(this,"isValidRequest",async t=>{if(!is(t)){const{message:l}=k("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(l)}const{topic:i,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!np(a,n)){const{message:l}=k("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(l)}if(!cA(r)){const{message:l}=k("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(l)}if(!uA(a,n,r.method)){const{message:l}=k("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(l)}if(o&&!fA(o,Sl)){const{message:l}=k("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Sl.min} and ${Sl.max}`);throw new Error(l)}}),x(this,"isValidRespond",async t=>{var i;if(!is(t)){const{message:o}=k("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(i=t==null?void 0:t.response)!=null&&i.id&&this.cleanupAfterResponse(t),o}if(!lA(n)){const{message:o}=k("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),x(this,"isValidPing",async t=>{if(!is(t)){const{message:r}=k("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),x(this,"isValidEmit",async t=>{if(!is(t)){const{message:a}=k("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:i,event:r,chainId:n}=t;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!np(o,n)){const{message:a}=k("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!hA(r)){const{message:a}=k("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!dA(o,n,r.name)){const{message:a}=k("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),x(this,"isValidDisconnect",async t=>{if(!is(t)){const{message:r}=k("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),x(this,"isValidAuthenticate",t=>{const{chains:i,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!it(r,!1))throw new Error("uri is required parameter");if(!it(n,!1))throw new Error("domain is required parameter");if(!it(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(l=>On(l).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=On(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),x(this,"getVerifyContext",async t=>{const{attestationId:i,hash:r,encryptedId:n,metadata:o,transportType:a}=t,l={verified:{verifyUrl:o.verifyUrl||Ro,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Ve.link_mode){const h=this.getAppLinkIfEnabled(o,a);return l.verified.validation=h&&new URL(h).origin===new URL(o.url).origin?"VALID":"INVALID",l}const c=await this.client.core.verify.resolve({attestationId:i,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});c&&(l.verified.origin=c.origin,l.verified.isScam=c.isScam,l.verified.validation=c.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(c){this.client.logger.warn(c)}return this.client.logger.debug(`Verify context: ${JSON.stringify(l)}`),l}),x(this,"validateSessionProps",(t,i)=>{Object.values(t).forEach(r=>{if(!it(r,!1)){const{message:n}=k("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(r)}`);throw new Error(n)}})}),x(this,"getPendingAuthRequest",t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0}),x(this,"addToRecentlyDeleted",(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=n)break;this.recentlyDeletedMap.delete(o)}}}),x(this,"checkRecentlyDeleted",t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:r}=k("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(r)}}),x(this,"isLinkModeEnabled",(t,i)=>{var r,n,o,a,l,c,h,u,d;return!t||i!==Ve.link_mode?!1:((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((c=(l=this.client.metadata)==null?void 0:l.redirect)==null?void 0:c.universal)!==""&&((h=t==null?void 0:t.redirect)==null?void 0:h.universal)!==void 0&&((u=t==null?void 0:t.redirect)==null?void 0:u.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(_.global==null?void 0:_.global.Linking)<"u"}),x(this,"getAppLinkIfEnabled",(t,i)=>{var r;return this.isLinkModeEnabled(t,i)?(r=t==null?void 0:t.redirect)==null?void 0:r.universal:void 0}),x(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Sd(t,"topic")||"",r=decodeURIComponent(Sd(t,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:Ve.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:r,sessionExists:n})}),x(this,"registerLinkModeListeners",async()=>{var t;if(_u()||Gi()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=_.global==null?void 0:_.global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await i.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),x(this,"shouldSetTVF",(t,i)=>{if(!i||t!=="wc_sessionRequest")return!1;const{request:r}=i;return Object.keys(xp).includes(r.method)}),x(this,"getTVFParams",(t,i,r)=>{var n,o;try{const a=i.request.method,l=this.extractTxHashesFromResult(a,r);return Zt(Ze({correlationId:t,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:l})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),x(this,"isValidContractData",t=>{var i;if(!t)return!1;try{const r=(t==null?void 0:t.data)||((i=t==null?void 0:t[0])==null?void 0:i.data);if(!r.startsWith("0x"))return!1;const n=r.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),x(this,"extractTxHashesFromResult",(t,i)=>{try{const r=xp[t];if(typeof i=="string")return[i];const n=i[r.key];if(vr(n))return n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(It.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(oc)?this.client.auth.authKeys.get(oc):{publicKey:void 0},a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===Ve.link_mode?ao:ji});try{Kn(a)?(this.client.core.history.set(t,a),this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:di(i)})):$r(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n})}catch(l){this.client.logger.error(l)}}registerExpirerEvents(){this.client.core.expirer.on(Cs.expired,async e=>{const{topic:t,id:i}=nw(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,k("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,k("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(cr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(cr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!it(e,!1)){const{message:t}=k("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=k("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Si(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=k("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!it(e,!1)){const{message:t}=k("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=k("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Si(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=k("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=k("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(it(e,!1)){const{message:t}=k("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=k("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!oA(e)){const{message:t}=k("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=k("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Si(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=k("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}},YC=class extends Tr{constructor(e,t){super(e,t,xC,Du),this.core=e,this.logger=t}},QC=class extends Tr{constructor(e,t){super(e,t,DC,Du),this.core=e,this.logger=t}},ZC=class extends Tr{constructor(e,t){super(e,t,jC,Du,i=>i.id),this.core=e,this.logger=t}},JC=class extends Tr{constructor(e,t){super(e,t,zC,Kc,()=>oc),this.core=e,this.logger=t}},XC=class extends Tr{constructor(e,t){super(e,t,FC,Kc),this.core=e,this.logger=t}},eS=class extends Tr{constructor(e,t){super(e,t,qC,Kc,i=>i.id),this.core=e,this.logger=t}};var tS=Object.defineProperty,sS=(s,e,t)=>e in s?tS(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,$l=(s,e,t)=>sS(s,typeof e!="symbol"?e+"":e,t);let iS=class{constructor(e,t){this.core=e,this.logger=t,$l(this,"authKeys"),$l(this,"pairingTopics"),$l(this,"requests"),this.authKeys=new JC(this.core,this.logger),this.pairingTopics=new XC(this.core,this.logger),this.requests=new eS(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}};var rS=Object.defineProperty,nS=(s,e,t)=>e in s?rS(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ce=(s,e,t)=>nS(s,typeof e!="symbol"?e+"":e,t);let oS=class Jw extends MC{constructor(e){super(e),ce(this,"protocol",Yw),ce(this,"version",Qw),ce(this,"name",Cl.name),ce(this,"metadata"),ce(this,"core"),ce(this,"logger"),ce(this,"events",new kt.EventEmitter),ce(this,"engine"),ce(this,"session"),ce(this,"proposal"),ce(this,"pendingRequest"),ce(this,"auth"),ce(this,"signConfig"),ce(this,"on",(i,r)=>this.events.on(i,r)),ce(this,"once",(i,r)=>this.events.once(i,r)),ce(this,"off",(i,r)=>this.events.off(i,r)),ce(this,"removeListener",(i,r)=>this.events.removeListener(i,r)),ce(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),ce(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"update",async i=>{try{return await this.engine.update(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"request",async i=>{try{return await this.engine.request(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"find",i=>{try{return this.engine.find(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),ce(this,"authenticate",async(i,r)=>{try{return await this.engine.authenticate(i,r)}catch(n){throw this.logger.error(n.message),n}}),ce(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||Cl.name,this.metadata=(e==null?void 0:e.metadata)||ew(),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Vn(yi({level:(e==null?void 0:e.logger)||Cl.logger}));this.core=(e==null?void 0:e.core)||new $C(e),this.logger=Ne(t,this.name),this.session=new QC(this.core,this.logger),this.proposal=new YC(this.core,this.logger),this.pendingRequest=new ZC(this.core,this.logger),this.engine=new GC(this),this.auth=new iS(this.core,this.logger)}static async init(e){const t=new Jw(e);return await t.initialize(),t}get context(){return qe(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()},E.toMiliseconds(E.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const kp="error",aS="wss://relay.walletconnect.org",cS="wc",lS="universal_provider",jp=`${cS}@2:${lS}:`,Xw="https://rpc.walletconnect.org/v1/",yn="generic",hS=`${Xw}bundler`,Ts={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Ra=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof _.global<"u"?_.global:typeof self<"u"?self:{};function uS(){this.__data__=[],this.size=0}var dS=uS;function pS(s,e){return s===e||s!==s&&e!==e}var Gc=pS,gS=Gc;function fS(s,e){for(var t=s.length;t--;)if(gS(s[t][0],e))return t;return-1}var Yc=fS,mS=Yc,wS=Array.prototype,yS=wS.splice;function bS(s){var e=this.__data__,t=mS(e,s);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():yS.call(e,t,1),--this.size,!0}var vS=bS,IS=Yc;function ES(s){var e=this.__data__,t=IS(e,s);return t<0?void 0:e[t][1]}var AS=ES,NS=Yc;function _S(s){return NS(this.__data__,s)>-1}var CS=_S,SS=Yc;function $S(s,e){var t=this.__data__,i=SS(t,s);return i<0?(++this.size,t.push([s,e])):t[i][1]=e,this}var PS=$S,TS=dS,MS=vS,OS=AS,xS=CS,DS=PS;function bn(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}bn.prototype.clear=TS,bn.prototype.delete=MS,bn.prototype.get=OS,bn.prototype.has=xS,bn.prototype.set=DS;var Qc=bn,kS=Qc;function jS(){this.__data__=new kS,this.size=0}var RS=jS;function LS(s){var e=this.__data__,t=e.delete(s);return this.size=e.size,t}var US=LS;function zS(s){return this.__data__.get(s)}var FS=zS;function qS(s){return this.__data__.has(s)}var BS=qS,HS=typeof Ra=="object"&&Ra&&Ra.Object===Object&&Ra,ey=HS,WS=ey,VS=typeof self=="object"&&self&&self.Object===Object&&self,KS=WS||VS||Function("return this")(),Zn=KS,GS=Zn,YS=GS.Symbol,ty=YS,Rp=ty,sy=Object.prototype,QS=sy.hasOwnProperty,ZS=sy.toString,go=Rp?Rp.toStringTag:void 0;function JS(s){var e=QS.call(s,go),t=s[go];try{s[go]=void 0;var i=!0}catch{}var r=ZS.call(s);return i&&(e?s[go]=t:delete s[go]),r}var XS=JS,e$=Object.prototype,t$=e$.toString;function s$(s){return t$.call(s)}var i$=s$,Lp=ty,r$=XS,n$=i$,o$="[object Null]",a$="[object Undefined]",Up=Lp?Lp.toStringTag:void 0;function c$(s){return s==null?s===void 0?a$:o$:Up&&Up in Object(s)?r$(s):n$(s)}var Zc=c$;function l$(s){var e=typeof s;return s!=null&&(e=="object"||e=="function")}var Mr=l$,h$=Zc,u$=Mr,d$="[object AsyncFunction]",p$="[object Function]",g$="[object GeneratorFunction]",f$="[object Proxy]";function m$(s){if(!u$(s))return!1;var e=h$(s);return e==p$||e==g$||e==d$||e==f$}var ku=m$,w$=Zn,y$=w$["__core-js_shared__"],b$=y$,Pl=b$,zp=function(){var s=/[^.]+$/.exec(Pl&&Pl.keys&&Pl.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function v$(s){return!!zp&&zp in s}var I$=v$,E$=Function.prototype,A$=E$.toString;function N$(s){if(s!=null){try{return A$.call(s)}catch{}try{return s+""}catch{}}return""}var _$=N$,C$=ku,S$=I$,$$=Mr,P$=_$,T$=/[\\^$.*+?()[\]{}|]/g,M$=/^\[object .+?Constructor\]$/,O$=Function.prototype,x$=Object.prototype,D$=O$.toString,k$=x$.hasOwnProperty,j$=RegExp("^"+D$.call(k$).replace(T$,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function R$(s){if(!$$(s)||S$(s))return!1;var e=C$(s)?j$:M$;return e.test(P$(s))}var L$=R$;function U$(s,e){return s==null?void 0:s[e]}var z$=U$,F$=L$,q$=z$;function B$(s,e){var t=q$(s,e);return F$(t)?t:void 0}var ju=B$,H$=ju,W$=Zn,V$=H$(W$,"Map"),iy=V$,K$=ju,G$=K$(Object,"create"),Jc=G$,Fp=Jc;function Y$(){this.__data__=Fp?Fp(null):{},this.size=0}var Q$=Y$;function Z$(s){var e=this.has(s)&&delete this.__data__[s];return this.size-=e?1:0,e}var J$=Z$,X$=Jc,eP="__lodash_hash_undefined__",tP=Object.prototype,sP=tP.hasOwnProperty;function iP(s){var e=this.__data__;if(X$){var t=e[s];return t===eP?void 0:t}return sP.call(e,s)?e[s]:void 0}var rP=iP,nP=Jc,oP=Object.prototype,aP=oP.hasOwnProperty;function cP(s){var e=this.__data__;return nP?e[s]!==void 0:aP.call(e,s)}var lP=cP,hP=Jc,uP="__lodash_hash_undefined__";function dP(s,e){var t=this.__data__;return this.size+=this.has(s)?0:1,t[s]=hP&&e===void 0?uP:e,this}var pP=dP,gP=Q$,fP=J$,mP=rP,wP=lP,yP=pP;function vn(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}vn.prototype.clear=gP,vn.prototype.delete=fP,vn.prototype.get=mP,vn.prototype.has=wP,vn.prototype.set=yP;var bP=vn,qp=bP,vP=Qc,IP=iy;function EP(){this.size=0,this.__data__={hash:new qp,map:new(IP||vP),string:new qp}}var AP=EP;function NP(s){var e=typeof s;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?s!=="__proto__":s===null}var _P=NP,CP=_P;function SP(s,e){var t=s.__data__;return CP(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Xc=SP,$P=Xc;function PP(s){var e=$P(this,s).delete(s);return this.size-=e?1:0,e}var TP=PP,MP=Xc;function OP(s){return MP(this,s).get(s)}var xP=OP,DP=Xc;function kP(s){return DP(this,s).has(s)}var jP=kP,RP=Xc;function LP(s,e){var t=RP(this,s),i=t.size;return t.set(s,e),this.size+=t.size==i?0:1,this}var UP=LP,zP=AP,FP=TP,qP=xP,BP=jP,HP=UP;function In(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}In.prototype.clear=zP,In.prototype.delete=FP,In.prototype.get=qP,In.prototype.has=BP,In.prototype.set=HP;var WP=In,VP=Qc,KP=iy,GP=WP,YP=200;function QP(s,e){var t=this.__data__;if(t instanceof VP){var i=t.__data__;if(!KP||i.length<YP-1)return i.push([s,e]),this.size=++t.size,this;t=this.__data__=new GP(i)}return t.set(s,e),this.size=t.size,this}var ZP=QP,JP=Qc,XP=RS,eT=US,tT=FS,sT=BS,iT=ZP;function En(s){var e=this.__data__=new JP(s);this.size=e.size}En.prototype.clear=XP,En.prototype.delete=eT,En.prototype.get=tT,En.prototype.has=sT,En.prototype.set=iT;var rT=En,nT=ju,oT=function(){try{var s=nT(Object,"defineProperty");return s({},"",{}),s}catch{}}(),ry=oT,Bp=ry;function aT(s,e,t){e=="__proto__"&&Bp?Bp(s,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):s[e]=t}var Ru=aT,cT=Ru,lT=Gc;function hT(s,e,t){(t!==void 0&&!lT(s[e],t)||t===void 0&&!(e in s))&&cT(s,e,t)}var ny=hT;function uT(s){return function(e,t,i){for(var r=-1,n=Object(e),o=i(e),a=o.length;a--;){var l=o[s?a:++r];if(t(n[l],l,n)===!1)break}return e}}var dT=uT,pT=dT,gT=pT(),fT=gT,Lh={exports:{}};(function(s,e){var t=Zn,i=e&&!e.nodeType&&e,r=i&&!0&&s&&!s.nodeType&&s,n=r&&r.exports===i,o=n?t.Buffer:void 0,a=o?o.allocUnsafe:void 0;function l(c,h){if(h)return c.slice();var u=c.length,d=a?a(u):new c.constructor(u);return c.copy(d),d}s.exports=l})(Lh,Lh.exports);var mT=Zn,wT=mT.Uint8Array,yT=wT,Hp=yT;function bT(s){var e=new s.constructor(s.byteLength);return new Hp(e).set(new Hp(s)),e}var vT=bT,IT=vT;function ET(s,e){var t=e?IT(s.buffer):s.buffer;return new s.constructor(t,s.byteOffset,s.length)}var AT=ET;function NT(s,e){var t=-1,i=s.length;for(e||(e=Array(i));++t<i;)e[t]=s[t];return e}var _T=NT,CT=Mr,Wp=Object.create,ST=function(){function s(){}return function(e){if(!CT(e))return{};if(Wp)return Wp(e);s.prototype=e;var t=new s;return s.prototype=void 0,t}}(),$T=ST;function PT(s,e){return function(t){return s(e(t))}}var TT=PT,MT=TT,OT=MT(Object.getPrototypeOf,Object),oy=OT,xT=Object.prototype;function DT(s){var e=s&&s.constructor,t=typeof e=="function"&&e.prototype||xT;return s===t}var ay=DT,kT=$T,jT=oy,RT=ay;function LT(s){return typeof s.constructor=="function"&&!RT(s)?kT(jT(s)):{}}var UT=LT;function zT(s){return s!=null&&typeof s=="object"}var ba=zT,FT=Zc,qT=ba,BT="[object Arguments]";function HT(s){return qT(s)&&FT(s)==BT}var WT=HT,Vp=WT,VT=ba,cy=Object.prototype,KT=cy.hasOwnProperty,GT=cy.propertyIsEnumerable,YT=Vp(function(){return arguments}())?Vp:function(s){return VT(s)&&KT.call(s,"callee")&&!GT.call(s,"callee")},ly=YT,QT=Array.isArray,hy=QT,ZT=9007199254740991;function JT(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=ZT}var uy=JT,XT=ku,e2=uy;function t2(s){return s!=null&&e2(s.length)&&!XT(s)}var Lu=t2,s2=Lu,i2=ba;function r2(s){return i2(s)&&s2(s)}var n2=r2,Sc={exports:{}};function o2(){return!1}var a2=o2;(function(s,e){var t=Zn,i=a2,r=e&&!e.nodeType&&e,n=r&&!0&&s&&!s.nodeType&&s,o=n&&n.exports===r,a=o?t.Buffer:void 0,l=a?a.isBuffer:void 0,c=l||i;s.exports=c})(Sc,Sc.exports);var c2=Zc,l2=oy,h2=ba,u2="[object Object]",d2=Function.prototype,p2=Object.prototype,dy=d2.toString,g2=p2.hasOwnProperty,f2=dy.call(Object);function m2(s){if(!h2(s)||c2(s)!=u2)return!1;var e=l2(s);if(e===null)return!0;var t=g2.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&dy.call(t)==f2}var w2=m2,y2=Zc,b2=uy,v2=ba,I2="[object Arguments]",E2="[object Array]",A2="[object Boolean]",N2="[object Date]",_2="[object Error]",C2="[object Function]",S2="[object Map]",$2="[object Number]",P2="[object Object]",T2="[object RegExp]",M2="[object Set]",O2="[object String]",x2="[object WeakMap]",D2="[object ArrayBuffer]",k2="[object DataView]",j2="[object Float32Array]",R2="[object Float64Array]",L2="[object Int8Array]",U2="[object Int16Array]",z2="[object Int32Array]",F2="[object Uint8Array]",q2="[object Uint8ClampedArray]",B2="[object Uint16Array]",H2="[object Uint32Array]",We={};We[j2]=We[R2]=We[L2]=We[U2]=We[z2]=We[F2]=We[q2]=We[B2]=We[H2]=!0,We[I2]=We[E2]=We[D2]=We[A2]=We[k2]=We[N2]=We[_2]=We[C2]=We[S2]=We[$2]=We[P2]=We[T2]=We[M2]=We[O2]=We[x2]=!1;function W2(s){return v2(s)&&b2(s.length)&&!!We[y2(s)]}var V2=W2;function K2(s){return function(e){return s(e)}}var G2=K2,Uh={exports:{}};(function(s,e){var t=ey,i=e&&!e.nodeType&&e,r=i&&!0&&s&&!s.nodeType&&s,n=r&&r.exports===i,o=n&&t.process,a=function(){try{var l=r&&r.require&&r.require("util").types;return l||o&&o.binding&&o.binding("util")}catch{}}();s.exports=a})(Uh,Uh.exports);var Y2=V2,Q2=G2,Kp=Uh.exports,Gp=Kp&&Kp.isTypedArray,Z2=Gp?Q2(Gp):Y2,py=Z2;function J2(s,e){if(!(e==="constructor"&&typeof s[e]=="function")&&e!="__proto__")return s[e]}var gy=J2,X2=Ru,eM=Gc,tM=Object.prototype,sM=tM.hasOwnProperty;function iM(s,e,t){var i=s[e];(!(sM.call(s,e)&&eM(i,t))||t===void 0&&!(e in s))&&X2(s,e,t)}var rM=iM,nM=rM,oM=Ru;function aM(s,e,t,i){var r=!t;t||(t={});for(var n=-1,o=e.length;++n<o;){var a=e[n],l=i?i(t[a],s[a],a,t,s):void 0;l===void 0&&(l=s[a]),r?oM(t,a,l):nM(t,a,l)}return t}var cM=aM;function lM(s,e){for(var t=-1,i=Array(s);++t<s;)i[t]=e(t);return i}var hM=lM,uM=9007199254740991,dM=/^(?:0|[1-9]\d*)$/;function pM(s,e){var t=typeof s;return e=e??uM,!!e&&(t=="number"||t!="symbol"&&dM.test(s))&&s>-1&&s%1==0&&s<e}var fy=pM,gM=hM,fM=ly,mM=hy,wM=Sc.exports,yM=fy,bM=py,vM=Object.prototype,IM=vM.hasOwnProperty;function EM(s,e){var t=mM(s),i=!t&&fM(s),r=!t&&!i&&wM(s),n=!t&&!i&&!r&&bM(s),o=t||i||r||n,a=o?gM(s.length,String):[],l=a.length;for(var c in s)(e||IM.call(s,c))&&!(o&&(c=="length"||r&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||yM(c,l)))&&a.push(c);return a}var AM=EM;function NM(s){var e=[];if(s!=null)for(var t in Object(s))e.push(t);return e}var _M=NM,CM=Mr,SM=ay,$M=_M,PM=Object.prototype,TM=PM.hasOwnProperty;function MM(s){if(!CM(s))return $M(s);var e=SM(s),t=[];for(var i in s)i=="constructor"&&(e||!TM.call(s,i))||t.push(i);return t}var OM=MM,xM=AM,DM=OM,kM=Lu;function jM(s){return kM(s)?xM(s,!0):DM(s)}var my=jM,RM=cM,LM=my;function UM(s){return RM(s,LM(s))}var zM=UM,Yp=ny,FM=Lh.exports,qM=AT,BM=_T,HM=UT,Qp=ly,Zp=hy,WM=n2,VM=Sc.exports,KM=ku,GM=Mr,YM=w2,QM=py,Jp=gy,ZM=zM;function JM(s,e,t,i,r,n,o){var a=Jp(s,t),l=Jp(e,t),c=o.get(l);if(c){Yp(s,t,c);return}var h=n?n(a,l,t+"",s,e,o):void 0,u=h===void 0;if(u){var d=Zp(l),p=!d&&VM(l),g=!d&&!p&&QM(l);h=l,d||p||g?Zp(a)?h=a:WM(a)?h=BM(a):p?(u=!1,h=FM(l,!0)):g?(u=!1,h=qM(l,!0)):h=[]:YM(l)||Qp(l)?(h=a,Qp(a)?h=ZM(a):(!GM(a)||KM(a))&&(h=HM(l))):u=!1}u&&(o.set(l,h),r(h,l,i,n,o),o.delete(l)),Yp(s,t,h)}var XM=JM,eO=rT,tO=ny,sO=fT,iO=XM,rO=Mr,nO=my,oO=gy;function wy(s,e,t,i,r){s!==e&&sO(e,function(n,o){if(r||(r=new eO),rO(n))iO(s,e,o,t,wy,i,r);else{var a=i?i(oO(s,o),n,o+"",s,e,r):void 0;a===void 0&&(a=n),tO(s,o,a)}},nO)}var aO=wy;function cO(s){return s}var yy=cO;function lO(s,e,t){switch(t.length){case 0:return s.call(e);case 1:return s.call(e,t[0]);case 2:return s.call(e,t[0],t[1]);case 3:return s.call(e,t[0],t[1],t[2])}return s.apply(e,t)}var hO=lO,uO=hO,Xp=Math.max;function dO(s,e,t){return e=Xp(e===void 0?s.length-1:e,0),function(){for(var i=arguments,r=-1,n=Xp(i.length-e,0),o=Array(n);++r<n;)o[r]=i[e+r];r=-1;for(var a=Array(e+1);++r<e;)a[r]=i[r];return a[e]=t(o),uO(s,this,a)}}var pO=dO;function gO(s){return function(){return s}}var fO=gO,mO=fO,eg=ry,wO=yy,yO=eg?function(s,e){return eg(s,"toString",{configurable:!0,enumerable:!1,value:mO(e),writable:!0})}:wO,bO=yO,vO=800,IO=16,EO=Date.now;function AO(s){var e=0,t=0;return function(){var i=EO(),r=IO-(i-t);if(t=i,r>0){if(++e>=vO)return arguments[0]}else e=0;return s.apply(void 0,arguments)}}var NO=AO,_O=bO,CO=NO,SO=CO(_O),$O=SO,PO=yy,TO=pO,MO=$O;function OO(s,e){return MO(TO(s,e,PO),s+"")}var xO=OO,DO=Gc,kO=Lu,jO=fy,RO=Mr;function LO(s,e,t){if(!RO(t))return!1;var i=typeof e;return(i=="number"?kO(t)&&jO(e,t.length):i=="string"&&e in t)?DO(t[e],s):!1}var UO=LO,zO=xO,FO=UO;function qO(s){return zO(function(e,t){var i=-1,r=t.length,n=r>1?t[r-1]:void 0,o=r>2?t[2]:void 0;for(n=s.length>3&&typeof n=="function"?(r--,n):void 0,o&&FO(t[0],t[1],o)&&(n=r<3?void 0:n,r=1),e=Object(e);++i<r;){var a=t[i];a&&s(e,a,i,n)}return e})}var BO=qO,HO=aO,WO=BO,VO=WO(function(s,e,t){HO(s,e,t)}),KO=VO,GO=Object.defineProperty,YO=Object.defineProperties,QO=Object.getOwnPropertyDescriptors,tg=Object.getOwnPropertySymbols,ZO=Object.prototype.hasOwnProperty,JO=Object.prototype.propertyIsEnumerable,sg=(s,e,t)=>e in s?GO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,La=(s,e)=>{for(var t in e||(e={}))ZO.call(e,t)&&sg(s,t,e[t]);if(tg)for(var t of tg(e))JO.call(e,t)&&sg(s,t,e[t]);return s},XO=(s,e)=>YO(s,QO(e));function ws(s,e,t){var i;const r=On(s);return((i=e.rpcMap)==null?void 0:i[r.reference])||`${Xw}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Or(s){return s.includes(":")?s.split(":")[1]:s}function by(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function ex(s,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(s));if(!t.length)return[];const i=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;i.push(...n)}),i}function Tl(s={},e={}){const t=ig(s),i=ig(e);return KO(t,i)}function ig(s){var e,t,i,r;const n={};if(!Jo(s))return n;for(const[o,a]of Object.entries(s)){const l=Ou(o)?[o]:a.chains,c=a.methods||[],h=a.events||[],u=a.rpcMap||{},d=Po(o);n[d]=XO(La(La({},n[d]),a),{chains:ic(l,(e=n[d])==null?void 0:e.chains),methods:ic(c,(t=n[d])==null?void 0:t.methods),events:ic(h,(i=n[d])==null?void 0:i.events),rpcMap:La(La({},u),(r=n[d])==null?void 0:r.rpcMap)})}return n}function tx(s){return s.includes(":")?s.split(":")[2]:s}function rg(s){const e={};for(const[t,i]of Object.entries(s)){const r=i.methods||[],n=i.events||[],o=i.accounts||[],a=Ou(t)?[t]:i.chains?i.chains:by(i.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Ml(s){return typeof s=="number"?s:s.includes("0x")?parseInt(s,16):(s=s.includes(":")?s.split(":")[1]:s,isNaN(Number(s))?s:Number(s))}const vy={},we=s=>vy[s],Ol=(s,e)=>{vy[s]=e};var sx=Object.defineProperty,ix=(s,e,t)=>e in s?sx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Br=(s,e,t)=>ix(s,typeof e!="symbol"?e+"":e,t);class rx{constructor(e){Br(this,"name","polkadot"),Br(this,"client"),Br(this,"httpProviders"),Br(this,"events"),Br(this,"namespace"),Br(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Or(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var nx=Object.defineProperty,ox=Object.defineProperties,ax=Object.getOwnPropertyDescriptors,ng=Object.getOwnPropertySymbols,cx=Object.prototype.hasOwnProperty,lx=Object.prototype.propertyIsEnumerable,zh=(s,e,t)=>e in s?nx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,og=(s,e)=>{for(var t in e||(e={}))cx.call(e,t)&&zh(s,t,e[t]);if(ng)for(var t of ng(e))lx.call(e,t)&&zh(s,t,e[t]);return s},ag=(s,e)=>ox(s,ax(e)),Hr=(s,e,t)=>zh(s,typeof e!="symbol"?e+"":e,t);class hx{constructor(e){Hr(this,"name","eip155"),Hr(this,"client"),Hr(this,"chainId"),Hr(this,"namespace"),Hr(this,"httpProviders"),Hr(this,"events"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(Ts.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,t){const i=t||ws(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=parseInt(Or(t));e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let r=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const n=parseInt(r,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:r}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,r;const n=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0];if(!n)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const o=this.client.session.get(e.topic),a=((r=o==null?void 0:o.sessionProperties)==null?void 0:r.capabilities)||{};if(a!=null&&a[n])return a==null?void 0:a[n];const l=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ag(og({},o.sessionProperties||{}),{capabilities:ag(og({},a||{}),{[n]:l})})})}catch(c){console.warn("Failed to update session with capabilities",c)}return l}async getCallStatus(e){var t,i;const r=this.client.session.get(e.topic),n=(t=r.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from bundler",l,a)}}const o=(i=r.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Gt("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${hS}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var ux=Object.defineProperty,dx=(s,e,t)=>e in s?ux(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Wr=(s,e,t)=>dx(s,typeof e!="symbol"?e+"":e,t);class px{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=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Or(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var gx=Object.defineProperty,fx=(s,e,t)=>e in s?gx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Vr=(s,e,t)=>fx(s,typeof e!="symbol"?e+"":e,t);class mx{constructor(e){Vr(this,"name","cosmos"),Vr(this,"client"),Vr(this,"httpProviders"),Vr(this,"events"),Vr(this,"namespace"),Vr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Or(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var wx=Object.defineProperty,yx=(s,e,t)=>e in s?wx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Kr=(s,e,t)=>yx(s,typeof e!="symbol"?e+"":e,t);class bx{constructor(e){Kr(this,"name","algorand"),Kr(this,"client"),Kr(this,"httpProviders"),Kr(this,"events"),Kr(this,"namespace"),Kr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){if(!this.httpProviders[e]){const i=t||ws(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(Ts.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new Ye(new tt(i,we("disableProviderPing")))}}var vx=Object.defineProperty,Ix=(s,e,t)=>e in s?vx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Gr=(s,e,t)=>Ix(s,typeof e!="symbol"?e+"":e,t);class Ex{constructor(e){Gr(this,"name","cip34"),Gr(this,"client"),Gr(this,"httpProviders"),Gr(this,"events"),Gr(this,"namespace"),Gr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),r=Or(t);e[r]=this.createHttpProvider(r,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var Ax=Object.defineProperty,Nx=(s,e,t)=>e in s?Ax(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Yr=(s,e,t)=>Nx(s,typeof e!="symbol"?e+"":e,t);class _x{constructor(e){Yr(this,"name","elrond"),Yr(this,"client"),Yr(this,"httpProviders"),Yr(this,"events"),Yr(this,"namespace"),Yr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Or(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var Cx=Object.defineProperty,Sx=(s,e,t)=>e in s?Cx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Qr=(s,e,t)=>Sx(s,typeof e!="symbol"?e+"":e,t);class $x{constructor(e){Qr(this,"name","multiversx"),Qr(this,"client"),Qr(this,"httpProviders"),Qr(this,"events"),Qr(this,"namespace"),Qr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Or(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var Px=Object.defineProperty,Tx=(s,e,t)=>e in s?Px(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Zr=(s,e,t)=>Tx(s,typeof e!="symbol"?e+"":e,t);class Mx{constructor(e){Zr(this,"name","near"),Zr(this,"client"),Zr(this,"httpProviders"),Zr(this,"events"),Zr(this,"namespace"),Zr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||ws(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Ts.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace);return typeof i>"u"?void 0:new Ye(new tt(i,we("disableProviderPing")))}}var Ox=Object.defineProperty,xx=(s,e,t)=>e in s?Ox(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Jr=(s,e,t)=>xx(s,typeof e!="symbol"?e+"":e,t);class Dx{constructor(e){Jr(this,"name","tezos"),Jr(this,"client"),Jr(this,"httpProviders"),Jr(this,"events"),Jr(this,"namespace"),Jr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||ws(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Ts.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace);return typeof i>"u"?void 0:new Ye(new tt(i))}}var kx=Object.defineProperty,jx=(s,e,t)=>e in s?kx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Xr=(s,e,t)=>jx(s,typeof e!="symbol"?e+"":e,t);class Rx{constructor(e){Xr(this,"name",yn),Xr(this,"client"),Xr(this,"httpProviders"),Xr(this,"events"),Xr(this,"namespace"),Xr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=On(r);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var Lx=Object.defineProperty,Ux=Object.defineProperties,zx=Object.getOwnPropertyDescriptors,cg=Object.getOwnPropertySymbols,Fx=Object.prototype.hasOwnProperty,qx=Object.prototype.propertyIsEnumerable,Fh=(s,e,t)=>e in s?Lx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ua=(s,e)=>{for(var t in e||(e={}))Fx.call(e,t)&&Fh(s,t,e[t]);if(cg)for(var t of cg(e))qx.call(e,t)&&Fh(s,t,e[t]);return s},xl=(s,e)=>Ux(s,zx(e)),ks=(s,e,t)=>Fh(s,typeof e!="symbol"?e+"":e,t);class Uu{constructor(e){ks(this,"client"),ks(this,"namespaces"),ks(this,"optionalNamespaces"),ks(this,"sessionProperties"),ks(this,"events",new Wn),ks(this,"rpcProviders",{}),ks(this,"session"),ks(this,"providerOpts"),ks(this,"logger"),ks(this,"uri"),ks(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Vn(yi({level:(e==null?void 0:e.logger)||kp})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Uu(e);return await t.initialize(),t}async request(e,t,i){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Ua({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,r){const n=new Date().getTime();this.request(e,i,r).then(o=>t(null,Vi(n,o))).catch(o=>t(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}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:r}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await r();if(this.session=n.session,this.session){const o=rg(this.session.namespaces);this.namespaces=Tl(this.namespaces,o),this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await i();this.session=r;const n=rg(r.namespaces);return this.namespaces=Tl(this.namespaces,n),this.persist("namespaces",this.namespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,r]=this.validateChain(e),n=this.getProvider(i);n.name===yn?n.setDefaultChain(`${i}:${r}`,t):n.setDefaultChain(r,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(vr(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await oS.init({core:this.providerOpts.core,logger:this.providerOpts.logger||kp,relayUrl:this.providerOpts.relayUrl||aS,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.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(t=>Po(t)))];Ol("client",this.client),Ol("events",this.events),Ol("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=ex(t,this.session),r=by(i),n=Tl(this.namespaces,this.optionalNamespaces),o=xl(Ua({},n[t]),{accounts:i,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new hx({namespace:o});break;case"algorand":this.rpcProviders[t]=new bx({namespace:o});break;case"solana":this.rpcProviders[t]=new px({namespace:o});break;case"cosmos":this.rpcProviders[t]=new mx({namespace:o});break;case"polkadot":this.rpcProviders[t]=new rx({namespace:o});break;case"cip34":this.rpcProviders[t]=new Ex({namespace:o});break;case"elrond":this.rpcProviders[t]=new _x({namespace:o});break;case"multiversx":this.rpcProviders[t]=new $x({namespace:o});break;case"near":this.rpcProviders[t]=new Mx({namespace:o});break;case"tezos":this.rpcProviders[t]=new Dx({namespace:o});break;default:this.rpcProviders[yn]?this.rpcProviders[yn].updateNamespace(o):this.rpcProviders[yn]=new Rx({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:t}=e,{event:i}=t;if(i.name==="accountsChanged"){const r=i.data;r&&vr(r)&&this.events.emit("accountsChanged",r.map(tx))}else if(i.name==="chainChanged"){const r=t.chainId,n=t.event.data,o=Po(r),a=Ml(r)!==Ml(n)?`${o}:${Ml(n)}`:r;this.onChainChanged(a)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i;const{namespaces:r}=t,n=(i=this.client)==null?void 0:i.session.get(e);this.session=xl(Ua({},n),{namespaces:r}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",xl(Ua({},Te("USER_DISCONNECTED")),{data:e.topic}))}),this.on(Ts.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[yn]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t,optionalNamespaces:i,sessionProperties:r}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=r,this.persist("namespaces",t),this.persist("optionalNamespaces",i)}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>Po(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const r=Po(Object.keys(this.namespaces)[0]),n=this.rpcProviders[r].getDefaultChain();return[r,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,r]=this.validateChain(e);r&&(t||this.getProvider(i).setDefaultChain(r),this.namespaces[i]?this.namespaces[i].defaultChain=r:this.namespaces[`${i}:${r}`]?this.namespaces[`${i}:${r}`].defaultChain=r:this.namespaces[`${i}:${r}`]={defaultChain:r},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",r))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(e,t){this.client.core.storage.setItem(`${jp}/${e}`,t)}async getFromStore(e){return await this.client.core.storage.getItem(`${jp}/${e}`)}}const Bx=Uu,Iy={caipNetworkIdToNumber(s){return s?Number(s.split(":")[1]):void 0},parseEvmChainId(s){return typeof s=="string"?this.caipNetworkIdToNumber(s):s},getNetworksByNamespace(s,e){return(s==null?void 0:s.filter(t=>t.chainNamespace===e))||[]},getFirstNetworkByNamespace(s,e){return this.getNetworksByNamespace(s,e)[0]}};var Hx=20,Wx=1,Jn=1e6,Vx=1e6,Kx=-7,Gx=21,Yx=!1,va="[big.js] ",xr=va+"Invalid ",el=xr+"decimal places",Qx=xr+"rounding mode",Ey=va+"Division by zero",$e={},ti=void 0,Zx=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Ay(){function s(e){var t=this;if(!(t instanceof s))return e===ti?Ay():new s(e);if(e instanceof s)t.s=e.s,t.e=e.e,t.c=e.c.slice();else{if(typeof e!="string"){if(s.strict===!0&&typeof e!="bigint")throw TypeError(xr+"value");e=e===0&&1/e<0?"-0":String(e)}Jx(t,e)}t.constructor=s}return s.prototype=$e,s.DP=Hx,s.RM=Wx,s.NE=Kx,s.PE=Gx,s.strict=Yx,s.roundDown=0,s.roundHalfUp=1,s.roundHalfEven=2,s.roundUp=3,s}function Jx(s,e){var t,i,r;if(!Zx.test(e))throw Error(xr+"number");for(s.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(t=e.indexOf("."))>-1&&(e=e.replace(".","")),(i=e.search(/e/i))>0?(t<0&&(t=i),t+=+e.slice(i+1),e=e.substring(0,i)):t<0&&(t=e.length),r=e.length,i=0;i<r&&e.charAt(i)=="0";)++i;if(i==r)s.c=[s.e=0];else{for(;r>0&&e.charAt(--r)=="0";);for(s.e=t-i-1,s.c=[],t=0;i<=r;)s.c[t++]=+e.charAt(i++)}return s}function Dr(s,e,t,i){var r=s.c;if(t===ti&&(t=s.constructor.RM),t!==0&&t!==1&&t!==2&&t!==3)throw Error(Qx);if(e<1)i=t===3&&(i||!!r[0])||e===0&&(t===1&&r[0]>=5||t===2&&(r[0]>5||r[0]===5&&(i||r[1]!==ti))),r.length=1,i?(s.e=s.e-e+1,r[0]=1):r[0]=s.e=0;else if(e<r.length){if(i=t===1&&r[e]>=5||t===2&&(r[e]>5||r[e]===5&&(i||r[e+1]!==ti||r[e-1]&1))||t===3&&(i||!!r[0]),r.length=e,i){for(;++r[--e]>9;)if(r[e]=0,e===0){++s.e,r.unshift(1);break}}for(e=r.length;!r[--e];)r.pop()}return s}function kr(s,e,t){var i=s.e,r=s.c.join(""),n=r.length;if(e)r=r.charAt(0)+(n>1?"."+r.slice(1):"")+(i<0?"e":"e+")+i;else if(i<0){for(;++i;)r="0"+r;r="0."+r}else if(i>0)if(++i>n)for(i-=n;i--;)r+="0";else i<n&&(r=r.slice(0,i)+"."+r.slice(i));else n>1&&(r=r.charAt(0)+"."+r.slice(1));return s.s<0&&t?"-"+r:r}$e.abs=function(){var s=new this.constructor(this);return s.s=1,s};$e.cmp=function(s){var e,t=this,i=t.c,r=(s=new t.constructor(s)).c,n=t.s,o=s.s,a=t.e,l=s.e;if(!i[0]||!r[0])return i[0]?n:r[0]?-o:0;if(n!=o)return n;if(e=n<0,a!=l)return a>l^e?1:-1;for(o=(a=i.length)<(l=r.length)?a:l,n=-1;++n<o;)if(i[n]!=r[n])return i[n]>r[n]^e?1:-1;return a==l?0:a>l^e?1:-1};$e.div=function(s){var e=this,t=e.constructor,i=e.c,r=(s=new t(s)).c,n=e.s==s.s?1:-1,o=t.DP;if(o!==~~o||o<0||o>Jn)throw Error(el);if(!r[0])throw Error(Ey);if(!i[0])return s.s=n,s.c=[s.e=0],s;var a,l,c,h,u,d=r.slice(),p=a=r.length,g=i.length,f=i.slice(0,a),y=f.length,w=s,m=w.c=[],b=0,I=o+(w.e=e.e-s.e)+1;for(w.s=n,n=I<0?0:I,d.unshift(0);y++<a;)f.push(0);do{for(c=0;c<10;c++){if(a!=(y=f.length))h=a>y?1:-1;else for(u=-1,h=0;++u<a;)if(r[u]!=f[u]){h=r[u]>f[u]?1:-1;break}if(h<0){for(l=y==a?r:d;y;){if(f[--y]<l[y]){for(u=y;u&&!f[--u];)f[u]=9;--f[u],f[y]+=10}f[y]-=l[y]}for(;!f[0];)f.shift()}else break}m[b++]=h?c:++c,f[0]&&h?f[y]=i[p]||0:f=[i[p]]}while((p++<g||f[0]!==ti)&&n--);return!m[0]&&b!=1&&(m.shift(),w.e--,I--),b>I&&Dr(w,I,t.RM,f[0]!==ti),w};$e.eq=function(s){return this.cmp(s)===0};$e.gt=function(s){return this.cmp(s)>0};$e.gte=function(s){return this.cmp(s)>-1};$e.lt=function(s){return this.cmp(s)<0};$e.lte=function(s){return this.cmp(s)<1};$e.minus=$e.sub=function(s){var e,t,i,r,n=this,o=n.constructor,a=n.s,l=(s=new o(s)).s;if(a!=l)return s.s=-l,n.plus(s);var c=n.c.slice(),h=n.e,u=s.c,d=s.e;if(!c[0]||!u[0])return u[0]?s.s=-l:c[0]?s=new o(n):s.s=1,s;if(a=h-d){for((r=a<0)?(a=-a,i=c):(d=h,i=u),i.reverse(),l=a;l--;)i.push(0);i.reverse()}else for(t=((r=c.length<u.length)?c:u).length,a=l=0;l<t;l++)if(c[l]!=u[l]){r=c[l]<u[l];break}if(r&&(i=c,c=u,u=i,s.s=-s.s),(l=(t=u.length)-(e=c.length))>0)for(;l--;)c[e++]=0;for(l=e;t>a;){if(c[--t]<u[t]){for(e=t;e&&!c[--e];)c[e]=9;--c[e],c[t]+=10}c[t]-=u[t]}for(;c[--l]===0;)c.pop();for(;c[0]===0;)c.shift(),--d;return c[0]||(s.s=1,c=[d=0]),s.c=c,s.e=d,s};$e.mod=function(s){var e,t=this,i=t.constructor,r=t.s,n=(s=new i(s)).s;if(!s.c[0])throw Error(Ey);return t.s=s.s=1,e=s.cmp(t)==1,t.s=r,s.s=n,e?new i(t):(r=i.DP,n=i.RM,i.DP=i.RM=0,t=t.div(s),i.DP=r,i.RM=n,this.minus(t.times(s)))};$e.neg=function(){var s=new this.constructor(this);return s.s=-s.s,s};$e.plus=$e.add=function(s){var e,t,i,r=this,n=r.constructor;if(s=new n(s),r.s!=s.s)return s.s=-s.s,r.minus(s);var o=r.e,a=r.c,l=s.e,c=s.c;if(!a[0]||!c[0])return c[0]||(a[0]?s=new n(r):s.s=r.s),s;if(a=a.slice(),e=o-l){for(e>0?(l=o,i=c):(e=-e,i=a),i.reverse();e--;)i.push(0);i.reverse()}for(a.length-c.length<0&&(i=c,c=a,a=i),e=c.length,t=0;e;a[e]%=10)t=(a[--e]=a[e]+c[e]+t)/10|0;for(t&&(a.unshift(t),++l),e=a.length;a[--e]===0;)a.pop();return s.c=a,s.e=l,s};$e.pow=function(s){var e=this,t=new e.constructor("1"),i=t,r=s<0;if(s!==~~s||s<-1e6||s>Vx)throw Error(xr+"exponent");for(r&&(s=-s);s&1&&(i=i.times(e)),s>>=1,!!s;)e=e.times(e);return r?t.div(i):i};$e.prec=function(s,e){if(s!==~~s||s<1||s>Jn)throw Error(xr+"precision");return Dr(new this.constructor(this),s,e)};$e.round=function(s,e){if(s===ti)s=0;else if(s!==~~s||s<-1e6||s>Jn)throw Error(el);return Dr(new this.constructor(this),s+this.e+1,e)};$e.sqrt=function(){var s,e,t,i=this,r=i.constructor,n=i.s,o=i.e,a=new r("0.5");if(!i.c[0])return new r(i);if(n<0)throw Error(va+"No square root");n=Math.sqrt(+kr(i,!0,!0)),n===0||n===1/0?(e=i.c.join(""),e.length+o&1||(e+="0"),n=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),s=new r((n==1/0?"5e":(n=n.toExponential()).slice(0,n.indexOf("e")+1))+o)):s=new r(n+""),o=s.e+(r.DP+=4);do t=s,s=a.times(t.plus(i.div(t)));while(t.c.slice(0,o).join("")!==s.c.slice(0,o).join(""));return Dr(s,(r.DP-=4)+s.e+1,r.RM)};$e.times=$e.mul=function(s){var e,t=this,i=t.constructor,r=t.c,n=(s=new i(s)).c,o=r.length,a=n.length,l=t.e,c=s.e;if(s.s=t.s==s.s?1:-1,!r[0]||!n[0])return s.c=[s.e=0],s;for(s.e=l+c,o<a&&(e=r,r=n,n=e,c=o,o=a,a=c),e=new Array(c=o+a);c--;)e[c]=0;for(l=a;l--;){for(a=0,c=o+l;c>l;)a=e[c]+n[l]*r[c-l-1]+a,e[c--]=a%10,a=a/10|0;e[c]=a}for(a?++s.e:e.shift(),l=e.length;!e[--l];)e.pop();return s.c=e,s};$e.toExponential=function(s,e){var t=this,i=t.c[0];if(s!==ti){if(s!==~~s||s<0||s>Jn)throw Error(el);for(t=Dr(new t.constructor(t),++s,e);t.c.length<s;)t.c.push(0)}return kr(t,!0,!!i)};$e.toFixed=function(s,e){var t=this,i=t.c[0];if(s!==ti){if(s!==~~s||s<0||s>Jn)throw Error(el);for(t=Dr(new t.constructor(t),s+t.e+1,e),s=s+t.e+1;t.c.length<s;)t.c.push(0)}return kr(t,!1,!!i)};$e[Symbol.for("nodejs.util.inspect.custom")]=$e.toJSON=$e.toString=function(){var s=this,e=s.constructor;return kr(s,s.e<=e.NE||s.e>=e.PE,!!s.c[0])};$e.toNumber=function(){var s=+kr(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(s.toString()))throw Error(va+"Imprecise conversion");return s};$e.toPrecision=function(s,e){var t=this,i=t.constructor,r=t.c[0];if(s!==ti){if(s!==~~s||s<1||s>Jn)throw Error(xr+"precision");for(t=Dr(new i(t),s,e);t.c.length<s;)t.c.push(0)}return kr(t,s<=t.e||t.e<=i.NE||t.e>=i.PE,!!r)};$e.valueOf=function(){var s=this,e=s.constructor;if(e.strict===!0)throw Error(va+"valueOf disallowed");return kr(s,s.e<=e.NE||s.e>=e.PE,!0)};var fo=Ay();const za={bigNumber(s){return s?new fo(s):new fo(0)},multiply(s,e){if(s===void 0||e===void 0)return new fo(0);const t=new fo(s),i=new fo(e);return t.times(i)},formatNumberToLocalString(s,e=2){return s===void 0?"0.00":typeof s=="number"?s.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(s).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(s){return s===void 0?0:parseFloat(s.replace(/,/gu,""))}},Xx=[{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"}]}],eD=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],tD=[{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"}]}],Q={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"},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"},sD={getERC20Abi:s=>Q.USDT_CONTRACT_ADDRESSES.includes(s)?tD:Xx,getSwapAbi:()=>eD},Ii={validateCaipAddress(s){var e;if(((e=s.split(":"))==null?void 0:e.length)!==3)throw new Error("Invalid CAIP Address");return s},parseCaipAddress(s){const e=s.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${s}`);const[t,i,r]=e;if(!t||!i||!r)throw new Error(`Invalid CAIP-10 address: ${s}`);return{chainNamespace:t,chainId:i,address:r}},parseCaipNetworkId(s){const e=s.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${s}`);const[t,i]=e;if(!t||!i)throw new Error(`Invalid CAIP-2 network id: ${s}`);return{chainNamespace:t,chainId:i}}},re={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"};function Dl(s){if(!s)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${s}:connected_connector_id`}const ee={setItem(s,e){To()&&e!==void 0&&localStorage.setItem(s,e)},getItem(s){if(To())return localStorage.getItem(s)||void 0},removeItem(s){To()&&localStorage.removeItem(s)},clear(){To()&&localStorage.clear()}};function To(){return typeof window<"u"&&typeof localStorage<"u"}function Ri(s,e){return e==="light"?{"--w3m-accent":(s==null?void 0:s["--w3m-accent"])||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":(s==null?void 0:s["--w3m-accent"])||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const iD=Symbol(),lg=Object.getPrototypeOf,qh=new WeakMap,rD=s=>s&&(qh.has(s)?qh.get(s):lg(s)===Object.prototype||lg(s)===Array.prototype),nD=s=>rD(s)&&s[iD]||null,hg=(s,e=!0)=>{qh.set(s,e)},$c={},kl=s=>typeof s=="object"&&s!==null,$i=new WeakMap,Mo=new WeakSet,oD=(s=Object.is,e=(c,h)=>new Proxy(c,h),t=c=>kl(c)&&!Mo.has(c)&&(Array.isArray(c)||!(Symbol.iterator in c))&&!(c instanceof WeakMap)&&!(c instanceof WeakSet)&&!(c instanceof Error)&&!(c instanceof Number)&&!(c instanceof Date)&&!(c instanceof String)&&!(c instanceof RegExp)&&!(c instanceof ArrayBuffer),i=c=>{switch(c.status){case"fulfilled":return c.value;case"rejected":throw c.reason;default:throw c}},r=new WeakMap,n=(c,h,u=i)=>{const d=r.get(c);if((d==null?void 0:d[0])===h)return d[1];const p=Array.isArray(c)?[]:Object.create(Object.getPrototypeOf(c));return hg(p,!0),r.set(c,[h,p]),Reflect.ownKeys(c).forEach(g=>{if(Object.getOwnPropertyDescriptor(p,g))return;const f=Reflect.get(c,g),{enumerable:y}=Reflect.getOwnPropertyDescriptor(c,g),w={value:f,enumerable:y,configurable:!0};if(Mo.has(f))hg(f,!1);else if(f instanceof Promise)delete w.value,w.get=()=>u(f);else if($i.has(f)){const[m,b]=$i.get(f);w.value=n(m,b(),u)}Object.defineProperty(p,g,w)}),Object.preventExtensions(p)},o=new WeakMap,a=[1,1],l=c=>{if(!kl(c))throw new Error("object required");const h=o.get(c);if(h)return h;let u=a[0];const d=new Set,p=(C,T=++a[0])=>{u!==T&&(u=T,d.forEach(S=>S(C,T)))};let g=a[1];const f=(C=++a[1])=>(g!==C&&!d.size&&(g=C,w.forEach(([T])=>{const S=T[1](C);S>u&&(u=S)})),u),y=C=>(T,S)=>{const R=[...T];R[1]=[C,...R[1]],p(R,S)},w=new Map,m=(C,T)=>{if(($c?"production":void 0)!=="production"&&w.has(C))throw new Error("prop listener already exists");if(d.size){const S=T[3](y(C));w.set(C,[T,S])}else w.set(C,[T])},b=C=>{var T;const S=w.get(C);S&&(w.delete(C),(T=S[1])==null||T.call(S))},I=C=>(d.add(C),d.size===1&&w.forEach(([S,R],L)=>{if(($c?"production":void 0)!=="production"&&R)throw new Error("remove already exists");const q=S[3](y(L));w.set(L,[S,q])}),()=>{d.delete(C),d.size===0&&w.forEach(([S,R],L)=>{R&&(R(),w.set(L,[S]))})}),N=Array.isArray(c)?[]:Object.create(Object.getPrototypeOf(c)),P=e(N,{deleteProperty(C,T){const S=Reflect.get(C,T);b(T);const R=Reflect.deleteProperty(C,T);return R&&p(["delete",[T],S]),R},set(C,T,S,R){const L=Reflect.has(C,T),q=Reflect.get(C,T,R);if(L&&(s(q,S)||o.has(S)&&s(q,o.get(S))))return!0;b(T),kl(S)&&(S=nD(S)||S);let B=S;if(S instanceof Promise)S.then(U=>{S.status="fulfilled",S.value=U,p(["resolve",[T],U])}).catch(U=>{S.status="rejected",S.reason=U,p(["reject",[T],U])});else{!$i.has(S)&&t(S)&&(B=l(S));const U=!Mo.has(B)&&$i.get(B);U&&m(T,U)}return Reflect.set(C,T,B,R),p(["set",[T],S,q]),!0}});o.set(c,P);const O=[N,f,n,I];return $i.set(P,O),Reflect.ownKeys(c).forEach(C=>{const T=Object.getOwnPropertyDescriptor(c,C);"value"in T&&(P[C]=c[C],delete T.value,delete T.writable),Object.defineProperty(N,C,T)}),P})=>[l,$i,Mo,s,e,t,i,r,n,o,a],[aD]=oD();function Xe(s={}){return aD(s)}function Yt(s,e,t){const i=$i.get(s);($c?"production":void 0)!=="production"&&!i&&console.warn("Please use proxy object");let r;const n=[],o=i[3];let a=!1;const c=o(h=>{n.push(h),r||(r=Promise.resolve().then(()=>{r=void 0,a&&e(n.splice(0))}))});return a=!0,()=>{a=!1,c()}}function Xo(s,e){const t=$i.get(s);($c?"production":void 0)!=="production"&&!t&&console.warn("Please use proxy object");const[i,r,n]=t;return n(i,r(),e)}function Ir(s){return Mo.add(s),s}function vs(s,e,t,i){let r=s[e];return Yt(s,()=>{const n=s[e];Object.is(r,n)||t(r=n)})}function cD(s){const e=Xe({data:Array.from([]),has(t){return this.data.some(i=>i[0]===t)},set(t,i){const r=this.data.find(n=>n[0]===t);return r?r[1]=i:this.data.push([t,i]),this},get(t){var i;return(i=this.data.find(r=>r[0]===t))==null?void 0:i[1]},delete(t){const i=this.data.findIndex(r=>r[0]===t);return i===-1?!1:(this.data.splice(i,1),!0)},clear(){this.data.splice(0)},get size(){return this.data.length},toJSON(){return new Map(this.data)},forEach(t){this.data.forEach(i=>{t(i[1],i[0],this)})},keys(){return this.data.map(t=>t[0]).values()},values(){return this.data.map(t=>t[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 ug={};const jl=(typeof _.process<"u"&&typeof ug<"u"?ug.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",os={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:jl,SECURE_SITE_DASHBOARD:`${jl}/dashboard`,SECURE_SITE_FAVICON:`${jl}/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","solana"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in a new browser tab"},DEFAULT_FEATURES:{swaps:!0,onramp:!0,receive:!0,send:!0,email:!0,emailShowWallets:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],history:!0,analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0},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"}},G={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(s,e){return Date.now()-s>e},getActiveNetworkProps(){const s=G.getActiveNamespace(),e=G.getActiveCaipNetworkId(),t=e?e.split(":")[1]:void 0,i=t?isNaN(Number(t))?t:Number(t):void 0;return{namespace:s,caipNetworkId:e,chainId:i}},setWalletConnectDeepLink({name:s,href:e}){try{ee.setItem(re.DEEPLINK_CHOICE,JSON.stringify({href:e,name:s}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const s=ee.getItem(re.DEEPLINK_CHOICE);if(s)return JSON.parse(s)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{ee.removeItem(re.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(s){try{ee.setItem(re.ACTIVE_NAMESPACE,s)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(s){try{ee.setItem(re.ACTIVE_CAIP_NETWORK_ID,s),G.setActiveNamespace(s.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return ee.getItem(re.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{ee.removeItem(re.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(s){try{const e=Dl(s);ee.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(s){try{const e=G.getRecentWallets();e.find(i=>i.id===s.id)||(e.unshift(s),e.length>2&&e.pop(),ee.setItem(re.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const s=ee.getItem(re.RECENT_WALLETS);return s?JSON.parse(s):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(s,e){try{const t=Dl(s);ee.setItem(t,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return ee.getItem(re.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(s){if(s)try{const e=Dl(s);return ee.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",s)}},setConnectedSocialProvider(s){try{ee.setItem(re.CONNECTED_SOCIAL,s)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return ee.getItem(re.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{ee.removeItem(re.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return ee.getItem(re.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var t;const s=ee.getItem(re.ACTIVE_CAIP_NETWORK_ID);return(t=s==null?void 0:s.split(":"))==null?void 0:t[1]},setConnectionStatus(s){try{ee.setItem(re.CONNECTION_STATUS,s)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return ee.getItem(re.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const s=ee.getItem(re.CONNECTED_NAMESPACES);return s!=null&&s.length?s.split(","):[]}catch{return[]}},setConnectedNamespaces(s){try{const e=Array.from(new Set(s));ee.setItem(re.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(s){try{const e=G.getConnectedNamespaces();e.includes(s)||(e.push(s),G.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(s){try{const e=G.getConnectedNamespaces(),t=e.indexOf(s);t>-1&&(e.splice(t,1),G.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return ee.getItem(re.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(s){try{ee.setItem(re.TELEGRAM_SOCIAL_PROVIDER,s)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{ee.removeItem(re.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let s={};try{const e=ee.getItem(re.PORTFOLIO_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return s},removeAddressFromBalanceCache(s){try{const e=G.getBalanceCache();ee.setItem(re.PORTFOLIO_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove address from balance cache",s)}},getBalanceCacheForCaipAddress(s){try{const t=G.getBalanceCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;G.removeAddressFromBalanceCache(s)}catch{console.info("Unable to get balance cache for address",s)}},updateBalanceCache(s){try{const e=G.getBalanceCache();e[s.caipAddress]=s,ee.setItem(re.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",s)}},getNativeBalanceCache(){let s={};try{const e=ee.getItem(re.NATIVE_BALANCE_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return s},removeAddressFromNativeBalanceCache(s){try{const e=G.getBalanceCache();ee.setItem(re.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove address from balance cache",s)}},getNativeBalanceCacheForCaipAddress(s){try{const t=G.getNativeBalanceCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",s),G.removeAddressFromBalanceCache(s)}catch{console.info("Unable to get balance cache for address",s)}},updateNativeBalanceCache(s){try{const e=G.getNativeBalanceCache();e[s.caipAddress]=s,ee.setItem(re.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",s)}},getEnsCache(){let s={};try{const e=ee.getItem(re.ENS_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return s},getEnsFromCacheForAddress(s){try{const t=G.getEnsCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;G.removeEnsFromCache(s)}catch{console.info("Unable to get ens name from cache",s)}},updateEnsCache(s){try{const e=G.getEnsCache();e[s.address]=s,ee.setItem(re.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",s)}},removeEnsFromCache(s){try{const e=G.getEnsCache();ee.setItem(re.ENS_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove ens name from cache",s)}},getIdentityCache(){let s={};try{const e=ee.getItem(re.IDENTITY_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return s},getIdentityFromCacheForAddress(s){try{const t=G.getIdentityCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;G.removeIdentityFromCache(s)}catch{console.info("Unable to get identity from cache",s)}},updateIdentityCache(s){try{const e=G.getIdentityCache();e[s.address]={identity:s.identity,timestamp:s.timestamp},ee.setItem(re.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",s)}},removeIdentityFromCache(s){try{const e=G.getIdentityCache();ee.setItem(re.IDENTITY_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove identity from cache",s)}},clearAddressCache(){try{ee.removeItem(re.PORTFOLIO_CACHE),ee.removeItem(re.NATIVE_BALANCE_CACHE),ee.removeItem(re.ENS_CACHE),ee.removeItem(re.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}}},se={isMobile(){var s;return this.isClient()?!!((s=window==null?void 0:window.matchMedia("(pointer:coarse)"))!=null&&s.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(s,e=""){return s==null?void 0:s.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const s=window==null?void 0:window.navigator.userAgent.toLowerCase();return se.isMobile()&&s.includes("android")},isIos(){if(!this.isMobile())return!1;const s=window==null?void 0:window.navigator.userAgent.toLowerCase();return s.includes("iphone")||s.includes("ipad")},isSafari(){return this.isClient()?(window==null?void 0:window.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(s){return s?s-Date.now()<=os.TEN_SEC_MS:!0},isAllowedRetry(s,e=os.ONE_SEC_MS){return Date.now()-s>=e},copyToClopboard(s){navigator.clipboard.writeText(s)},isIframe(){try{return(window==null?void 0:window.self)!==(window==null?void 0:window.top)}catch{return!1}},getPairingExpiry(){return Date.now()+os.FOUR_MINUTES_MS},getNetworkId(s){return s==null?void 0:s.split(":")[1]},getPlainAddress(s){return s==null?void 0:s.split(":")[2]},async wait(s){return new Promise(e=>{setTimeout(e,s)})},debounce(s,e=500){let t;return(...i)=>{function r(){s(...i)}t&&clearTimeout(t),t=setTimeout(r,e)}},isHttpUrl(s){return s.startsWith("http://")||s.startsWith("https://")},formatNativeUrl(s,e){if(se.isHttpUrl(s))return this.formatUniversalUrl(s,e);let t=s;t.includes("://")||(t=s.replaceAll("/","").replaceAll(":",""),t=`${t}://`),t.endsWith("/")||(t=`${t}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const i=encodeURIComponent(e);return{redirect:`${t}wc?uri=${i}`,href:t}},formatUniversalUrl(s,e){if(!se.isHttpUrl(s))return this.formatNativeUrl(s,e);let t=s;t.endsWith("/")||(t=`${t}/`);const i=encodeURIComponent(e);return{redirect:`${t}wc?uri=${i}`,href:t}},getOpenTargetForPlatform(s){return s==="popupWindow"?s:this.isTelegram()?G.getTelegramSocialProvider()?"_top":"_blank":s},openHref(s,e,t){window==null||window.open(s,this.getOpenTargetForPlatform(e),t||"noreferrer noopener")},returnOpenHref(s,e,t){return window==null?void 0:window.open(s,this.getOpenTargetForPlatform(e),t||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},async preloadImage(s){const e=new Promise((t,i)=>{const r=new Image;r.onload=t,r.onerror=i,r.crossOrigin="anonymous",r.src=s});return Promise.race([e,se.wait(2e3)])},formatBalance(s,e){let t="0.000";if(typeof s=="string"){const i=Number(s);if(i){const r=Math.floor(i*1e3)/1e3;r&&(t=r.toString())}}return`${t}${e?` ${e}`:""}`},formatBalance2(s,e){var i;let t;if(s==="0")t="0";else if(typeof s=="string"){const r=Number(s);r&&(t=(i=r.toString().match(/^-?\d+(?:\.\d{0,3})?/u))==null?void 0:i[0])}return{value:t??"0",rest:t==="0"?"000":"",symbol:e}},getApiUrl(){return Q.W3M_API_URL},getBlockchainApiUrl(){return Q.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return Q.PULSE_API_URL},getUUID(){return crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})},parseError(s){var e,t;return typeof s=="string"?s:typeof((t=(e=s==null?void 0:s.issues)==null?void 0:e[0])==null?void 0:t.message)=="string"?s.issues[0].message:s instanceof Error?s.message:"Unknown error"},sortRequestedNetworks(s,e=[]){const t={};return e&&s&&(s.forEach((i,r)=>{t[i]=r}),e.sort((i,r)=>{const n=t[i.id],o=t[r.id];return n!==void 0&&o!==void 0?n-o:n!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(s){let e=0;for(const t of s)e+=t.value??0;return e},formatTokenBalance(s){const e=s.toFixed(2),[t,i]=e.split(".");return{dollars:t,pennies:i}},isAddress(s,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(s)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(s)||/^(?:0x)?[0-9A-F]{40}$/iu.test(s))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(s);default:return!1}},uniqueBy(s,e){const t=new Set;return s.filter(i=>{const r=i[e];return t.has(r)?!1:(t.add(r),!0)})},generateSdkVersion(s,e,t){const r=s.length===0?os.ADAPTER_TYPES.UNIVERSAL:s.map(n=>n.adapterType).join(",");return`${e}-${r}-${t}`},createAccount(s,e,t,i,r){return{namespace:s,address:e,type:t,publicKey:i,path:r}},isCaipAddress(s){if(typeof s!="string")return!1;const e=s.split(":"),t=e[0];return e.filter(Boolean).length===3&&t in Q.CHAIN_NAME_MAP},isMac(){const s=window==null?void 0:window.navigator.userAgent.toLowerCase();return s.includes("macintosh")&&!s.includes("safari")},formatTelegramSocialLoginUrl(s){const e=`--${encodeURIComponent(window==null?void 0:window.location.href)}`,t="state=";if(new URL(s).host==="auth.magic.link"){const r="provider_authorization_url=",n=s.substring(s.indexOf(r)+r.length),o=this.injectIntoUrl(decodeURIComponent(n),t,e);return s.replace(n,encodeURIComponent(o))}return this.injectIntoUrl(s,t,e)},injectIntoUrl(s,e,t){const i=s.indexOf(e);if(i===-1)throw new Error(`${e} parameter not found in the URL: ${s}`);const r=s.indexOf("&",i),n=e.length,o=r!==-1?r:s.length,a=s.substring(0,i+n),l=s.substring(i+n,o),c=s.substring(r),h=l+t;return a+h+c}};async function mo(...s){const e=await fetch(...s);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class tl{constructor({baseUrl:e,clientId:t}){this.baseUrl=e,this.clientId=t}async get({headers:e,signal:t,cache:i,...r}){const n=this.createUrl(r);return(await mo(n,{method:"GET",headers:e,signal:t,cache:i})).json()}async getBlob({headers:e,signal:t,...i}){const r=this.createUrl(i);return(await mo(r,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await mo(n,{method:"POST",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}async put({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await mo(n,{method:"PUT",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}async delete({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await mo(n,{method:"DELETE",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}createUrl({path:e,params:t}){const i=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([r,n])=>{n&&i.searchParams.append(r,n)}),this.clientId&&i.searchParams.append("clientId",this.clientId),i}}const lD={handleSolanaDeeplinkRedirect(s){if(v.state.activeChain===Q.CHAIN.SOLANA){const e=window.location.href,t=encodeURIComponent(e);if(s==="Phantom"&&!("phantom"in window)){const i=e.startsWith("https")?"https":"http",r=e.split("/")[2],n=encodeURIComponent(`${i}://${r}`);window.location.href=`https://phantom.app/ul/browse/${t}?ref=${n}`}s==="Coinbase Wallet"&&!("coinbaseSolana"in window)&&(window.location.href=`https://go.cb-w.com/dapp?cb_url=${t}`)}}},as=Xe({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Fs={state:as,subscribeNetworkImages(s){return Yt(as.networkImages,()=>s(as.networkImages))},subscribeKey(s,e){return vs(as,s,e)},subscribe(s){return Yt(as,()=>s(as))},setWalletImage(s,e){as.walletImages[s]=e},setNetworkImage(s,e){as.networkImages[s]=e},setChainImage(s,e){as.chainImages[s]=e},setConnectorImage(s,e){as.connectorImages={...as.connectorImages,[s]:e}},setTokenImage(s,e){as.tokenImages[s]=e},setCurrencyImage(s,e){as.currencyImages[s]=e}},hD={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},Rl=Xe({networkImagePromises:{}}),Ny={async fetchWalletImage(s){if(s)return await ie._fetchWalletImage(s),this.getWalletImageById(s)},async fetchNetworkImage(s){if(!s)return;const e=this.getNetworkImageById(s);return e||(Rl.networkImagePromises[s]||(Rl.networkImagePromises[s]=ie._fetchNetworkImage(s)),await Rl.networkImagePromises[s],this.getNetworkImageById(s))},getWalletImageById(s){if(s)return Fs.state.walletImages[s]},getWalletImage(s){if(s!=null&&s.image_url)return s==null?void 0:s.image_url;if(s!=null&&s.image_id)return Fs.state.walletImages[s.image_id]},getNetworkImage(s){var e,t,i;if((e=s==null?void 0:s.assets)!=null&&e.imageUrl)return(t=s==null?void 0:s.assets)==null?void 0:t.imageUrl;if((i=s==null?void 0:s.assets)!=null&&i.imageId)return Fs.state.networkImages[s.assets.imageId]},getNetworkImageById(s){if(s)return Fs.state.networkImages[s]},getConnectorImage(s){if(s!=null&&s.imageUrl)return s.imageUrl;if(s!=null&&s.imageId)return Fs.state.connectorImages[s.imageId]},getChainImage(s){return Fs.state.networkImages[hD[s]]}},uD={getFeatureValue(s,e){const t=e==null?void 0:e[s];return t===void 0?os.DEFAULT_FEATURES[s]:t},filterSocialsByPlatform(s){if(!s||!s.length)return s;if(se.isTelegram()){if(se.isIos())return s.filter(e=>e!=="google");if(se.isMac())return s.filter(e=>e!=="x");if(se.isAndroid())return s.filter(e=>!["facebook","x"].includes(e))}return s}},J=Xe({features:os.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:os.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0}),D={state:J,subscribeKey(s,e){return vs(J,s,e)},setOptions(s){Object.assign(J,s)},setFeatures(s){if(!s)return;J.features||(J.features=os.DEFAULT_FEATURES);const e={...J.features,...s};J.features=e,J.features.socials&&(J.features.socials=uD.filterSocialsByPlatform(J.features.socials))},setProjectId(s){J.projectId=s},setCustomRpcUrls(s){J.customRpcUrls=s},setAllWallets(s){J.allWallets=s},setIncludeWalletIds(s){J.includeWalletIds=s},setExcludeWalletIds(s){J.excludeWalletIds=s},setFeaturedWalletIds(s){J.featuredWalletIds=s},setTokens(s){J.tokens=s},setTermsConditionsUrl(s){J.termsConditionsUrl=s},setPrivacyPolicyUrl(s){J.privacyPolicyUrl=s},setCustomWallets(s){J.customWallets=s},setIsSiweEnabled(s){J.isSiweEnabled=s},setIsUniversalProvider(s){J.isUniversalProvider=s},setSdkVersion(s){J.sdkVersion=s},setMetadata(s){J.metadata=s},setDisableAppend(s){J.disableAppend=s},setEIP6963Enabled(s){J.enableEIP6963=s},setDebug(s){J.debug=s},setEnableWalletConnect(s){J.enableWalletConnect=s},setEnableWalletGuide(s){J.enableWalletGuide=s},setEnableAuthLogger(s){J.enableAuthLogger=s},setEnableWallets(s){J.enableWallets=s},setHasMultipleAddresses(s){J.hasMultipleAddresses=s},setSIWX(s){J.siwx=s},setConnectMethodsOrder(s){J.features={...J.features,connectMethodsOrder:s}},setWalletFeaturesOrder(s){J.features={...J.features,walletFeaturesOrder:s}},setSocialsOrder(s){J.features={...J.features,socials:s}},setCollapseWallets(s){J.features={...J.features,collapseWallets:s}},setEnableEmbedded(s){J.enableEmbedded=s},setAllowUnsupportedChain(s){J.allowUnsupportedChain=s},setManualWCControl(s){J.manualWCControl=s},setEnableNetworkSwitch(s){J.enableNetworkSwitch=s},setDefaultAccountTypes(s={}){Object.entries(s).forEach(([e,t])=>{t&&(J.defaultAccountTypes[e]=t)})},setUniversalProviderConfigOverride(s){J.universalProviderConfigOverride=s},getUniversalProviderConfigOverride(){return J.universalProviderConfigOverride},getSnapshot(){return Xo(J)}},Ei=Xe({message:"",variant:"info",open:!1}),ac={state:Ei,subscribeKey(s,e){return vs(Ei,s,e)},open(s,e){const{debug:t}=D.state,{shortMessage:i,longMessage:r}=s;t&&(Ei.message=i,Ei.variant=e,Ei.open=!0),r&&console.error(typeof r=="function"?r():r)},close(){Ei.open=!1,Ei.message="",Ei.variant="info"}},dD=se.getAnalyticsUrl(),pD=new tl({baseUrl:dD,clientId:null}),gD=["MODAL_CREATED"],oi=Xe({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),ze={state:oi,subscribe(s){return Yt(oi,()=>s(oi))},getSdkProperties(){const{projectId:s,sdkType:e,sdkVersion:t}=D.state;return{projectId:s,st:e,sv:t||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(s){try{const e=Z.state.address;if(gD.includes(s.data.event)||typeof window>"u")return;await pD.post({path:"/e",params:ze.getSdkProperties(),body:{eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:s.timestamp,props:{...s.data,address:e}}}),oi.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===Q.HTTP_STATUS_CODES.FORBIDDEN&&!oi.reportedErrors.FORBIDDEN&&(ac.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${To()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),oi.reportedErrors.FORBIDDEN=!0)}},sendEvent(s){var e;oi.timestamp=Date.now(),oi.data=s,(e=D.state.features)!=null&&e.analytics&&ze._sendAnalyticsEvent(oi)}},fD=se.getApiUrl(),zt=new tl({baseUrl:fD,clientId:null}),mD="40",dg="4",wD=20,_e=Xe({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),ie={state:_e,subscribeKey(s,e){return vs(_e,s,e)},_getSdkProperties(){const{projectId:s,sdkType:e,sdkVersion:t}=D.state;return{projectId:s,st:e||"appkit",sv:t||"html-wagmi-4.2.2"}},_filterOutExtensions(s){return D.state.isUniversalProvider?s.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):s},async _fetchWalletImage(s){const e=`${zt.baseUrl}/getWalletImage/${s}`,t=await zt.getBlob({path:e,params:ie._getSdkProperties()});Fs.setWalletImage(s,URL.createObjectURL(t))},async _fetchNetworkImage(s){const e=`${zt.baseUrl}/public/getAssetImage/${s}`,t=await zt.getBlob({path:e,params:ie._getSdkProperties()});Fs.setNetworkImage(s,URL.createObjectURL(t))},async _fetchConnectorImage(s){const e=`${zt.baseUrl}/public/getAssetImage/${s}`,t=await zt.getBlob({path:e,params:ie._getSdkProperties()});Fs.setConnectorImage(s,URL.createObjectURL(t))},async _fetchCurrencyImage(s){const e=`${zt.baseUrl}/public/getCurrencyImage/${s}`,t=await zt.getBlob({path:e,params:ie._getSdkProperties()});Fs.setCurrencyImage(s,URL.createObjectURL(t))},async _fetchTokenImage(s){const e=`${zt.baseUrl}/public/getTokenImage/${s}`,t=await zt.getBlob({path:e,params:ie._getSdkProperties()});Fs.setTokenImage(s,URL.createObjectURL(t))},async fetchNetworkImages(){const s=v.getAllRequestedCaipNetworks(),e=s==null?void 0:s.map(({assets:t})=>t==null?void 0:t.imageId).filter(Boolean).filter(t=>!Ny.getNetworkImageById(t));e&&await Promise.allSettled(e.map(t=>ie._fetchNetworkImage(t)))},async fetchConnectorImages(){const{connectors:s}=te.state,e=s.map(({imageId:t})=>t).filter(Boolean);await Promise.allSettled(e.map(t=>ie._fetchConnectorImage(t)))},async fetchCurrencyImages(s=[]){await Promise.allSettled(s.map(e=>ie._fetchCurrencyImage(e)))},async fetchTokenImages(s=[]){await Promise.allSettled(s.map(e=>ie._fetchTokenImage(e)))},async fetchFeaturedWallets(){const{featuredWalletIds:s}=D.state;if(s!=null&&s.length){const{data:e}=await zt.get({path:"/getWallets",params:{...ie._getSdkProperties(),page:"1",entries:s!=null&&s.length?String(s.length):dg,include:s==null?void 0:s.join(",")}});e.sort((i,r)=>s.indexOf(i.id)-s.indexOf(r.id));const t=e.map(i=>i.image_id).filter(Boolean);await Promise.allSettled(t.map(i=>ie._fetchWalletImage(i))),_e.featured=e,_e.allFeatured=e}},async fetchRecommendedWallets(){try{_e.isFetchingRecommendedWallets=!0;const{includeWalletIds:s,excludeWalletIds:e,featuredWalletIds:t}=D.state,i=[...e??[],...t??[]].filter(Boolean),r=v.getRequestedCaipNetworkIds().join(","),{data:n,count:o}=await zt.get({path:"/getWallets",params:{...ie._getSdkProperties(),page:"1",chains:r,entries:dg,include:s==null?void 0:s.join(","),exclude:i==null?void 0:i.join(",")}}),a=G.getRecentWallets(),l=n.map(h=>h.image_id).filter(Boolean),c=a.map(h=>h.image_id).filter(Boolean);await Promise.allSettled([...l,...c].map(h=>ie._fetchWalletImage(h))),_e.recommended=n,_e.allRecommended=n,_e.count=o??0}catch{}finally{_e.isFetchingRecommendedWallets=!1}},async fetchWallets({page:s}){const{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:i}=D.state,r=v.getRequestedCaipNetworkIds().join(","),n=[..._e.recommended.map(({id:c})=>c),...t??[],...i??[]].filter(Boolean),{data:o,count:a}=await zt.get({path:"/getWallets",params:{...ie._getSdkProperties(),page:String(s),entries:mD,chains:r,include:e==null?void 0:e.join(","),exclude:n.join(",")}}),l=o.slice(0,wD).map(c=>c.image_id).filter(Boolean);await Promise.allSettled(l.map(c=>ie._fetchWalletImage(c))),_e.wallets=se.uniqueBy([..._e.wallets,...ie._filterOutExtensions(o)],"id"),_e.count=a>_e.count?a:_e.count,_e.page=s},async initializeExcludedWallets({ids:s}){const e=v.getRequestedCaipNetworkIds().join(","),{data:t}=await zt.get({path:"/getWallets",params:{...ie._getSdkProperties(),page:"1",entries:String(s.length),chains:e,include:s==null?void 0:s.join(",")}});t&&t.forEach(i=>{i!=null&&i.rdns&&_e.excludedWallets.push({rdns:i.rdns,name:i.name})})},async searchWallet({search:s,badge:e}){const{includeWalletIds:t,excludeWalletIds:i}=D.state;_e.search=[];const r=v.getRequestedCaipNetworkIds().join(","),{data:n}=await zt.get({path:"/getWallets",params:{...ie._getSdkProperties(),page:"1",entries:"100",search:s==null?void 0:s.trim(),badge_type:e,chains:r,include:t==null?void 0:t.join(","),exclude:i==null?void 0:i.join(",")}});ze.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:s??""}});const o=n.map(a=>a.image_id).filter(Boolean);await Promise.allSettled([...o.map(a=>ie._fetchWalletImage(a)),se.wait(300)]),_e.search=ie._filterOutExtensions(n)},initPromise(s,e){const t=_e.promises[s];return t||(_e.promises[s]=e())},prefetch({fetchConnectorImages:s=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:t=!0,fetchNetworkImages:i=!0}={}){const r=[s&&ie.initPromise("connectorImages",ie.fetchConnectorImages),e&&ie.initPromise("featuredWallets",ie.fetchFeaturedWallets),t&&ie.initPromise("recommendedWallets",ie.fetchRecommendedWallets),i&&ie.initPromise("networkImages",ie.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(r)},prefetchAnalyticsConfig(){var s;(s=D.state.features)!=null&&s.analytics&&ie.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:s}=await zt.get({path:"/getAnalyticsConfig",params:ie._getSdkProperties()});D.setFeatures({analytics:s})}catch{D.setFeatures({analytics:!1})}},setFilterByNamespace(s){if(!s){_e.featured=_e.allFeatured,_e.recommended=_e.allRecommended;return}const e=v.getRequestedCaipNetworkIds().join(",");_e.featured=_e.allFeatured.filter(t=>{var i;return(i=t.chains)==null?void 0:i.some(r=>e.includes(r))}),_e.recommended=_e.allRecommended.filter(t=>{var i;return(i=t.chains)==null?void 0:i.some(r=>e.includes(r))})}},ve=Xe({view:"Connect",history:["Connect"],transactionStack:[]}),Se={state:ve,subscribeKey(s,e){return vs(ve,s,e)},pushTransactionStack(s){ve.transactionStack.push(s)},popTransactionStack(s){var t,i;const e=ve.transactionStack.pop();if(e)if(s)this.goBack(),(t=e==null?void 0:e.onCancel)==null||t.call(e);else{if(e.goBack)this.goBack();else if(e.replace){const n=ve.history.indexOf("ConnectingSiwe");n>0?this.goBackToIndex(n-1):(ct.close(),ve.history=[])}else e.view&&this.reset(e.view);(i=e==null?void 0:e.onSuccess)==null||i.call(e)}},push(s,e){s!==ve.view&&(ve.view=s,ve.history.push(s),ve.data=e)},reset(s,e){ve.view=s,ve.history=[s],ve.data=e},replace(s,e){ve.history.at(-1)===s||(ve.view=s,ve.history[ve.history.length-1]=s,ve.data=e)},goBack(){var e;const s=!v.state.activeCaipAddress&&this.state.view==="ConnectingFarcaster";if(ve.history.length>1&&!ve.history.includes("UnsupportedChain")){ve.history.pop();const[t]=ve.history.slice(-1);t&&(ve.view=t)}else ct.close();(e=ve.data)!=null&&e.wallet&&(ve.data.wallet=void 0),setTimeout(()=>{var t,i,r;if(s){Z.setFarcasterUrl(void 0,v.state.activeChain);const n=te.getAuthConnector();(t=n==null?void 0:n.provider)==null||t.reload();const o=Xo(D.state);(r=(i=n==null?void 0:n.provider)==null?void 0:i.syncDappData)==null||r.call(i,{metadata:o.metadata,sdkVersion:o.sdkVersion,projectId:o.projectId,sdkType:o.sdkType})}},100)},goBackToIndex(s){if(ve.history.length>1){ve.history=ve.history.slice(0,s+1);const[e]=ve.history.slice(-1);e&&(ve.view=e)}}},ai=Xe({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Vt={state:ai,subscribe(s){return Yt(ai,()=>s(ai))},setThemeMode(s){ai.themeMode=s;try{const e=te.getAuthConnector();if(e){const t=Vt.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:s,themeVariables:t,w3mThemeVariables:Ri(t,s)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(s){ai.themeVariables={...ai.themeVariables,...s};try{const e=te.getAuthConnector();if(e){const t=Vt.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:Ri(ai.themeVariables,ai.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Xo(ai)}},_y={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0},Ce=Xe({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{..._y}}),te={state:Ce,subscribe(s){return Yt(Ce,()=>{s(Ce)})},subscribeKey(s,e){return vs(Ce,s,e)},initialize(s){s.forEach(e=>{const t=G.getConnectedConnectorId(e);t&&this.setConnectorId(t,e)})},setActiveConnector(s){s&&(Ce.activeConnector=Ir(s))},setConnectors(s){s.filter(t=>!Ce.allConnectors.some(i=>i.id===t.id&&this.getConnectorName(i.name)===this.getConnectorName(t.name)&&i.chain===t.chain)).forEach(t=>{t.type!=="MULTI_CHAIN"&&Ce.allConnectors.push(Ir(t))}),Ce.connectors=this.mergeMultiChainConnectors(Ce.allConnectors)},removeAdapter(s){Ce.allConnectors=Ce.allConnectors.filter(e=>e.chain!==s),Ce.connectors=this.mergeMultiChainConnectors(Ce.allConnectors)},mergeMultiChainConnectors(s){const e=this.generateConnectorMapByName(s),t=[];return e.forEach(i=>{const r=i[0],n=(r==null?void 0:r.id)===Q.CONNECTOR_ID.AUTH;i.length>1&&r?t.push({name:r.name,imageUrl:r.imageUrl,imageId:r.imageId,connectors:[...i],type:n?"AUTH":"MULTI_CHAIN",chain:"eip155",id:(r==null?void 0:r.id)||""}):r&&t.push(r)}),t},generateConnectorMapByName(s){const e=new Map;return s.forEach(t=>{const{name:i}=t,r=this.getConnectorName(i);if(!r)return;const n=e.get(r)||[];n.find(a=>a.chain===t.chain)||n.push(t),e.set(r,n)}),e},getConnectorName(s){return s&&({"Trust Wallet":"Trust"}[s]||s)},getUniqueConnectorsByName(s){const e=[];return s.forEach(t=>{e.find(i=>i.chain===t.chain)||e.push(t)}),e},addConnector(s){var e,t,i;if(s.id===Q.CONNECTOR_ID.AUTH){const r=s,n=Xo(D.state),o=Vt.getSnapshot().themeMode,a=Vt.getSnapshot().themeVariables;(t=(e=r==null?void 0:r.provider)==null?void 0:e.syncDappData)==null||t.call(e,{metadata:n.metadata,sdkVersion:n.sdkVersion,projectId:n.projectId,sdkType:n.sdkType}),(i=r==null?void 0:r.provider)==null||i.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:Ri(a,o)}),this.setConnectors([s])}else this.setConnectors([s])},getAuthConnector(s){var i;const e=s||v.state.activeChain,t=Ce.connectors.find(r=>r.id===Q.CONNECTOR_ID.AUTH);if(t)return(i=t==null?void 0:t.connectors)!=null&&i.length?t.connectors.find(n=>n.chain===e):t},getAnnouncedConnectorRdns(){return Ce.connectors.filter(s=>s.type==="ANNOUNCED").map(s=>{var e;return(e=s.info)==null?void 0:e.rdns})},getConnectorById(s){return Ce.allConnectors.find(e=>e.id===s)},getConnector(s,e){return Ce.allConnectors.filter(i=>i.chain===v.state.activeChain).find(i=>{var r;return i.explorerId===s||((r=i.info)==null?void 0:r.rdns)===e})},syncIfAuthConnector(s){var n,o;if(s.id!=="ID_AUTH")return;const e=s,t=Xo(D.state),i=Vt.getSnapshot().themeMode,r=Vt.getSnapshot().themeVariables;(o=(n=e==null?void 0:e.provider)==null?void 0:n.syncDappData)==null||o.call(n,{metadata:t.metadata,sdkVersion:t.sdkVersion,sdkType:t.sdkType,projectId:t.projectId}),e.provider.syncTheme({themeMode:i,themeVariables:r,w3mThemeVariables:Ri(r,i)})},getConnectorsByNamespace(s){const e=Ce.allConnectors.filter(t=>t.chain===s);return this.mergeMultiChainConnectors(e)},selectWalletConnector(s){const e=te.getConnector(s.id,s.rdns);v.state.activeChain===Q.CHAIN.SOLANA&&lD.handleSolanaDeeplinkRedirect((e==null?void 0:e.name)||s.name||""),e?Se.push("ConnectingExternal",{connector:e}):Se.push("ConnectingWalletConnect",{wallet:s})},getConnectors(s){return s?this.getConnectorsByNamespace(s):this.mergeMultiChainConnectors(Ce.allConnectors)},setFilterByNamespace(s){Ce.filterByNamespace=s,Ce.connectors=this.getConnectors(s),ie.setFilterByNamespace(s)},setConnectorId(s,e){s&&(Ce.activeConnectorIds={...Ce.activeConnectorIds,[e]:s},G.setConnectedConnectorId(e,s))},removeConnectorId(s){Ce.activeConnectorIds={...Ce.activeConnectorIds,[s]:void 0},G.deleteConnectedConnectorId(s)},getConnectorId(s){if(s)return Ce.activeConnectorIds[s]},isConnected(s){return s?!!Ce.activeConnectorIds[s]:Object.values(Ce.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){Ce.activeConnectorIds={..._y}}};function Fa(s,e){return te.getConnectorId(s)===e}function yD(s){const e=Array.from(v.state.chains.keys());let t=[];return s?(t.push([s,v.state.chains.get(s)]),Fa(s,Q.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(i=>{i!==s&&Fa(i,Q.CONNECTOR_ID.WALLET_CONNECT)&&t.push([i,v.state.chains.get(i)])}):Fa(s,Q.CONNECTOR_ID.AUTH)&&e.forEach(i=>{i!==s&&Fa(i,Q.CONNECTOR_ID.AUTH)&&t.push([i,v.state.chains.get(i)])})):t=Array.from(v.state.chains.entries()),t}var bD=Object.defineProperty,vD=(s,e,t)=>e in s?bD(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,pg=(s,e,t)=>vD(s,typeof e!="symbol"?e+"":e,t);let ID=class extends bs{constructor(e){super(),this.opts=e,pg(this,"protocol","wc"),pg(this,"version",2)}};var ED=Object.defineProperty,AD=(s,e,t)=>e in s?ED(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ND=(s,e,t)=>AD(s,e+"",t);let _D=class extends bs{constructor(e,t){super(),this.core=e,this.logger=t,ND(this,"records",new Map)}},CD=class{constructor(e,t){this.logger=e,this.core=t}},SD=class extends bs{constructor(e,t){super(),this.relayer=e,this.logger=t}},$D=class extends bs{constructor(e){super()}},PD=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},TD=class extends bs{constructor(e,t){super(),this.relayer=e,this.logger=t}},MD=class extends bs{constructor(e,t){super(),this.core=e,this.logger=t}},OD=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},xD=class{constructor(e,t){this.projectId=e,this.logger=t}},DD=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};var kD=Object.defineProperty,jD=(s,e,t)=>e in s?kD(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,gg=(s,e,t)=>jD(s,typeof e!="symbol"?e+"":e,t);let RD=class{constructor(e){this.opts=e,gg(this,"protocol","wc"),gg(this,"version",2)}},LD=class{constructor(e){this.client=e}};const Pi={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"}},nr=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),ht=Xe({...nr}),xt={state:ht,subscribeKey(s,e){return vs(ht,s,e)},showLoading(s,e={}){this._showMessage({message:s,variant:"loading",...e})},showSuccess(s){this._showMessage({message:s,variant:"success"})},showSvg(s,e){this._showMessage({message:s,svg:e})},showError(s){const e=se.parseError(s);this._showMessage({message:e,variant:"error"})},hide(){ht.message=nr.message,ht.variant=nr.variant,ht.svg=nr.svg,ht.open=nr.open,ht.autoClose=nr.autoClose},_showMessage({message:s,svg:e,variant:t="success",autoClose:i=nr.autoClose}){ht.open?(ht.open=!1,setTimeout(()=>{ht.message=s,ht.variant=t,ht.svg=e,ht.open=!0,ht.autoClose=i},150)):(ht.message=s,ht.variant=t,ht.svg=e,ht.open=!0,ht.autoClose=i)}},Lo={getSIWX(){return D.state.siwx},async initializeIfEnabled(){var n;const s=D.state.siwx,e=v.getActiveCaipAddress();if(!(s&&e))return;const[t,i,r]=e.split(":");if(v.checkIfSupportedNetwork(t))try{if((await s.getSessions(`${t}:${i}`,r)).length)return;await ct.open({view:"SIWXSignMessage"})}catch(o){console.error("SIWXUtil:initializeIfEnabled",o),ze.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await((n=Ue._getClient())==null?void 0:n.disconnect().catch(console.error)),Se.reset("Connect"),xt.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const s=D.state.siwx,e=se.getPlainAddress(v.getActiveCaipAddress()),t=v.getActiveCaipNetwork(),i=Ue._getClient();if(!s)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!t)throw new Error("No ActiveCaipNetwork or client found");if(!i)throw new Error("No ConnectionController client found");try{const r=await s.createMessage({chainId:t.caipNetworkId,accountAddress:e}),n=r.toString();te.getConnectorId(t.chainNamespace)===Q.CONNECTOR_ID.AUTH&&Se.pushTransactionStack({view:null,goBack:!1,replace:!0});const a=await i.signMessage(n);await s.addSession({data:r,message:n,signature:a}),ct.close(),ze.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){const n=this.getSIWXEventProperties();(!ct.state.open||Se.state.view==="ApproveTransaction")&&await ct.open({view:"SIWXSignMessage"}),n.isSmartAccount?xt.showError("This application might not support Smart Accounts"):xt.showError("Signature declined"),ze.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:n}),console.error("SWIXUtil:requestSignMessage",r)}},async cancelSignMessage(){var s;try{const e=this.getSIWX();((s=e==null?void 0:e.getRequired)==null?void 0:s.call(e))?await Ue.disconnect():ct.close(),Se.reset("Connect"),ze.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getSessions(){const s=D.state.siwx,e=se.getPlainAddress(v.getActiveCaipAddress()),t=v.getActiveCaipNetwork();return s&&e&&t?s.getSessions(t.caipNetworkId,e):[]},async isSIWXCloseDisabled(){var e;const s=this.getSIWX();if(s){const t=Se.state.view==="ApproveTransaction",i=Se.state.view==="SIWXSignMessage";if(t||i)return((e=s.getRequired)==null?void 0:e.call(s))&&(await this.getSessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:s,chains:e,methods:t}){var a,l,c;const i=Lo.getSIWX(),r=new Set(e.map(h=>h.split(":")[0]));if(!i||r.size!==1||!r.has("eip155"))return!1;const n=await i.createMessage({chainId:((a=v.getActiveCaipNetwork())==null?void 0:a.caipNetworkId)||"",accountAddress:""}),o=await s.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:t,chains:[n.chainId,...e.filter(h=>h!==n.chainId)]});if(xt.showLoading("Authenticating...",{autoClose:!1}),Z.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:(l=o.session.peer.metadata.icons)==null?void 0:l[0],type:"WALLET_CONNECT"},Array.from(r)[0]),(c=o==null?void 0:o.auths)!=null&&c.length){const h=o.auths.map(u=>{const d=s.client.formatAuthMessage({request:u.p,iss:u.p.iss});return{data:{...u.p,accountAddress:u.p.iss.split(":").slice(-1).join(""),chainId:u.p.iss.split(":").slice(2,4).join(":"),uri:u.p.aud,version:u.p.version||n.version,expirationTime:u.p.exp,issuedAt:u.p.iat,notBefore:u.p.nbf},message:d,signature:u.s.s,cacao:u}});try{await i.setSessions(h),ze.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:Lo.getSIWXEventProperties()})}catch(u){throw console.error("SIWX:universalProviderAuth - failed to set sessions",u),ze.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:Lo.getSIWXEventProperties()}),await s.disconnect().catch(console.error),u}finally{xt.hide()}}return!0},getSIWXEventProperties(){var s;return{network:((s=v.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||"",isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const s=this.getSIWX();s&&await s.setSessions([])}},je=Xe({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),UD={state:je,subscribe(s){return Yt(je,()=>s(je))},setLastNetworkInView(s){je.lastNetworkInView=s},async fetchTransactions(s,e){var t;if(!s)throw new Error("Transactions can't be fetched without an accountAddress");je.loading=!0;try{const i=await X.fetchTransactions({account:s,cursor:je.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:(t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId}),r=this.filterSpamTransactions(i.data),n=this.filterByConnectedChain(r),o=[...je.transactions,...n];je.loading=!1,e==="coinbase"?je.coinbaseTransactions=this.groupTransactionsByYearAndMonth(je.coinbaseTransactions,i.data):(je.transactions=o,je.transactionsByYear=this.groupTransactionsByYearAndMonth(je.transactionsByYear,n)),je.empty=o.length===0,je.next=i.next?i.next:void 0}catch{ze.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:s,projectId:D.state.projectId,cursor:je.next,isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT}}),xt.showError("Failed to fetch transactions"),je.loading=!1,je.empty=!0,je.next=void 0}},groupTransactionsByYearAndMonth(s={},e=[]){const t=s;return e.forEach(i=>{const r=new Date(i.metadata.minedAt).getFullYear(),n=new Date(i.metadata.minedAt).getMonth(),o=t[r]??{},l=(o[n]??[]).filter(c=>c.id!==i.id);t[r]={...o,[n]:[...l,i].sort((c,h)=>new Date(h.metadata.minedAt).getTime()-new Date(c.metadata.minedAt).getTime())}}),t},filterSpamTransactions(s){return s.filter(e=>!e.transfers.every(i=>{var r;return((r=i.nft_info)==null?void 0:r.flags.is_spam)===!0}))},filterByConnectedChain(s){var i;const e=(i=v.state.activeCaipNetwork)==null?void 0:i.caipNetworkId;return s.filter(r=>r.metadata.chain===e)},clearCursor(){je.next=void 0},resetTransactions(){je.transactions=[],je.transactionsByYear={},je.lastNetworkInView=void 0,je.loading=!1,je.empty=!1,je.next=void 0}},Re=Xe({wcError:!1,buffering:!1,status:"disconnected"});let en;const Ue={state:Re,subscribeKey(s,e){return vs(Re,s,e)},_getClient(){return Re._client},setClient(s){Re._client=Ir(s)},async connectWalletConnect(){var s,e,t,i;if(se.isTelegram()||se.isSafari()&&se.isIos()){if(en){await en,en=void 0;return}if(!se.isPairingExpired(Re==null?void 0:Re.wcPairingExpiry)){const r=Re.wcUri;Re.wcUri=r;return}en=(e=(s=this._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:e.call(s).catch(()=>{}),this.state.status="connecting",await en,en=void 0,Re.wcPairingExpiry=void 0,this.state.status="connected"}else await((i=(t=this._getClient())==null?void 0:t.connectWalletConnect)==null?void 0:i.call(t))},async connectExternal(s,e,t=!0){var i,r;await((r=(i=this._getClient())==null?void 0:i.connectExternal)==null?void 0:r.call(i,s)),t&&v.setActiveNamespace(e)},async reconnectExternal(s){var t,i;await((i=(t=this._getClient())==null?void 0:t.reconnectExternal)==null?void 0:i.call(t,s));const e=s.chain||v.state.activeChain;e&&te.setConnectorId(s.id,e)},async setPreferredAccountType(s){var t;ct.setLoading(!0,v.state.activeChain);const e=te.getAuthConnector();e&&(await(e==null?void 0:e.provider.setPreferredAccount(s)),await this.reconnectExternal(e),ct.setLoading(!1,v.state.activeChain),ze.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:s,network:((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)||""}}))},async signMessage(s){var e;return(e=this._getClient())==null?void 0:e.signMessage(s)},parseUnits(s,e){var t;return(t=this._getClient())==null?void 0:t.parseUnits(s,e)},formatUnits(s,e){var t;return(t=this._getClient())==null?void 0:t.formatUnits(s,e)},async sendTransaction(s){var e;return(e=this._getClient())==null?void 0:e.sendTransaction(s)},async getCapabilities(s){var e;return(e=this._getClient())==null?void 0:e.getCapabilities(s)},async grantPermissions(s){var e;return(e=this._getClient())==null?void 0:e.grantPermissions(s)},async walletGetAssets(s){var e;return((e=this._getClient())==null?void 0:e.walletGetAssets(s))??{}},async estimateGas(s){var e;return(e=this._getClient())==null?void 0:e.estimateGas(s)},async writeContract(s){var e;return(e=this._getClient())==null?void 0:e.writeContract(s)},async getEnsAddress(s){var e;return(e=this._getClient())==null?void 0:e.getEnsAddress(s)},async getEnsAvatar(s){var e;return(e=this._getClient())==null?void 0:e.getEnsAvatar(s)},checkInstalled(s){var e,t;return((t=(e=this._getClient())==null?void 0:e.checkInstalled)==null?void 0:t.call(e,s))||!1},resetWcConnection(){Re.wcUri=void 0,Re.wcPairingExpiry=void 0,Re.wcLinking=void 0,Re.recentWallet=void 0,Re.status="disconnected",UD.resetTransactions(),G.deleteWalletConnectDeepLink()},resetUri(){Re.wcUri=void 0,Re.wcPairingExpiry=void 0},finalizeWcConnection(){var t,i;const{wcLinking:s,recentWallet:e}=Ue.state;s&&G.setWalletConnectDeepLink(s),e&&G.setAppKitRecent(e),ze.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:s?"mobile":"qrcode",name:((i=(t=Se.state.data)==null?void 0:t.wallet)==null?void 0:i.name)||"Unknown"}})},setWcBasic(s){Re.wcBasic=s},setUri(s){Re.wcUri=s,Re.wcPairingExpiry=se.getPairingExpiry()},setWcLinking(s){Re.wcLinking=s},setWcError(s){Re.wcError=s,Re.buffering=!1},setRecentWallet(s){Re.recentWallet=s},setBuffering(s){Re.buffering=s},setStatus(s){Re.status=s},async disconnect(s){try{ct.setLoading(!0,s),await Lo.clearSessions(),await v.disconnect(s),ct.setLoading(!1,s),te.setFilterByNamespace(void 0)}catch{throw new Error("Failed to disconnect")}}},wo=Xe({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),fi={state:wo,subscribe(s){return Yt(wo,()=>s(wo))},set(s){Object.assign(wo,{...wo,...s})}},Ll={createBalance(s,e){const t={name:s.metadata.name||"",symbol:s.metadata.symbol||"",decimals:s.metadata.decimals||0,value:s.metadata.value||0,price:s.metadata.price||0,iconUrl:s.metadata.iconUrl||""};return{name:t.name,symbol:t.symbol,chainId:e,address:s.address==="native"?void 0:this.convertAddressToCAIP10Address(s.address,e),value:t.value,price:t.price,quantity:{decimals:t.decimals.toString(),numeric:this.convertHexToBalance({hex:s.balance,decimals:t.decimals})},iconUrl:t.iconUrl}},convertHexToBalance({hex:s,decimals:e}){return yv(BigInt(s),e)},convertAddressToCAIP10Address(s,e){return`${e}:${s}`},createCAIP2ChainId(s,e){return`${e}:${parseInt(s,16)}`},getChainIdHexFromCAIP2ChainId(s){const e=s.split(":");if(e.length<2||!e[1])return"0x0";const t=e[1],i=parseInt(t,10);return isNaN(i)?"0x0":`0x${i.toString(16)}`},isWalletGetAssetsResponse(s){return typeof s!="object"||s===null?!1:Object.values(s).every(e=>Array.isArray(e)&&e.every(t=>this.isValidAsset(t)))},isValidAsset(s){return typeof s=="object"&&s!==null&&typeof s.address=="string"&&typeof s.balance=="string"&&(s.type==="ERC20"||s.type==="NATIVE")&&typeof s.metadata=="object"&&s.metadata!==null&&typeof s.metadata.name=="string"&&typeof s.metadata.symbol=="string"&&typeof s.metadata.decimals=="number"&&typeof s.metadata.price=="number"&&typeof s.metadata.iconUrl=="string"}},fg={async getMyTokensWithBalance(s){const e=Z.state.address,t=v.state.activeCaipNetwork;if(!e||!t)return[];if(t.chainNamespace==="eip155"){const r=await this.getEIP155Balances(e,t);if(r)return this.filterLowQualityTokens(r)}const i=await X.getBalance(e,t.caipNetworkId,s);return this.filterLowQualityTokens(i.balances)},async getEIP155Balances(s,e){var t,i;try{const r=Ll.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),n=await Ue.getCapabilities(s);if(!((i=(t=n==null?void 0:n[r])==null?void 0:t.assetDiscovery)!=null&&i.supported))return null;const o=await Ue.walletGetAssets({account:s,chainFilter:[r]});return Ll.isWalletGetAssetsResponse(o)?(o[r]||[]).map(l=>Ll.createBalance(l,e.caipNetworkId)):null}catch{return null}},filterLowQualityTokens(s){return s.filter(e=>e.quantity.decimals!=="0")},mapBalancesToSwapTokens(s){return(s==null?void 0:s.map(e=>({...e,address:e!=null&&e.address?e.address:v.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]}},ue=Xe({tokenBalances:[],loading:!1}),mg={state:ue,subscribe(s){return Yt(ue,()=>s(ue))},subscribeKey(s,e){return vs(ue,s,e)},setToken(s){s&&(ue.token=Ir(s))},setTokenAmount(s){ue.sendTokenAmount=s},setReceiverAddress(s){ue.receiverAddress=s},setReceiverProfileImageUrl(s){ue.receiverProfileImageUrl=s},setReceiverProfileName(s){ue.receiverProfileName=s},setGasPrice(s){ue.gasPrice=s},setGasPriceInUsd(s){ue.gasPriceInUSD=s},setNetworkBalanceInUsd(s){ue.networkBalanceInUSD=s},setLoading(s){ue.loading=s},sendToken(){var s;switch((s=v.state.activeCaipNetwork)==null?void 0:s.chainNamespace){case"eip155":this.sendEvmToken();return;case"solana":this.sendSolanaToken();return;default:throw new Error("Unsupported chain")}},sendEvmToken(){var s,e,t,i,r;(s=this.state.token)!=null&&s.address&&this.state.sendTokenAmount&&this.state.receiverAddress?(ze.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token.address,amount:this.state.sendTokenAmount,network:((e=v.state.activeCaipNetwork)==null?void 0:e.caipNetworkId)||""}}),this.sendERC20Token({receiverAddress:this.state.receiverAddress,tokenAddress:this.state.token.address,sendTokenAmount:this.state.sendTokenAmount,decimals:this.state.token.quantity.decimals})):this.state.receiverAddress&&this.state.sendTokenAmount&&this.state.gasPrice&&((t=this.state.token)!=null&&t.quantity.decimals)&&(ze.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT,token:(i=this.state.token)==null?void 0:i.symbol,amount:this.state.sendTokenAmount,network:((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||""}}),this.sendNativeToken({receiverAddress:this.state.receiverAddress,sendTokenAmount:this.state.sendTokenAmount,gasPrice:this.state.gasPrice,decimals:this.state.token.quantity.decimals}))},async fetchTokenBalance(s){var n,o;ue.loading=!0;const e=(n=v.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,t=(o=v.state.activeCaipNetwork)==null?void 0:o.chainNamespace,i=v.state.activeCaipAddress,r=i?se.getPlainAddress(i):void 0;if(ue.lastRetry&&!se.isAllowedRetry(ue.lastRetry,30*os.ONE_SEC_MS))return ue.loading=!1,[];try{if(r&&e&&t){const a=await fg.getMyTokensWithBalance();return ue.tokenBalances=a,ue.lastRetry=void 0,a}}catch(a){ue.lastRetry=Date.now(),s==null||s(a),xt.showError("Token Balance Unavailable")}finally{ue.loading=!1}return[]},fetchNetworkBalance(){if(ue.tokenBalances.length===0)return;const s=fg.mapBalancesToSwapTokens(ue.tokenBalances);if(!s)return;const e=s.find(t=>t.address===v.getActiveNetworkTokenAddress());e&&(ue.networkBalanceInUSD=e?za.multiply(e.quantity.numeric,e.price).toString():"0")},isInsufficientNetworkTokenForGas(s,e){const t=e||"0";return za.bigNumber(s).eq(0)?!0:za.bigNumber(za.bigNumber(t)).gt(s)},hasInsufficientGasFunds(){let s=!0;return Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT?s=!1:ue.networkBalanceInUSD&&(s=this.isInsufficientNetworkTokenForGas(ue.networkBalanceInUSD,ue.gasPriceInUSD)),s},async sendNativeToken(s){var n,o,a,l;Se.pushTransactionStack({view:"Account",goBack:!1});const e=s.receiverAddress,t=Z.state.address,i=Ue.parseUnits(s.sendTokenAmount.toString(),Number(s.decimals)),r="0x";try{await Ue.sendTransaction({chainNamespace:"eip155",to:e,address:t,data:r,value:i??BigInt(0),gasPrice:s.gasPrice}),xt.showSuccess("Transaction started"),ze.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT,token:((n=this.state.token)==null?void 0:n.symbol)||"",amount:s.sendTokenAmount,network:((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)||""}}),this.resetSend()}catch(c){console.error("SendController:sendERC20Token - failed to send native token",c);const h=c instanceof Error?c.message:"Unknown error";ze.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:h,isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT,token:((a=this.state.token)==null?void 0:a.symbol)||"",amount:s.sendTokenAmount,network:((l=v.state.activeCaipNetwork)==null?void 0:l.caipNetworkId)||""}}),xt.showError("Something went wrong")}},async sendERC20Token(s){var t,i;Se.pushTransactionStack({view:"Account",goBack:!1});const e=Ue.parseUnits(s.sendTokenAmount.toString(),Number(s.decimals));try{if(Z.state.address&&s.sendTokenAmount&&s.receiverAddress&&s.tokenAddress){const r=se.getPlainAddress(s.tokenAddress);await Ue.writeContract({fromAddress:Z.state.address,tokenAddress:r,args:[s.receiverAddress,e??BigInt(0)],method:"transfer",abi:sD.getERC20Abi(r),chainNamespace:"eip155"}),xt.showSuccess("Transaction started"),this.resetSend()}}catch(r){console.error("SendController:sendERC20Token - failed to send erc20 token",r);const n=r instanceof Error?r.message:"Unknown error";ze.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:n,isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT,token:((t=this.state.token)==null?void 0:t.symbol)||"",amount:s.sendTokenAmount,network:((i=v.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||""}}),xt.showError("Something went wrong")}},sendSolanaToken(){if(!this.state.sendTokenAmount||!this.state.receiverAddress){xt.showError("Please enter a valid amount and receiver address");return}Se.pushTransactionStack({view:"Account",goBack:!1}),Ue.sendTransaction({chainNamespace:"solana",to:this.state.receiverAddress,value:this.state.sendTokenAmount}).then(()=>{this.resetSend(),Z.fetchTokenBalance()}).catch(s=>{xt.showError("Failed to send transaction. Please try again."),console.error("SendController:sendToken - failed to send solana transaction",s)})},resetSend(){ue.token=void 0,ue.sendTokenAmount=void 0,ue.receiverAddress=void 0,ue.receiverProfileImageUrl=void 0,ue.receiverProfileName=void 0,ue.loading=!1,ue.tokenBalances=[]}},Ul={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},qa={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},F=Xe({chains:cD(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),v={state:F,subscribe(s){return Yt(F,()=>{s(F)})},subscribeKey(s,e){return vs(F,s,e)},subscribeChainProp(s,e,t){let i;return Yt(F.chains,()=>{var n;const r=t||F.activeChain;if(r){const o=(n=F.chains.get(r))==null?void 0:n[s];i!==o&&(i=o,e(o))}})},initialize(s,e,t){const{chainId:i,namespace:r}=G.getActiveNetworkProps(),n=e==null?void 0:e.find(c=>c.id.toString()===(i==null?void 0:i.toString())),a=s.find(c=>(c==null?void 0:c.namespace)===r)||(s==null?void 0:s[0]),l=new Set([...(e==null?void 0:e.map(c=>c.chainNamespace))??[]]);((s==null?void 0:s.length)===0||!a)&&(F.noAdapters=!0),F.noAdapters||(F.activeChain=a==null?void 0:a.namespace,F.activeCaipNetwork=n,this.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:n}),F.activeChain&&fi.set({activeChain:a==null?void 0:a.namespace})),l.forEach(c=>{const h=e==null?void 0:e.filter(u=>u.chainNamespace===c);v.state.chains.set(c,{namespace:c,networkState:Xe({...qa,caipNetwork:h==null?void 0:h[0]}),accountState:Xe(Ul),caipNetworks:h??[],...t}),this.setRequestedCaipNetworks(h??[],c)})},removeAdapter(s){var e,t;if(F.activeChain===s){const i=Array.from(F.chains.entries()).find(([r])=>r!==s);if(i){const r=(t=(e=i[1])==null?void 0:e.caipNetworks)==null?void 0:t[0];r&&this.setActiveCaipNetwork(r)}}F.chains.delete(s)},addAdapter(s,{networkControllerClient:e,connectionControllerClient:t},i){F.chains.set(s.namespace,{namespace:s.namespace,networkState:{...qa,caipNetwork:i[0]},accountState:Ul,caipNetworks:i,connectionControllerClient:t,networkControllerClient:e}),this.setRequestedCaipNetworks((i==null?void 0:i.filter(r=>r.chainNamespace===s.namespace))??[],s.namespace)},addNetwork(s){var t;const e=F.chains.get(s.chainNamespace);if(e){const i=[...e.caipNetworks||[]];(t=e.caipNetworks)!=null&&t.find(r=>r.id===s.id)||i.push(s),F.chains.set(s.chainNamespace,{...e,caipNetworks:i}),this.setRequestedCaipNetworks(i,s.chainNamespace)}},removeNetwork(s,e){var i,r,n;const t=F.chains.get(s);if(t){const o=((i=F.activeCaipNetwork)==null?void 0:i.id)===e,a=[...((r=t.caipNetworks)==null?void 0:r.filter(l=>l.id!==e))||[]];o&&((n=t==null?void 0:t.caipNetworks)!=null&&n[0])&&this.setActiveCaipNetwork(t.caipNetworks[0]),F.chains.set(s,{...t,caipNetworks:a}),this.setRequestedCaipNetworks(a||[],s)}},setAdapterNetworkState(s,e){const t=F.chains.get(s);t&&(t.networkState={...t.networkState||qa,...e},F.chains.set(s,t))},setChainAccountData(s,e,t=!0){if(!s)throw new Error("Chain is required to update chain account data");const i=F.chains.get(s);if(i){const r={...i.accountState||Ul,...e};F.chains.set(s,{...i,accountState:r}),(F.chains.size===1||F.activeChain===s)&&(e.caipAddress&&(F.activeCaipAddress=e.caipAddress),Z.replaceState(r))}},setChainNetworkData(s,e){if(!s)return;const t=F.chains.get(s);if(t){const i={...t.networkState||qa,...e};F.chains.set(s,{...t,networkState:i})}},setAccountProp(s,e,t,i=!0){this.setChainAccountData(t,{[s]:e},i),s==="status"&&e==="disconnected"&&t&&te.removeConnectorId(t)},setActiveNamespace(s){var i,r;F.activeChain=s;const e=s?F.chains.get(s):void 0,t=(i=e==null?void 0:e.networkState)==null?void 0:i.caipNetwork;t!=null&&t.id&&s&&(F.activeCaipAddress=(r=e==null?void 0:e.accountState)==null?void 0:r.caipAddress,F.activeCaipNetwork=t,this.setChainNetworkData(s,{caipNetwork:t}),G.setActiveCaipNetworkId(t==null?void 0:t.caipNetworkId),fi.set({activeChain:s,selectedNetworkId:t==null?void 0:t.caipNetworkId}))},setActiveCaipNetwork(s){var i,r,n;if(!s)return;F.activeChain!==s.chainNamespace&&this.setIsSwitchingNamespace(!0);const e=F.chains.get(s.chainNamespace);F.activeChain=s.chainNamespace,F.activeCaipNetwork=s,this.setChainNetworkData(s.chainNamespace,{caipNetwork:s}),(i=e==null?void 0:e.accountState)!=null&&i.address?F.activeCaipAddress=`${s.chainNamespace}:${s.id}:${(r=e==null?void 0:e.accountState)==null?void 0:r.address}`:F.activeCaipAddress=void 0,this.setAccountProp("caipAddress",F.activeCaipAddress,s.chainNamespace),e&&Z.replaceState(e.accountState),mg.resetSend(),fi.set({activeChain:F.activeChain,selectedNetworkId:(n=F.activeCaipNetwork)==null?void 0:n.caipNetworkId}),G.setActiveCaipNetworkId(s.caipNetworkId),!this.checkIfSupportedNetwork(s.chainNamespace)&&D.state.enableNetworkSwitch&&!D.state.allowUnsupportedChain&&!Ue.state.wcBasic&&this.showUnsupportedChainUI()},addCaipNetwork(s){var t;if(!s)return;const e=F.chains.get(s.chainNamespace);e&&((t=e==null?void 0:e.caipNetworks)==null||t.push(s))},async switchActiveNamespace(s){var r;if(!s)return;const e=s!==v.state.activeChain,t=(r=v.getNetworkData(s))==null?void 0:r.caipNetwork,i=v.getCaipNetworkByNamespace(s,t==null?void 0:t.id);e&&i&&await v.switchActiveNetwork(i)},async switchActiveNetwork(s){var r;const e=v.state.chains.get(v.state.activeChain);!((r=e==null?void 0:e.caipNetworks)!=null&&r.some(n=>{var o;return n.id===((o=F.activeCaipNetwork)==null?void 0:o.id)}))&&Se.goBack();const i=this.getNetworkControllerClient(s.chainNamespace);i&&(await i.switchCaipNetwork(s),ze.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:s.caipNetworkId}}))},getNetworkControllerClient(s){const e=s||F.activeChain,t=F.chains.get(e);if(!t)throw new Error("Chain adapter not found");if(!t.networkControllerClient)throw new Error("NetworkController client not set");return t.networkControllerClient},getConnectionControllerClient(s){const e=s||F.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const t=F.chains.get(e);if(!(t!=null&&t.connectionControllerClient))throw new Error("ConnectionController client not set");return t.connectionControllerClient},getAccountProp(s,e){var r;let t=F.activeChain;if(e&&(t=e),!t)return;const i=(r=F.chains.get(t))==null?void 0:r.accountState;if(i)return i[s]},getNetworkProp(s,e){var i;const t=(i=F.chains.get(e))==null?void 0:i.networkState;if(t)return t[s]},getRequestedCaipNetworks(s){const e=F.chains.get(s),{approvedCaipNetworkIds:t=[],requestedCaipNetworks:i=[]}=(e==null?void 0:e.networkState)||{};return se.sortRequestedNetworks(t,i)},getAllRequestedCaipNetworks(){const s=[];return F.chains.forEach(e=>{const t=this.getRequestedCaipNetworks(e.namespace);s.push(...t)}),s},setRequestedCaipNetworks(s,e){this.setAdapterNetworkState(e,{requestedCaipNetworks:s})},getAllApprovedCaipNetworkIds(){const s=[];return F.chains.forEach(e=>{const t=this.getApprovedCaipNetworkIds(e.namespace);s.push(...t)}),s},getActiveCaipNetwork(){return F.activeCaipNetwork},getActiveCaipAddress(){return F.activeCaipAddress},getApprovedCaipNetworkIds(s){var i;const e=F.chains.get(s);return((i=e==null?void 0:e.networkState)==null?void 0:i.approvedCaipNetworkIds)||[]},async setApprovedCaipNetworksData(s){const e=this.getNetworkControllerClient(),t=await(e==null?void 0:e.getApprovedCaipNetworksData());this.setAdapterNetworkState(s,{approvedCaipNetworkIds:t==null?void 0:t.approvedCaipNetworkIds,supportsAllNetworks:t==null?void 0:t.supportsAllNetworks})},checkIfSupportedNetwork(s,e){const t=e||F.activeCaipNetwork,i=this.getRequestedCaipNetworks(s);return i.length?i==null?void 0:i.some(r=>r.id===(t==null?void 0:t.id)):!0},checkIfSupportedChainId(s){if(!F.activeChain)return!0;const e=this.getRequestedCaipNetworks(F.activeChain);return e==null?void 0:e.some(t=>t.id===s)},setSmartAccountEnabledNetworks(s,e){this.setAdapterNetworkState(e,{smartAccountEnabledNetworks:s})},checkIfSmartAccountEnabled(){var i;const s=Iy.caipNetworkIdToNumber((i=F.activeCaipNetwork)==null?void 0:i.caipNetworkId),e=F.activeChain;if(!e||!s)return!1;const t=this.getNetworkProp("smartAccountEnabledNetworks",e);return!!(t!=null&&t.includes(Number(s)))},getActiveNetworkTokenAddress(){var i,r;const s=((i=F.activeCaipNetwork)==null?void 0:i.chainNamespace)||"eip155",e=((r=F.activeCaipNetwork)==null?void 0:r.id)||1,t=os.NATIVE_TOKEN_ADDRESS[s];return`${s}:${e}:${t}`},showUnsupportedChainUI(){ct.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const s=F.activeCaipNetwork;return!!(s!=null&&s.chainNamespace&&os.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(s.chainNamespace))},resetNetwork(s){this.setAdapterNetworkState(s,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(s){const e=s;if(!e)throw new Error("Chain is required to set account prop");F.activeCaipAddress=void 0,this.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),te.removeConnectorId(e)},async disconnect(s){const e=yD(s);try{mg.resetSend();const t=await Promise.allSettled(e.map(async([r,n])=>{var o;try{const{caipAddress:a}=this.getAccountData(r)||{};a&&((o=n.connectionControllerClient)!=null&&o.disconnect)&&await n.connectionControllerClient.disconnect(r),this.resetAccount(r),this.resetNetwork(r)}catch(a){throw new Error(`Failed to disconnect chain ${r}: ${a.message}`)}}));Ue.resetWcConnection();const i=t.filter(r=>r.status==="rejected");if(i.length>0)throw new Error(i.map(r=>r.reason.message).join(", "));G.deleteConnectedSocialProvider(),s?te.removeConnectorId(s):te.resetConnectorIds(),ze.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:s||"all"}})}catch(t){console.error(t.message||"Failed to disconnect chains"),ze.sendEvent({type:"track",event:"DISCONNECT_ERROR",properties:{message:t.message||"Failed to disconnect chains"}})}},setIsSwitchingNamespace(s){F.isSwitchingNamespace=s},getFirstCaipNetworkSupportsAuthConnector(){var t,i;const s=[];let e;if(F.chains.forEach(r=>{Q.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===r.namespace)&&r.namespace&&s.push(r.namespace)}),s.length>0){const r=s[0];return e=r?(i=(t=F.chains.get(r))==null?void 0:t.caipNetworks)==null?void 0:i[0]:void 0,e}},getAccountData(s){var e;return s?(e=v.state.chains.get(s))==null?void 0:e.accountState:Z.state},getNetworkData(s){var t;const e=s||F.activeChain;if(e)return(t=v.state.chains.get(e))==null?void 0:t.networkState},getCaipNetworkByNamespace(s,e){var r,n,o;if(!s)return;const t=v.state.chains.get(s),i=(r=t==null?void 0:t.caipNetworks)==null?void 0:r.find(a=>a.id===e);return i||((n=t==null?void 0:t.networkState)==null?void 0:n.caipNetwork)||((o=t==null?void 0:t.caipNetworks)==null?void 0:o[0])},getRequestedCaipNetworkIds(){const s=te.state.filterByNamespace;return(s?[F.chains.get(s)]:Array.from(F.chains.values())).flatMap(t=>(t==null?void 0:t.caipNetworks)||[]).map(t=>t.caipNetworkId)}},zD={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"}]}]},Cy=se.getBlockchainApiUrl(),cs=Xe({clientId:null,api:new tl({baseUrl:Cy,clientId:null}),supportedChains:{http:[],ws:[]}}),X={state:cs,async get(s){const{st:e,sv:t}=X.getSdkProperties(),i=D.state.projectId,r={...s.params||{},st:e,sv:t,projectId:i};return cs.api.get({...s,params:r})},getSdkProperties(){const{sdkType:s,sdkVersion:e}=D.state;return{st:s||"unknown",sv:e||"unknown"}},async isNetworkSupported(s){if(!s)return!1;try{cs.supportedChains.http.length||await X.getSupportedNetworks()}catch{return!1}return cs.supportedChains.http.includes(s)},async getSupportedNetworks(){const s=await X.get({path:"v1/supported-chains"});return cs.supportedChains=s,s},async fetchIdentity({address:s,caipNetworkId:e}){if(!await X.isNetworkSupported(e))return{avatar:"",name:""};const i=G.getIdentityFromCacheForAddress(s);if(i)return i;const r=await X.get({path:`/v1/identity/${s}`,params:{sender:v.state.activeCaipAddress?se.getPlainAddress(v.state.activeCaipAddress):void 0}});return G.updateIdentityCache({address:s,identity:r,timestamp:Date.now()}),r},async fetchTransactions({account:s,cursor:e,onramp:t,signal:i,cache:r,chainId:n}){var a;return await X.isNetworkSupported((a=v.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?X.get({path:`/v1/account/${s}/history`,params:{cursor:e,onramp:t,chainId:n},signal:i,cache:r}):{data:[],next:void 0}},async fetchSwapQuote({amount:s,userAddress:e,from:t,to:i,gasPrice:r}){var o;return await X.isNetworkSupported((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?X.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:s,userAddress:e,from:t,to:i,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:s}){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?X.get({path:"/v1/convert/tokens",params:{chainId:s}}):{tokens:[]}},async fetchTokenPrice({addresses:s}){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?cs.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:s,projectId:D.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:s,userAddress:e}){var i;return await X.isNetworkSupported((i=v.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?X.get({path:"/v1/convert/allowance",params:{tokenAddress:s,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:s}){var r;const{st:e,sv:t}=X.getSdkProperties();if(!await X.isNetworkSupported((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))throw new Error("Network not supported for Gas Price");return X.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:s,st:e,sv:t}})},async generateSwapCalldata({amount:s,from:e,to:t,userAddress:i,disableEstimate:r}){var o;if(!await X.isNetworkSupported((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return cs.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:s,eip155:{slippage:os.CONVERT_SLIPPAGE_TOLERANCE},projectId:D.state.projectId,from:e,to:t,userAddress:i,disableEstimate:r}})},async generateApproveCalldata({from:s,to:e,userAddress:t}){var o;const{st:i,sv:r}=X.getSdkProperties();if(!await X.isNetworkSupported((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return X.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:t,from:s,to:e,st:i,sv:r}})},async getBalance(s,e,t){var c;const{st:i,sv:r}=X.getSdkProperties();if(!await X.isNetworkSupported((c=v.state.activeCaipNetwork)==null?void 0:c.caipNetworkId))return xt.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${s}`,a=G.getBalanceCacheForCaipAddress(o);if(a)return a;const l=await X.get({path:`/v1/account/${s}/balance`,params:{currency:"usd",chainId:e,forceUpdate:t,st:i,sv:r}});return G.updateBalanceCache({caipAddress:o,balance:l,timestamp:Date.now()}),l},async lookupEnsName(s){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?X.get({path:`/v1/profile/account/${s}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:s}){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?X.get({path:`/v1/profile/reverse/${s}`,params:{sender:Z.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(s){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?X.get({path:`/v1/profile/suggestions/${s}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:s,address:e,message:t,signature:i}){var n;return await X.isNetworkSupported((n=v.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?cs.api.post({path:"/v1/profile/account",body:{coin_type:s,address:e,message:t,signature:i},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:s,partnerUserId:e,defaultNetwork:t,purchaseAmount:i,paymentAmount:r}){var a;return await X.isNetworkSupported((a=v.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await cs.api.post({path:"/v1/generators/onrampurl",params:{projectId:D.state.projectId},body:{destinationWallets:s,defaultNetwork:t,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:i,presetFiatAmount:r}})).url:""},async getOnrampOptions(){var e;if(!await X.isNetworkSupported((e=v.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await X.get({path:"/v1/onramp/options"})}catch{return zD}},async getOnrampQuote({purchaseCurrency:s,paymentCurrency:e,amount:t,network:i}){var r;try{return await X.isNetworkSupported((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?await cs.api.post({path:"/v1/onramp/quote",params:{projectId:D.state.projectId},body:{purchaseCurrency:s,paymentCurrency:e,amount:t,network:i}}):null}catch{return{coinbaseFee:{amount:t,currency:e.id},networkFee:{amount:t,currency:e.id},paymentSubtotal:{amount:t,currency:e.id},paymentTotal:{amount:t,currency:e.id},purchaseAmount:{amount:t,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(s){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?X.get({path:`/v1/sessions/${s}`}):[]},async revokeSmartSession(s,e,t){var r;return await X.isNetworkSupported((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?cs.api.post({path:`/v1/sessions/${s}/revoke`,params:{projectId:D.state.projectId},body:{pci:e,signature:t}}):{success:!1}},setClientId(s){cs.clientId=s,cs.api=new tl({baseUrl:Cy,clientId:s})}},Ks=Xe({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),Z={state:Ks,replaceState(s){s&&Object.assign(Ks,Ir(s))},subscribe(s){return v.subscribeChainProp("accountState",e=>{if(e)return s(e)})},subscribeKey(s,e,t){let i;return v.subscribeChainProp("accountState",r=>{if(r){const n=r[s];i!==n&&(i=n,e(n))}},t)},setStatus(s,e){v.setAccountProp("status",s,e)},getCaipAddress(s){return v.getAccountProp("caipAddress",s)},setCaipAddress(s,e){const t=s?se.getPlainAddress(s):void 0;e===v.state.activeChain&&(v.state.activeCaipAddress=s),v.setAccountProp("caipAddress",s,e),v.setAccountProp("address",t,e)},setBalance(s,e,t){v.setAccountProp("balance",s,t),v.setAccountProp("balanceSymbol",e,t)},setProfileName(s,e){v.setAccountProp("profileName",s,e)},setProfileImage(s,e){v.setAccountProp("profileImage",s,e)},setUser(s,e){v.setAccountProp("user",s,e)},setAddressExplorerUrl(s,e){v.setAccountProp("addressExplorerUrl",s,e)},setSmartAccountDeployed(s,e){v.setAccountProp("smartAccountDeployed",s,e)},setCurrentTab(s){v.setAccountProp("currentTab",s,v.state.activeChain)},setTokenBalance(s,e){s&&v.setAccountProp("tokenBalance",s,e)},setShouldUpdateToAddress(s,e){v.setAccountProp("shouldUpdateToAddress",s,e)},setAllAccounts(s,e){v.setAccountProp("allAccounts",s,e)},addAddressLabel(s,e,t){const i=v.getAccountProp("addressLabels",t)||new Map;i.set(s,e),v.setAccountProp("addressLabels",i,t)},removeAddressLabel(s,e){const t=v.getAccountProp("addressLabels",e)||new Map;t.delete(s),v.setAccountProp("addressLabels",t,e)},setConnectedWalletInfo(s,e){v.setAccountProp("connectedWalletInfo",s,e,!1)},setPreferredAccountType(s,e){v.setAccountProp("preferredAccountType",s,e)},setSocialProvider(s,e){s&&v.setAccountProp("socialProvider",s,e)},setSocialWindow(s,e){v.setAccountProp("socialWindow",s?Ir(s):void 0,e)},setFarcasterUrl(s,e){v.setAccountProp("farcasterUrl",s,e)},async fetchTokenBalance(s){var n,o;Ks.balanceLoading=!0;const e=(n=v.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,t=(o=v.state.activeCaipNetwork)==null?void 0:o.chainNamespace,i=v.state.activeCaipAddress,r=i?se.getPlainAddress(i):void 0;if(Ks.lastRetry&&!se.isAllowedRetry(Ks.lastRetry,30*os.ONE_SEC_MS))return Ks.balanceLoading=!1,[];try{if(r&&e&&t){const l=(await X.getBalance(r,e)).balances.filter(c=>c.quantity.decimals!=="0");return this.setTokenBalance(l,t),Ks.lastRetry=void 0,Ks.balanceLoading=!1,l}}catch(a){Ks.lastRetry=Date.now(),s==null||s(a),xt.showError("Token Balance Unavailable")}finally{Ks.balanceLoading=!1}return[]},resetAccount(s){v.resetAccount(s)}},Jt=Xe({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),ct={state:Jt,subscribe(s){return Yt(Jt,()=>s(Jt))},subscribeKey(s,e){return vs(Jt,s,e)},async open(s){var r;const e=Z.state.status==="connected";Ue.state.wcBasic?ie.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await ie.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),s!=null&&s.namespace?(await v.switchActiveNamespace(s.namespace),ct.setLoading(!0,s.namespace)):ct.setLoading(!0),te.setFilterByNamespace(s==null?void 0:s.namespace);const t=(r=v.getAccountData(s==null?void 0:s.namespace))==null?void 0:r.caipAddress;v.state.noAdapters&&!t?se.isMobile()?Se.reset("AllWallets"):Se.reset("ConnectingWalletConnectBasic"):s!=null&&s.view?Se.reset(s.view):t?Se.reset("Account"):Se.reset("Connect"),Jt.open=!0,fi.set({open:!0}),ze.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!t}})},close(){const s=D.state.enableEmbedded,e=!!v.state.activeCaipAddress;Jt.open&&ze.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),Jt.open=!1,ct.clearLoading(),s?e?Se.replace("Account"):Se.push("Connect"):fi.set({open:!1}),Ue.resetUri()},setLoading(s,e){e&&Jt.loadingNamespaceMap.set(e,s),Jt.loading=s,fi.set({loading:s})},clearLoading(){Jt.loadingNamespaceMap.clear(),Jt.loading=!1},shake(){Jt.shake||(Jt.shake=!0,setTimeout(()=>{Jt.shake=!1},500))}},wg=2147483648,FD={convertEVMChainIdToCoinType(s){if(s>=wg)throw new Error("Invalid chainId");return(wg|s)>>>0}},Es=Xe({suggestions:[],loading:!1}),Sy={state:Es,subscribe(s){return Yt(Es,()=>s(Es))},subscribeKey(s,e){return vs(Es,s,e)},async resolveName(s){var e,t;try{return await X.lookupEnsName(s)}catch(i){const r=i;throw new Error(((t=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:t.description)||"Error resolving name")}},async isNameRegistered(s){try{return await X.lookupEnsName(s),!0}catch{return!1}},async getSuggestions(s){try{Es.loading=!0,Es.suggestions=[];const e=await X.getEnsNameSuggestions(s);return Es.suggestions=e.suggestions.map(t=>({...t,name:t.name}))||[],Es.suggestions}catch(e){const t=this.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(t)}finally{Es.loading=!1}},async getNamesForAddress(s){try{if(!v.state.activeCaipNetwork)return[];const t=G.getEnsFromCacheForAddress(s);if(t)return t;const i=await X.reverseLookupEnsName({address:s});return G.updateEnsCache({address:s,ens:i,timestamp:Date.now()}),i}catch(e){const t=this.parseEnsApiError(e,"Error fetching names for address");throw new Error(t)}},async registerName(s){const e=v.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const t=Z.state.address,i=te.getAuthConnector();if(!t||!i)throw new Error("Address or auth connector not found");Es.loading=!0;try{const r=JSON.stringify({name:s,attributes:{},timestamp:Math.floor(Date.now()/1e3)});Se.pushTransactionStack({view:"RegisterAccountNameSuccess",goBack:!1,replace:!0,onCancel(){Es.loading=!1}});const n=await Ue.signMessage(r),o=e.id;if(!o)throw new Error("Network not found");const a=FD.convertEVMChainIdToCoinType(Number(o));await X.registerEnsName({coinType:a,address:t,signature:n,message:r}),Z.setProfileName(s,e.chainNamespace),Se.replace("RegisterAccountNameSuccess")}catch(r){const n=this.parseEnsApiError(r,`Error registering name ${s}`);throw Se.replace("RegisterAccountName"),new Error(n)}finally{Es.loading=!1}},validateName(s){return/^[a-zA-Z0-9-]{4,}$/u.test(s)},parseEnsApiError(s,e){var i,r;const t=s;return((r=(i=t==null?void 0:t.reasons)==null?void 0:i[0])==null?void 0:r.description)||e}};function qD(s){return!s||typeof s.then!="function"?Promise.resolve(s):s}function bt(s,...e){try{return qD(s(...e))}catch(t){return Promise.reject(t)}}function BD(s){const e=typeof s;return s===null||e!=="object"&&e!=="function"}function HD(s){const e=Object.getPrototypeOf(s);return!e||e.isPrototypeOf(Object)}function cc(s){if(BD(s))return String(s);if(HD(s)||Array.isArray(s))return JSON.stringify(s);if(typeof s.toJSON=="function")return cc(s.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Bh="base64:";function WD(s){return typeof s=="string"?s:Bh+GD(s)}function VD(s){return typeof s!="string"||!s.startsWith(Bh)?s:KD(s.slice(Bh.length))}function KD(s){return globalThis.Buffer?_.Buffer.from(s,"base64"):Uint8Array.from(globalThis.atob(s),e=>e.codePointAt(0))}function GD(s){return globalThis.Buffer?_.Buffer.from(s).toString("base64"):globalThis.btoa(String.fromCodePoint(...s))}function ss(s){var e;return s&&((e=s.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function YD(...s){return ss(s.join(":"))}function Ba(s){return s=ss(s),s?s+":":""}function QD(s,e){if(e===void 0)return!0;let t=0,i=s.indexOf(":");for(;i>-1;)t++,i=s.indexOf(":",i+1);return t<=e}function ZD(s,e){return e?s.startsWith(e)&&s[s.length-1]!=="$":s[s.length-1]!=="$"}const JD="memory",XD=()=>{const s=new Map;return{name:JD,getInstance:()=>s,hasItem(e){return s.has(e)},getItem(e){return s.get(e)??null},getItemRaw(e){return s.get(e)??null},setItem(e,t){s.set(e,t)},setItemRaw(e,t){s.set(e,t)},removeItem(e){s.delete(e)},getKeys(){return[...s.keys()]},clear(){s.clear()},dispose(){s.clear()}}};function ek(s={}){const e={mounts:{"":s.driver||XD()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=c=>{for(const h of e.mountpoints)if(c.startsWith(h))return{base:h,relativeKey:c.slice(h.length),driver:e.mounts[h]};return{base:"",relativeKey:c,driver:e.mounts[""]}},i=(c,h)=>e.mountpoints.filter(u=>u.startsWith(c)||h&&c.startsWith(u)).map(u=>({relativeBase:c.length>u.length?c.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(c,h)=>{if(e.watching){h=ss(h);for(const u of e.watchListeners)u(c,h)}},n=async()=>{if(!e.watching){e.watching=!0;for(const c in e.mounts)e.unwatch[c]=await yg(e.mounts[c],r,c)}},o=async()=>{if(e.watching){for(const c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},a=(c,h,u)=>{const d=new Map,p=g=>{let f=d.get(g.base);return f||(f={driver:g.driver,base:g.base,items:[]},d.set(g.base,f)),f};for(const g of c){const f=typeof g=="string",y=ss(f?g:g.key),w=f?void 0:g.value,m=f||!g.options?h:{...h,...g.options},b=t(y);p(b).items.push({key:y,value:w,relativeKey:b.relativeKey,options:m})}return Promise.all([...d.values()].map(g=>u(g))).then(g=>g.flat())},l={hasItem(c,h={}){c=ss(c);const{relativeKey:u,driver:d}=t(c);return bt(d.hasItem,u,h)},getItem(c,h={}){c=ss(c);const{relativeKey:u,driver:d}=t(c);return bt(d.getItem,u,h).then(p=>Di(p))},getItems(c,h={}){return a(c,h,u=>u.driver.getItems?bt(u.driver.getItems,u.items.map(d=>({key:d.relativeKey,options:d.options})),h).then(d=>d.map(p=>({key:YD(u.base,p.key),value:Di(p.value)}))):Promise.all(u.items.map(d=>bt(u.driver.getItem,d.relativeKey,d.options).then(p=>({key:d.key,value:Di(p)})))))},getItemRaw(c,h={}){c=ss(c);const{relativeKey:u,driver:d}=t(c);return d.getItemRaw?bt(d.getItemRaw,u,h):bt(d.getItem,u,h).then(p=>VD(p))},async setItem(c,h,u={}){if(h===void 0)return l.removeItem(c);c=ss(c);const{relativeKey:d,driver:p}=t(c);p.setItem&&(await bt(p.setItem,d,cc(h),u),p.watch||r("update",c))},async setItems(c,h){await a(c,h,async u=>{if(u.driver.setItems)return bt(u.driver.setItems,u.items.map(d=>({key:d.relativeKey,value:cc(d.value),options:d.options})),h);u.driver.setItem&&await Promise.all(u.items.map(d=>bt(u.driver.setItem,d.relativeKey,cc(d.value),d.options)))})},async setItemRaw(c,h,u={}){if(h===void 0)return l.removeItem(c,u);c=ss(c);const{relativeKey:d,driver:p}=t(c);if(p.setItemRaw)await bt(p.setItemRaw,d,h,u);else if(p.setItem)await bt(p.setItem,d,WD(h),u);else return;p.watch||r("update",c)},async removeItem(c,h={}){typeof h=="boolean"&&(h={removeMeta:h}),c=ss(c);const{relativeKey:u,driver:d}=t(c);d.removeItem&&(await bt(d.removeItem,u,h),(h.removeMeta||h.removeMata)&&await bt(d.removeItem,u+"$",h),d.watch||r("remove",c))},async getMeta(c,h={}){typeof h=="boolean"&&(h={nativeOnly:h}),c=ss(c);const{relativeKey:u,driver:d}=t(c),p=Object.create(null);if(d.getMeta&&Object.assign(p,await bt(d.getMeta,u,h)),!h.nativeOnly){const g=await bt(d.getItem,u+"$",h).then(f=>Di(f));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(p,g))}return p},setMeta(c,h,u={}){return this.setItem(c+"$",h,u)},removeMeta(c,h={}){return this.removeItem(c+"$",h)},async getKeys(c,h={}){var y;c=Ba(c);const u=i(c,!0);let d=[];const p=[];let g=!0;for(const w of u){(y=w.driver.flags)!=null&&y.maxDepth||(g=!1);const m=await bt(w.driver.getKeys,w.relativeBase,h);for(const b of m){const I=w.mountpoint+ss(b);d.some(N=>I.startsWith(N))||p.push(I)}d=[w.mountpoint,...d.filter(b=>!b.startsWith(w.mountpoint))]}const f=h.maxDepth!==void 0&&!g;return p.filter(w=>(!f||QD(w,h.maxDepth))&&ZD(w,c))},async clear(c,h={}){c=Ba(c),await Promise.all(i(c,!1).map(async u=>{if(u.driver.clear)return bt(u.driver.clear,u.relativeBase,h);if(u.driver.removeItem){const d=await u.driver.getKeys(u.relativeBase||"",h);return Promise.all(d.map(p=>u.driver.removeItem(p,h)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>bg(c)))},async watch(c){return await n(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(h=>h!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,h){if(c=Ba(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((u,d)=>d.length-u.length)),e.mounts[c]=h,e.watching&&Promise.resolve(yg(h,r,c)).then(u=>{e.unwatch[c]=u}).catch(console.error),l},async unmount(c,h=!0){var u,d;c=Ba(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&((d=(u=e.unwatch)[c])==null||d.call(u),delete e.unwatch[c]),h&&await bg(e.mounts[c]),e.mountpoints=e.mountpoints.filter(p=>p!==c),delete e.mounts[c])},getMount(c=""){c=ss(c)+":";const h=t(c);return{driver:h.driver,base:h.base}},getMounts(c="",h={}){return c=ss(c),i(c,h.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(c,h={})=>l.getKeys(c,h),get:(c,h={})=>l.getItem(c,h),set:(c,h,u={})=>l.setItem(c,h,u),has:(c,h={})=>l.hasItem(c,h),del:(c,h={})=>l.removeItem(c,h),remove:(c,h={})=>l.removeItem(c,h)};return l}function yg(s,e,t){return s.watch?s.watch((i,r)=>e(i,t+r)):()=>{}}async function bg(s){typeof s.dispose=="function"&&await bt(s.dispose)}const tk="idb-keyval";var sk=(s={})=>{const e=s.base&&s.base.length>0?`${s.base}:`:"",t=r=>e+r;let i;return s.dbName&&s.storeName&&(i=Am(s.dbName,s.storeName)),{name:tk,options:s,async hasItem(r){return!(typeof await bc(t(r),i)>"u")},async getItem(r){return await bc(t(r),i)??null},setItem(r,n){return Sm(t(r),n,i)},removeItem(r){return Cm(t(r),i)},getKeys(){return _m(i)},clear(){return Nm(i)}}};const ik="WALLET_CONNECT_V2_INDEXED_DB",rk="keyvaluestorage";let nk=class{constructor(){this.indexedDb=ek({driver:sk({dbName:ik,storeName:rk})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,Sr(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var zl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof _.global<"u"?_.global:typeof self<"u"?self:{},lc={exports:{}};(function(){let s;function e(){}s=e,s.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},s.prototype.setItem=function(t,i){this[t]=String(i)},s.prototype.removeItem=function(t){delete this[t]},s.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(i){t[i]=void 0,delete t[i]})},s.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},s.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof zl<"u"&&zl.localStorage?lc.exports=zl.localStorage:typeof window<"u"&&window.localStorage?lc.exports=window.localStorage:lc.exports=new e})();function ok(s){var e;return[s[0],wi((e=s[1])!=null?e:"")]}let ak=class{constructor(){this.localStorage=lc.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(ok)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return wi(t)}async setItem(e,t){this.localStorage.setItem(e,Sr(t))}async removeItem(e){this.localStorage.removeItem(e)}};const ck="wc_storage_version",vg=1,lk=async(s,e,t)=>{const i=ck,r=await e.getItem(i);if(r&&r>=vg){t(e);return}const n=await s.getKeys();if(!n.length){t(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const l=a.toLowerCase();if(l.includes("wc@")||l.includes("walletconnect")||l.includes("wc_")||l.includes("wallet_connect")){const c=await s.getItem(a);await e.setItem(a,c),o.push(a)}}await e.setItem(i,vg),t(e),hk(s,o)},hk=async(s,e)=>{e.length&&e.forEach(async t=>{await s.removeItem(t)})};let uk=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new ak;this.storage=e;try{const t=new nk;lk(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}};function ea(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function Ig(s){return ea(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const $y="2.23.2";let yo={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${$y}`};class Er extends Error{constructor(e,t={}){var a;const i=(()=>{var l;return t.cause instanceof Er?t.cause.details:(l=t.cause)!=null&&l.message?t.cause.message:t.details})(),r=t.cause instanceof Er&&t.cause.docsPath||t.docsPath,n=(a=yo.getDocsUrl)==null?void 0:a.call(yo,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...yo.version?[`Version: ${yo.version}`]:[]].join(`
13
- `);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=$y}walk(e){return Py(this,e)}}function Py(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?Py(s.cause,e):e?null:s}class Ty extends Er{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Xn(s,{dir:e,size:t=32}={}){return typeof s=="string"?dk(s,{dir:e,size:t}):pk(s,{dir:e,size:t})}function dk(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new Ty({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function pk(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new Ty({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}class gk extends Er{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class fk extends Er{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function eo(s,{size:e}){if(Ig(s)>e)throw new fk({givenSize:Ig(s),maxSize:e})}function Hh(s,e={}){const{signed:t}=e;e.size&&eo(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function mk(s,e={}){return Number(Hh(s,e))}const wk=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Wh(s,e={}){return typeof s=="number"||typeof s=="bigint"?Oy(s,e):typeof s=="string"?vk(s,e):typeof s=="boolean"?yk(s,e):My(s,e)}function yk(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(eo(t,{size:e.size}),Xn(t,{size:e.size})):t}function My(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=wk[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(eo(i,{size:e.size}),Xn(i,{dir:"right",size:e.size})):i}function Oy(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const l=typeof s=="bigint"?"n":"";throw new gk({max:n?`${n}${l}`:void 0,min:`${o}${l}`,signed:t,size:i,value:`${s}${l}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?Xn(a,{size:i}):a}const bk=new TextEncoder;function vk(s,e={}){const t=bk.encode(s);return My(t,e)}const Ik=new TextEncoder;function Ek(s,e={}){return typeof s=="number"||typeof s=="bigint"?Nk(s,e):typeof s=="boolean"?Ak(s,e):ea(s)?xy(s,e):Dy(s,e)}function Ak(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(eo(t,{size:e.size}),Xn(t,{size:e.size})):t}const ci={zero:48,nine:57,A:65,F:70,a:97,f:102};function Eg(s){if(s>=ci.zero&&s<=ci.nine)return s-ci.zero;if(s>=ci.A&&s<=ci.F)return s-(ci.A-10);if(s>=ci.a&&s<=ci.f)return s-(ci.a-10)}function xy(s,e={}){let t=s;e.size&&(eo(t,{size:e.size}),t=Xn(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const l=Eg(i.charCodeAt(a++)),c=Eg(i.charCodeAt(a++));if(l===void 0||c===void 0)throw new Er(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=l*16+c}return n}function Nk(s,e){const t=Oy(s,e);return xy(t)}function Dy(s,e={}){const t=Ik.encode(s);return typeof e.size=="number"?(eo(t,{size:e.size}),Xn(t,{dir:"right",size:e.size})):t}function Pc(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function _k(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function sl(s,...e){if(!_k(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function yq(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Pc(s.outputLen),Pc(s.blockLen)}function Ag(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ck(s,e){sl(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Ha=BigInt(2**32-1),Ng=BigInt(32);function Sk(s,e=!1){return e?{h:Number(s&Ha),l:Number(s>>Ng&Ha)}:{h:Number(s>>Ng&Ha)|0,l:Number(s&Ha)|0}}function $k(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=Sk(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const Pk=(s,e,t)=>s<<t|e>>>32-t,Tk=(s,e,t)=>e<<t|s>>>32-t,Mk=(s,e,t)=>e<<t-32|s>>>64-t,Ok=(s,e,t)=>s<<t-32|e>>>64-t,tn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function xk(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function bq(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function vq(s,e){return s<<32-e|s>>>e}const _g=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Dk(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Cg(s){for(let e=0;e<s.length;e++)s[e]=Dk(s[e])}function kk(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function ky(s){return typeof s=="string"&&(s=kk(s)),sl(s),s}function Iq(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];sl(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}class jk{clone(){return this._cloneInto()}}function Rk(s){const e=i=>s().update(ky(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Eq(s=32){if(tn&&typeof tn.getRandomValues=="function")return tn.getRandomValues(new Uint8Array(s));if(tn&&typeof tn.randomBytes=="function")return tn.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const jy=[],Ry=[],Ly=[],Lk=BigInt(0),bo=BigInt(1),Uk=BigInt(2),zk=BigInt(7),Fk=BigInt(256),qk=BigInt(113);for(let s=0,e=bo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],jy.push(2*(5*i+t)),Ry.push((s+1)*(s+2)/2%64);let r=Lk;for(let n=0;n<7;n++)e=(e<<bo^(e>>zk)*qk)%Fk,e&Uk&&(r^=bo<<(bo<<BigInt(n))-bo);Ly.push(r)}const[Bk,Hk]=$k(Ly,!0),Sg=(s,e,t)=>t>32?Mk(s,e,t):Pk(s,e,t),$g=(s,e,t)=>t>32?Ok(s,e,t):Tk(s,e,t);function Wk(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,l=(o+2)%10,c=t[l],h=t[l+1],u=Sg(c,h,1)^t[a],d=$g(c,h,1)^t[a+1];for(let p=0;p<50;p+=10)s[o+p]^=u,s[o+p+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Ry[o],l=Sg(r,n,a),c=$g(r,n,a),h=jy[o];r=s[h],n=s[h+1],s[h]=l,s[h+1]=c}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=Bk[i],s[1]^=Hk[i]}t.fill(0)}class zu extends jk{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Pc(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=xk(this.state)}keccak(){_g||Cg(this.state32),Wk(this.state32,this.rounds),_g||Cg(this.state32),this.posOut=0,this.pos=0}update(e){Ag(this);const{blockLen:t,state:i}=this;e=ky(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Ag(this,!1),sl(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Pc(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ck(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:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new zu(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Vk=(s,e,t)=>Rk(()=>new zu(e,s,t)),Kk=Vk(1,136,256/8);function Uy(s,e){const t=e||"hex",i=Kk(ea(s,{strict:!1})?Ek(s):s);return t==="bytes"?i:Wh(i)}class Gk extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const Fl=new Gk(8192);function Yk(s,e){if(Fl.has(`${s}.${e}`))return Fl.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=Uy(Dy(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Fl.set(`${s}.${e}`,n),n}function Qk(s){const e=Uy(`0x${s.substring(4)}`).substring(26);return Yk(`0x${e}`)}async function Zk({hash:s,signature:e}){const t=ea(s)?s:Wh(s),{secp256k1:i}=await Vo(async()=>{const{secp256k1:o}=await import("./secp256k1-DfnLU_Rr.js");return{secp256k1:o}},__vite__mapDeps([11,1,2,5,6,7,8,9,10]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:c,s:h,v:u,yParity:d}=e,p=Number(d??u),g=Pg(p);return new i.Signature(Hh(c),Hh(h)).addRecoveryBit(g)}const o=ea(e)?e:Wh(e),a=mk(`0x${o.slice(130)}`),l=Pg(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(l)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Pg(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function Jk({hash:s,signature:e}){return Qk(await Zk({hash:s,signature:e}))}function Xk(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<s.length;c++){const h=s.charAt(c),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=c}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,u=0,d=0;const p=c.length;for(;d!==p&&c[d]===0;)d++,h++;const g=(p-d)*n+1>>>0,f=new Uint8Array(g);for(;d!==p;){let m=c[d],b=0;for(let I=g-1;(m!==0||b<u)&&I!==-1;I--,b++)m+=256*f[I]>>>0,f[I]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");u=b,d++}let y=g-u;for(;y!==g&&f[y]===0;)y++;let w=i.repeat(h);for(;y<g;++y)w+=s.charAt(f[y]);return w}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;c[h]===i;)u++,h++;const p=(c.length-h)*r+1>>>0,g=new Uint8Array(p);for(;h<c.length;){const m=c.charCodeAt(h);if(m>255)return;let b=e[m];if(b===255)return;let I=0;for(let N=p-1;(b!==0||I<d)&&N!==-1;N--,I++)b+=t*g[N]>>>0,g[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=I,h++}let f=p-d;for(;f!==p&&g[f]===0;)f++;const y=new Uint8Array(u+(p-f));let w=u;for(;f!==p;)y[w++]=g[f++];return y}function l(c){const h=a(c);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:l}}var e3="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const zy=Xk(e3);var t3={};const s3=":";function xn(s){const[e,t]=s.split(s3);return{namespace:e,reference:t}}function Fy(s,e){return s.includes(":")?[s]:e.chains||[]}const i3="ReactNative",ms={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},r3="js";function Tc(){return typeof _.process<"u"&&typeof _.process.versions<"u"&&typeof _.process.versions.node<"u"}function Yi(){return!Wi()&&!!zc()&&navigator.product===i3}function n3(){return Yi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="android"}function o3(){return Yi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="ios"}function Ia(){return!Tc()&&!!zc()&&!!Wi()}function Ea(){return Yi()?ms.reactNative:Tc()?ms.node:Ia()?ms.browser:ms.unknown}function Tg(){var s;try{return Yi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Application)<"u"?(s=_.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function a3(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function qy(){return Im()||{name:"",description:"",url:"",icons:[""]}}function c3(){if(Ea()===ms.reactNative&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"){const{OS:t,Version:i}=_.global.Platform;return[t,i].join("-")}const s=Pm();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function l3(){var s;const e=Ea();return e===ms.browser?[e,((s=Em())==null?void 0:s.host)||"unknown"].join(":"):e}function By(s,e,t){const i=c3(),r=l3();return[[s,e].join("-"),[r3,t].join("-"),i,r].join("/")}function h3({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:l}){const c=t.split("?"),h=By(s,e,i),u={auth:r,ua:h,projectId:n,useOnCloseEvent:o,packageName:l||void 0,bundleId:a||void 0},d=a3(c[1]||"",u);return c[0]+"?"+d}function pr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Vh(s){return Object.fromEntries(s.entries())}function Kh(s){return new Map(Object.entries(s))}function or(s=E.FIVE_MINUTES,e){const t=E.toMiliseconds(s||E.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,l)=>{if(o)return a(o);n=setTimeout(()=>{const c=new Error(e);o=Promise.reject(c),l(c)},t),i=a,r=l})}}function Li(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function Hy(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.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: ${s}`)}function u3(s){return Hy("topic",s)}function d3(s){return Hy("id",s)}function Wy(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function dt(s,e){return E.fromMiliseconds(Date.now()+E.toMiliseconds(s))}function Ti(s){return Date.now()>=E.toMiliseconds(s)}function Ee(s,e){return`${s}${e?`:${e}`:""}`}function hc(s=[],e=[]){return[...new Set([...s,...e])]}async function p3({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=g3(n,s,e),a=Ea();if(a===ms.browser){if(!((i=Wi())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}f3(o)}else a===ms.reactNative&&typeof(_.global==null?void 0:_.global.Linking)<"u"&&await _.global.Linking.openURL(o)}catch(r){console.error(r)}}function g3(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${b3(i,!0)}`}else r=`${r}/wc?${i}`;return r}function f3(s){let e="_self";y3()?e="_top":(w3()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function m3(s,e){let t="";try{if(Ia()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Mg(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Og(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function Fu(){return typeof _.process<"u"&&t3.IS_VITEST==="true"}function w3(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function y3(){try{return window.self!==window.top}catch{return!1}}function b3(s,e=!1){const t=_.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Vy(s){return _.Buffer.from(s,"base64").toString("utf-8")}function v3(s){return new Promise(e=>setTimeout(e,s))}function ta(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function I3(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function il(s,...e){if(!I3(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function qu(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ta(s.outputLen),ta(s.blockLen)}function zn(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ky(s,e){il(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Wa=BigInt(2**32-1),xg=BigInt(32);function E3(s,e=!1){return e?{h:Number(s&Wa),l:Number(s>>xg&Wa)}:{h:Number(s>>xg&Wa)|0,l:Number(s&Wa)|0}}function A3(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=E3(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const N3=(s,e,t)=>s<<t|e>>>32-t,_3=(s,e,t)=>e<<t|s>>>32-t,C3=(s,e,t)=>e<<t-32|s>>>64-t,S3=(s,e,t)=>s<<t-32|e>>>64-t,sn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function $3(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function ql(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Gs(s,e){return s<<32-e|s>>>e}const Dg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function P3(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function kg(s){for(let e=0;e<s.length;e++)s[e]=P3(s[e])}function T3(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Fn(s){return typeof s=="string"&&(s=T3(s)),il(s),s}let Bu=class{clone(){return this._cloneInto()}};function Gy(s){const e=i=>s().update(Fn(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Aa(s=32){if(sn&&typeof sn.getRandomValues=="function")return sn.getRandomValues(new Uint8Array(s));if(sn&&typeof sn.randomBytes=="function")return sn.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Yy=[],Qy=[],Zy=[],M3=BigInt(0),vo=BigInt(1),O3=BigInt(2),x3=BigInt(7),D3=BigInt(256),k3=BigInt(113);for(let s=0,e=vo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Yy.push(2*(5*i+t)),Qy.push((s+1)*(s+2)/2%64);let r=M3;for(let n=0;n<7;n++)e=(e<<vo^(e>>x3)*k3)%D3,e&O3&&(r^=vo<<(vo<<BigInt(n))-vo);Zy.push(r)}const[j3,R3]=A3(Zy,!0),jg=(s,e,t)=>t>32?C3(s,e,t):N3(s,e,t),Rg=(s,e,t)=>t>32?S3(s,e,t):_3(s,e,t);function L3(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,l=(o+2)%10,c=t[l],h=t[l+1],u=jg(c,h,1)^t[a],d=Rg(c,h,1)^t[a+1];for(let p=0;p<50;p+=10)s[o+p]^=u,s[o+p+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Qy[o],l=jg(r,n,a),c=Rg(r,n,a),h=Yy[o];r=s[h],n=s[h+1],s[h]=l,s[h+1]=c}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=j3[i],s[1]^=R3[i]}t.fill(0)}let U3=class Jy extends Bu{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ta(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=$3(this.state)}keccak(){Dg||kg(this.state32),L3(this.state32,this.rounds),Dg||kg(this.state32),this.posOut=0,this.pos=0}update(e){zn(this);const{blockLen:t,state:i}=this;e=Fn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){zn(this,!1),il(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ta(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ky(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:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Jy(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const z3=(s,e,t)=>Gy(()=>new U3(e,s,t)),F3=z3(1,136,256/8),q3="https://rpc.walletconnect.org/v1";function Xy(s){const e=`Ethereum Signed Message:
12
+ Approved: ${d.toString()}`))}),o.forEach(u=>{i||(dr(r[u].methods,n[u].methods)?dr(r[u].events,n[u].events)||(i=k("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):i=k("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),i}function pA(s){const e={};return Object.keys(s).forEach(t=>{var i;t.includes(":")?e[t]=s[t]:(i=s[t].chains)==null||i.forEach(r=>{e[r]={methods:s[t].methods,events:s[t].events}})}),e}function ap(s){return[...new Set(s.map(e=>e.includes(":")?e.split(":")[0]:e))]}function gA(s){const e={};return Object.keys(s).forEach(t=>{if(t.includes(":"))e[t]=s[t];else{const i=Qn(s[t].accounts);i==null||i.forEach(r=>{e[r]={accounts:s[t].accounts.filter(n=>n.includes(`${r}:`)),methods:s[t].methods,events:s[t].events}})}}),e}function fA(s,e){return xu(s,!1)&&s<=e.max&&s>=e.min}function cp(){const s=ga();return new Promise(e=>{switch(s){case fs.browser:e(mA());break;case fs.reactNative:e(wA());break;case fs.node:e(yA());break;default:e(!0)}})}function mA(){return pa()&&(navigator==null?void 0:navigator.onLine)}async function wA(){if(Gi()&&typeof _.global<"u"&&_.global!=null&&_.global.NetInfo){const s=await(_.global==null?void 0:_.global.NetInfo.fetch());return s==null?void 0:s.isConnected}return!0}function yA(){return!0}function bA(s){switch(ga()){case fs.browser:vA(s);break;case fs.reactNative:IA(s);break}}function vA(s){!Gi()&&pa()&&(window.addEventListener("online",()=>s(!0)),window.addEventListener("offline",()=>s(!1)))}function IA(s){var e;Gi()&&typeof _.global<"u"&&_.global!=null&&_.global.NetInfo&&((e=_.global)==null||e.NetInfo.addEventListener(t=>s(t==null?void 0:t.isConnected)))}const El={};let co=class{static get(e){return El[e]}static set(e,t){El[e]=t}static delete(e){delete El[e]}},Ye=class extends yv{constructor(e){super(e),this.events=new kt.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(Gt(e.method,e.params||[],e.id||gs().toString()),t)}async requestStrict(e,t){return new Promise(async(i,r)=>{if(!this.connection.connected)try{await this.open()}catch(n){r(n)}this.events.on(`${e.id}`,n=>{st(n)?r(n.error):i(n.result)});try{await this.connection.send(e,t)}catch(n){r(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),$r(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const EA=()=>typeof WebSocket<"u"?WebSocket:typeof _.global<"u"&&typeof _.global.WebSocket<"u"?_.global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),AA=()=>typeof WebSocket<"u"||typeof _.global<"u"&&typeof _.global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",lp=s=>s.split("?")[0],hp=10,NA=EA();let Ow=class{constructor(e){if(this.url=e,this.events=new kt.EventEmitter,this.registering=!1,!od(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,t)=>{if(typeof this.socket>"u"){t(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Sr(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!od(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,r)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),r(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return r(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,i)=>{const r=bv.isReactNative()?void 0:{rejectUnauthorized:!vv(e)},n=new NA(e,[],r);AA()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),t(n)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?wi(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),r=i.message||i.toString(),n=ca(e,r);this.events.emit("payload",n)}parseError(e,t=this.url){return Iv(e,lp(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>hp&&this.events.setMaxListeners(hp)}emitError(e){const t=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${lp(this.url)}`));return this.events.emit("register_error",t),t}};const xw="wc",Dw=2,Sh="core",si=`${xw}@2:${Sh}:`,_A={logger:"error"},CA={database:":memory:"},SA="crypto",up="client_ed25519_seed",$A=E.ONE_DAY,PA="keychain",TA="0.3",MA="messages",OA="0.3",dp=E.SIX_HOURS,xA="publisher",kw="irn",DA="error",jw="wss://relay.walletconnect.org",kA="relayer",It={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},jA="_subscription",Is={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},RA=.1,$h="2.19.0",Ve={link_mode:"link_mode",relay:"relay"},LA="0.3",UA="WALLETCONNECT_CLIENT_ID",pp="WALLETCONNECT_LINK_MODE_APPS",hs={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},zA="subscription",FA="0.3",qA=E.FIVE_SECONDS*1e3,BA="pairing",HA="0.3",lo={wc_pairingDelete:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:E.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:E.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:E.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:E.ONE_DAY,prompt:!1,tag:0},res:{ttl:E.ONE_DAY,prompt:!1,tag:0}}},cr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Os={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},WA="history",VA="0.3",KA="expirer",Cs={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},GA="0.3",YA="verify-api",QA="https://verify.walletconnect.com",Rw="https://verify.walletconnect.org",Ro=Rw,ZA=`${Ro}/v3`,JA=[QA,Rw],XA="echo",eN="https://echo.walletconnect.com",Zs={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},hi={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"},xs={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"},Xi={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"},er={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},ho={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},tN=.1,sN="event-client",iN=86400,rN="https://pulse.walletconnect.org/batch";function nN(s,e){if(s.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var r=0;r<s.length;r++){var n=s.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=s.length,l=s.charAt(0),c=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var f=0,y=0,w=0,m=g.length;w!==m&&g[w]===0;)w++,f++;for(var b=(m-w)*h+1>>>0,I=new Uint8Array(b);w!==m;){for(var N=g[w],$=0,P=b-1;(N!==0||$<y)&&P!==-1;P--,$++)N+=256*I[P]>>>0,I[P]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");y=$,w++}for(var O=b-y;O!==b&&I[O]===0;)O++;for(var C=l.repeat(f);O<b;++O)C+=s.charAt(I[O]);return C}function d(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var f=0;if(g[f]!==" "){for(var y=0,w=0;g[f]===l;)y++,f++;for(var m=(g.length-f)*c+1>>>0,b=new Uint8Array(m);g[f];){var I=t[g.charCodeAt(f)];if(I===255)return;for(var N=0,$=m-1;(I!==0||N<w)&&$!==-1;$--,N++)I+=a*b[$]>>>0,b[$]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");w=N,f++}if(g[f]!==" "){for(var P=m-w;P!==m&&b[P]===0;)P++;for(var O=new Uint8Array(y+(m-P)),C=y;P!==m;)O[C++]=b[P++];return O}}}function p(g){var f=d(g);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:p}}var oN=nN,aN=oN;const Lw=s=>{if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);throw new Error("Unknown type, must be binary type")},cN=s=>new TextEncoder().encode(s),lN=s=>new TextDecoder().decode(s);let hN=class{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},uN=class{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Uw(this,e)}},dN=class{constructor(e){this.decoders=e}or(e){return Uw(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Uw=(s,e)=>new dN({...s.decoders||{[s.prefix]:s},...e.decoders||{[e.prefix]:e}});let pN=class{constructor(e,t,i,r){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=r,this.encoder=new hN(e,t,i),this.decoder=new uN(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Vc=({name:s,prefix:e,encode:t,decode:i})=>new pN(s,e,t,i),ya=({prefix:s,name:e,alphabet:t})=>{const{encode:i,decode:r}=aN(t,e);return Vc({prefix:s,name:e,encode:i,decode:n=>Lw(r(n))})},gN=(s,e,t,i)=>{const r={};for(let h=0;h<e.length;++h)r[e[h]]=h;let n=s.length;for(;s[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,l=0,c=0;for(let h=0;h<n;++h){const u=r[s[h]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);l=l<<t|u,a+=t,a>=8&&(a-=8,o[c++]=255&l>>a)}if(a>=t||255&l<<8-a)throw new SyntaxError("Unexpected end of data");return o},fN=(s,e,t)=>{const i=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Rt=({name:s,prefix:e,bitsPerChar:t,alphabet:i})=>Vc({prefix:e,name:s,encode(r){return fN(r,i,t)},decode(r){return gN(r,i,t,s)}}),mN=Vc({prefix:"\0",name:"identity",encode:s=>lN(s),decode:s=>cN(s)});var wN=Object.freeze({__proto__:null,identity:mN});const yN=Rt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var bN=Object.freeze({__proto__:null,base2:yN});const vN=Rt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var IN=Object.freeze({__proto__:null,base8:vN});const EN=ya({prefix:"9",name:"base10",alphabet:"0123456789"});var AN=Object.freeze({__proto__:null,base10:EN});const NN=Rt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_N=Rt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var CN=Object.freeze({__proto__:null,base16:NN,base16upper:_N});const SN=Rt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$N=Rt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),PN=Rt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),TN=Rt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),MN=Rt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ON=Rt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xN=Rt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),DN=Rt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),kN=Rt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var jN=Object.freeze({__proto__:null,base32:SN,base32upper:$N,base32pad:PN,base32padupper:TN,base32hex:MN,base32hexupper:ON,base32hexpad:xN,base32hexpadupper:DN,base32z:kN});const RN=ya({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),LN=ya({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var UN=Object.freeze({__proto__:null,base36:RN,base36upper:LN});const zN=ya({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),FN=ya({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qN=Object.freeze({__proto__:null,base58btc:zN,base58flickr:FN});const BN=Rt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),HN=Rt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),WN=Rt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),VN=Rt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var KN=Object.freeze({__proto__:null,base64:BN,base64pad:HN,base64url:WN,base64urlpad:VN});const zw=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),GN=zw.reduce((s,e,t)=>(s[t]=e,s),[]),YN=zw.reduce((s,e,t)=>(s[e.codePointAt(0)]=t,s),[]);function QN(s){return s.reduce((e,t)=>(e+=GN[t],e),"")}function ZN(s){const e=[];for(const t of s){const i=YN[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const JN=Vc({prefix:"🚀",name:"base256emoji",encode:QN,decode:ZN});var XN=Object.freeze({__proto__:null,base256emoji:JN}),e_=Fw,gp=128,t_=-128,s_=Math.pow(2,31);function Fw(s,e,t){e=e||[],t=t||0;for(var i=t;s>=s_;)e[t++]=s&255|gp,s/=128;for(;s&t_;)e[t++]=s&255|gp,s>>>=7;return e[t]=s|0,Fw.bytes=t-i+1,e}var i_=Ph,r_=128,fp=127;function Ph(s,i){var t=0,i=i||0,r=0,n=i,o,a=s.length;do{if(n>=a)throw Ph.bytes=0,new RangeError("Could not decode varint");o=s[n++],t+=r<28?(o&fp)<<r:(o&fp)*Math.pow(2,r),r+=7}while(o>=r_);return Ph.bytes=n-i,t}var n_=Math.pow(2,7),o_=Math.pow(2,14),a_=Math.pow(2,21),c_=Math.pow(2,28),l_=Math.pow(2,35),h_=Math.pow(2,42),u_=Math.pow(2,49),d_=Math.pow(2,56),p_=Math.pow(2,63),g_=function(s){return s<n_?1:s<o_?2:s<a_?3:s<c_?4:s<l_?5:s<h_?6:s<u_?7:s<d_?8:s<p_?9:10},f_={encode:e_,decode:i_,encodingLength:g_},qw=f_;const mp=(s,e,t=0)=>(qw.encode(s,e,t),e),wp=s=>qw.encodingLength(s),Th=(s,e)=>{const t=e.byteLength,i=wp(s),r=i+wp(t),n=new Uint8Array(r+t);return mp(s,n,0),mp(t,n,i),n.set(e,r),new m_(s,t,e,n)};let m_=class{constructor(e,t,i,r){this.code=e,this.size=t,this.digest=i,this.bytes=r}};const Bw=({name:s,code:e,encode:t})=>new w_(s,e,t);let w_=class{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Th(this.code,t):t.then(i=>Th(this.code,i))}else throw Error("Unknown type, must be binary type")}};const Hw=s=>async e=>new Uint8Array(await crypto.subtle.digest(s,e)),y_=Bw({name:"sha2-256",code:18,encode:Hw("SHA-256")}),b_=Bw({name:"sha2-512",code:19,encode:Hw("SHA-512")});var v_=Object.freeze({__proto__:null,sha256:y_,sha512:b_});const Ww=0,I_="identity",Vw=Lw,E_=s=>Th(Ww,Vw(s)),A_={code:Ww,name:I_,encode:Vw,digest:E_};var N_=Object.freeze({__proto__:null,identity:A_});new TextEncoder,new TextDecoder;const yp={...wN,...bN,...IN,...AN,...CN,...jN,...UN,...qN,...KN,...XN};({...v_,...N_});function __(s=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(s):new Uint8Array(s)}function Kw(s,e,t,i){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:i}}}const bp=Kw("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),Al=Kw("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);const e=__(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),C_={utf8:bp,"utf-8":bp,hex:yp.base16,latin1:Al,ascii:Al,binary:Al,...yp};function S_(s,e="utf8"){const t=C_[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(s,"utf8"):t.decoder.decode(`${t.prefix}${s}`)}var $_=Object.defineProperty,P_=(s,e,t)=>e in s?$_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Hs=(s,e,t)=>P_(s,typeof e!="symbol"?e+"":e,t);let T_=class{constructor(e,t){this.core=e,this.logger=t,Hs(this,"keychain",new Map),Hs(this,"name",PA),Hs(this,"version",TA),Hs(this,"initialized",!1),Hs(this,"storagePrefix",si),Hs(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Hs(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Hs(this,"set",async(i,r)=>{this.isInitialized(),this.keychain.set(i,r),await this.persist()}),Hs(this,"get",i=>{this.isInitialized();const r=this.keychain.get(i);if(typeof r>"u"){const{message:n}=k("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return r}),Hs(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Ne(t,this.name)}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,sw(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?iw(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var M_=Object.defineProperty,O_=(s,e,t)=>e in s?M_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ct=(s,e,t)=>O_(s,typeof e!="symbol"?e+"":e,t);let x_=class{constructor(e,t,i){this.core=e,this.logger=t,Ct(this,"name",SA),Ct(this,"keychain"),Ct(this,"randomSessionIdentifier",Ch()),Ct(this,"initialized",!1),Ct(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ct(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ct(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=vc(r);return $m(n.publicKey)}),Ct(this,"generateKeyPair",()=>{this.isInitialized();const r=CE();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ct(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=vc(n),a=this.randomSessionIdentifier;return await Pm(a,r,$A,o)}),Ct(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),l=SE(a,n);return this.setSymKey(l,o)}),Ct(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||nc(r);return await this.keychain.set(o,r),o}),Ct(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ct(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ct(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Pw(o),l=Sr(n);if(ep(a))return TE(l,o==null?void 0:o.encoding);if(Xd(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;r=await this.generateSharedKey(d,p)}const c=this.getSymKey(r),{type:h,senderPublicKey:u}=a;return $E({type:h,symKey:c,message:l,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Ct(this,"decode",async(r,n,o)=>{this.isInitialized();const a=OE(n,o);if(ep(a)){const l=ME(n,o==null?void 0:o.encoding);return wi(l)}if(Xd(a)){const l=a.receiverPublicKey,c=a.senderPublicKey;r=await this.generateSharedKey(l,c)}try{const l=this.getSymKey(r),c=PE({symKey:l,encoded:n,encoding:o==null?void 0:o.encoding});return wi(c)}catch(l){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(l)}}),Ct(this,"getPayloadType",(r,n=ji)=>{const o=Zo({encoded:r,encoding:n});return br(o.type)}),Ct(this,"getPayloadSenderPublicKey",(r,n=ji)=>{const o=Zo({encoded:r,encoding:n});return o.senderPublicKey?Ae(o.senderPublicKey,Bt):void 0}),this.core=e,this.logger=Ne(t,this.name),this.keychain=i||new T_(this.core,this.logger)}get context(){return qe(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(up)}catch{e=Ch(),await this.keychain.set(up,e)}return S_(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var D_=Object.defineProperty,k_=(s,e,t)=>e in s?D_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ws=(s,e,t)=>k_(s,typeof e!="symbol"?e+"":e,t);let j_=class extends N0{constructor(e,t){super(e,t),this.logger=e,this.core=t,Ws(this,"messages",new Map),Ws(this,"name",MA),Ws(this,"version",OA),Ws(this,"initialized",!1),Ws(this,"storagePrefix",si),Ws(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),Ws(this,"set",async(i,r)=>{this.isInitialized();const n=di(r);let o=this.messages.get(i);return typeof o>"u"&&(o={}),typeof o[n]<"u"||(o[n]=r,this.messages.set(i,o),await this.persist()),n}),Ws(this,"get",i=>{this.isInitialized();let r=this.messages.get(i);return typeof r>"u"&&(r={}),r}),Ws(this,"has",(i,r)=>{this.isInitialized();const n=this.get(i),o=di(r);return typeof n[o]<"u"}),Ws(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()}),this.logger=Ne(e,this.name),this.core=t}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,sw(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?iw(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var R_=Object.defineProperty,L_=Object.defineProperties,U_=Object.getOwnPropertyDescriptors,vp=Object.getOwnPropertySymbols,z_=Object.prototype.hasOwnProperty,F_=Object.prototype.propertyIsEnumerable,Mh=(s,e,t)=>e in s?R_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ja=(s,e)=>{for(var t in e||(e={}))z_.call(e,t)&&Mh(s,t,e[t]);if(vp)for(var t of vp(e))F_.call(e,t)&&Mh(s,t,e[t]);return s},Nl=(s,e)=>L_(s,U_(e)),Ds=(s,e,t)=>Mh(s,typeof e!="symbol"?e+"":e,t);let q_=class extends _0{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Ds(this,"events",new kt.EventEmitter),Ds(this,"name",xA),Ds(this,"queue",new Map),Ds(this,"publishTimeout",E.toMiliseconds(E.ONE_MINUTE)),Ds(this,"initialPublishTimeout",E.toMiliseconds(E.ONE_SECOND*15)),Ds(this,"needsTransportRestart",!1),Ds(this,"publish",async(i,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:r,opts:n}});const a=(n==null?void 0:n.ttl)||dp,l=_c(n),c=(n==null?void 0:n.prompt)||!1,h=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||gs().toString(),d={topic:i,message:r,opts:{ttl:a,relay:l,prompt:c,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},p=`Failed to publish payload, please try again. id:${u} tag:${h}`;try{const g=new Promise(async f=>{const y=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(It.publish,y),f(d))};this.relayer.events.on(It.publish,y);const w=ki(new Promise((m,b)=>{this.rpcPublish({topic:i,message:r,ttl:a,prompt:c,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(m).catch(I=>{this.logger.warn(I,I==null?void 0:I.message),b(I)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${h}`);try{await w,this.events.removeListener(It.publish,y)}catch(m){this.queue.set(u,Nl(ja({},d),{attempt:1})),this.logger.warn(m,m==null?void 0:m.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:i,message:r,opts:n}}),await ki(g,this.publishTimeout,p)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(u)}}),Ds(this,"on",(i,r)=>{this.events.on(i,r)}),Ds(this,"once",(i,r)=>{this.events.once(i,r)}),Ds(this,"off",(i,r)=>{this.events.off(i,r)}),Ds(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.relayer=e,this.logger=Ne(t,this.name),this.registerEventListeners()}get context(){return qe(this.logger)}async rpcPublish(e){var t,i,r,n;const{topic:o,message:a,ttl:l=dp,prompt:c,tag:h,id:u,attestation:d,tvf:p}=e,g={method:$o(_c().protocol).publish,params:ja({topic:o,message:a,ttl:l,prompt:c,tag:h,attestation:d},p),id:u};Kt((t=g.params)==null?void 0:t.prompt)&&((i=g.params)==null||delete i.prompt),Kt((r=g.params)==null?void 0:r.tag)&&((n=g.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const f=await this.relayer.request(g);return this.relayer.events.emit(It.publish,e),this.logger.debug("Successfully Published Payload"),f}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,Nl(ja({},e),{attempt:i}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Nl(ja({},e),{topic:r,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(qs.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(It.connection_stalled);return}this.checkQueue()}),this.relayer.on(It.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}};var B_=Object.defineProperty,H_=(s,e,t)=>e in s?B_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Fr=(s,e,t)=>H_(s,typeof e!="symbol"?e+"":e,t);let W_=class{constructor(){Fr(this,"map",new Map),Fr(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),Fr(this,"get",e=>this.map.get(e)||[]),Fr(this,"exists",(e,t)=>this.get(e).includes(t)),Fr(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const r=i.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),Fr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}};var V_=Object.defineProperty,K_=Object.defineProperties,G_=Object.getOwnPropertyDescriptors,Ip=Object.getOwnPropertySymbols,Y_=Object.prototype.hasOwnProperty,Q_=Object.prototype.propertyIsEnumerable,Oh=(s,e,t)=>e in s?V_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,uo=(s,e)=>{for(var t in e||(e={}))Y_.call(e,t)&&Oh(s,t,e[t]);if(Ip)for(var t of Ip(e))Q_.call(e,t)&&Oh(s,t,e[t]);return s},_l=(s,e)=>K_(s,G_(e)),Pe=(s,e,t)=>Oh(s,typeof e!="symbol"?e+"":e,t);let Z_=class extends $0{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Pe(this,"subscriptions",new Map),Pe(this,"topicMap",new W_),Pe(this,"events",new kt.EventEmitter),Pe(this,"name",zA),Pe(this,"version",FA),Pe(this,"pending",new Map),Pe(this,"cached",[]),Pe(this,"initialized",!1),Pe(this,"pendingSubscriptionWatchLabel","pending_sub_watch_label"),Pe(this,"pollingInterval",20),Pe(this,"storagePrefix",si),Pe(this,"subscribeTimeout",E.toMiliseconds(E.ONE_MINUTE)),Pe(this,"initialSubscribeTimeout",E.toMiliseconds(E.ONE_SECOND*15)),Pe(this,"clientId"),Pe(this,"batchSubscribeTopicsLimit",500),Pe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Pe(this,"subscribe",async(i,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}});try{const n=_c(r),o={topic:i,relay:n,transportType:r==null?void 0:r.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,r);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),Pe(this,"unsubscribe",async(i,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(i,r.id,r):await this.unsubscribeByTopic(i,r)}),Pe(this,"isSubscribed",async i=>{if(this.topics.includes(i))return!0;const r=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((n,o)=>{const a=new E.Watch;a.start(r);const l=setInterval(()=>{(!this.pending.has(i)&&this.topics.includes(i)||this.cached.some(c=>c.topic===i))&&(clearInterval(l),a.stop(r),n(!0)),a.elapsed(r)>=qA&&(clearInterval(l),a.stop(r),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)}),Pe(this,"on",(i,r)=>{this.events.on(i,r)}),Pe(this,"once",(i,r)=>{this.events.once(i,r)}),Pe(this,"off",(i,r)=>{this.events.off(i,r)}),Pe(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),Pe(this,"start",async()=>{await this.onConnect()}),Pe(this,"stop",async()=>{await this.onDisconnect()}),Pe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Pe(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(r=>{i.push(r)}),await this.batchSubscribe(i)}),Pe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(qs.pulse,async()=>{await this.checkPending()}),this.events.on(hs.created,async i=>{const r=hs.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()}),this.events.on(hs.deleted,async i=>{const r=hs.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()})}),this.relayer=e,this.logger=Ne(t,this.name),this.clientId=""}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const r=_c(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Te("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,i){var r;(!i||(i==null?void 0:i.transportType)===Ve.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:$o(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=i==null?void 0:i.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===Ve.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(h=>this.logger.warn(h))},E.toMiliseconds(E.ONE_SECOND)),a;const l=new Promise(async h=>{const u=d=>{d.topic===e&&(this.events.removeListener(hs.created,u),h(d.id))};this.events.on(hs.created,u);try{const d=await ki(new Promise((p,g)=>{this.relayer.request(n).catch(f=>{this.logger.warn(f,f==null?void 0:f.message),g(f)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(hs.created,u),h(d)}catch{}}),c=await ki(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!c&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return c?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(It.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:$o(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await ki(new Promise(r=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(It.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:$o(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let r;try{r=await await ki(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(It.connection_stalled)}return r}rpcUnsubscribe(e,t,i){const r={method:$o(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,_l(uo({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,uo({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,uo({},t)),this.topicMap.set(t.topic,e),this.events.emit(hs.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=k("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(hs.deleted,_l(uo({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(hs.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(hs.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=k("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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 t=>_l(uo({},t),{id:await this.getSubscriptionId(t.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await zI(E.toMiliseconds(E.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=k("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 di(e+await this.getClientId())}};var J_=Object.defineProperty,Ep=Object.getOwnPropertySymbols,X_=Object.prototype.hasOwnProperty,eC=Object.prototype.propertyIsEnumerable,xh=(s,e,t)=>e in s?J_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ap=(s,e)=>{for(var t in e||(e={}))X_.call(e,t)&&xh(s,t,e[t]);if(Ep)for(var t of Ep(e))eC.call(e,t)&&xh(s,t,e[t]);return s},pe=(s,e,t)=>xh(s,typeof e!="symbol"?e+"":e,t);let tC=class extends C0{constructor(e){super(e),pe(this,"protocol","wc"),pe(this,"version",2),pe(this,"core"),pe(this,"logger"),pe(this,"events",new kt.EventEmitter),pe(this,"provider"),pe(this,"messages"),pe(this,"subscriber"),pe(this,"publisher"),pe(this,"name",kA),pe(this,"transportExplicitlyClosed",!1),pe(this,"initialized",!1),pe(this,"connectionAttemptInProgress",!1),pe(this,"relayUrl"),pe(this,"projectId"),pe(this,"packageName"),pe(this,"bundleId"),pe(this,"hasExperiencedNetworkDisruption",!1),pe(this,"pingTimeout"),pe(this,"heartBeatTimeout",E.toMiliseconds(E.THIRTY_SECONDS+E.FIVE_SECONDS)),pe(this,"reconnectTimeout"),pe(this,"connectPromise"),pe(this,"reconnectInProgress",!1),pe(this,"requestsInFlight",[]),pe(this,"connectTimeout",E.toMiliseconds(E.ONE_SECOND*15)),pe(this,"request",async t=>{var i,r;this.logger.debug("Publishing Request Payload");const n=t.id||gs().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((r=t.params)==null?void 0:r.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),pe(this,"resetPingTimeout",()=>{if(Ac())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,r;this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(r=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null||r.terminate()},this.heartBeatTimeout)}catch(t){this.logger.warn(t,t==null?void 0:t.message)}}),pe(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),pe(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(It.connect)}),pe(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),pe(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(It.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),pe(this,"registerProviderListeners",()=>{this.provider.on(Is.payload,this.onPayloadHandler),this.provider.on(Is.connect,this.onConnectHandler),this.provider.on(Is.disconnect,this.onDisconnectHandler),this.provider.on(Is.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ne(e.logger,this.name):Wn(yi({level:e.logger||DA})),this.messages=new j_(this.logger,e.core),this.subscriber=new Z_(this,this.logger),this.publisher=new q_(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||jw,this.projectId=e.projectId,_I()?this.packageName=Cd():CI()&&(this.bundleId=Cd()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return qe(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Ve.relay})}async subscribe(e,t){var i,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=t==null?void 0:t.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(r=t==null?void 0:t.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",l;const c=h=>{h.topic===e&&(this.subscriber.off(hs.created,c),l())};return await Promise.all([new Promise(h=>{l=h,this.subscriber.on(hs.created,c)}),new Promise(async(h,u)=>{a=await this.subscriber.subscribe(e,Ap({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&u(d)})||a,h()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await ki(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(t,i)=>{await this.connect(e).then(t).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await cp())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,r)=>i.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+(r==null?void 0:r.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const r=ut(E.FIVE_MINUTES),n={topic:i,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(It.message,e),await this.recordMessageEvent(e)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Is.disconnect,n),await ki(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off(Is.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const l=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Is.disconnect,l),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Is.disconnect,l)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const r=i;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(i=>setTimeout(i,E.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,r,n;if(Ac())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(i=this.provider)==null?void 0:i.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ye(new Ow(TI({sdkVersion:$h,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){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.warn(`Ignoring message for non-subscribed topic ${t}`),!0;const r=this.messages.has(t,i);return r&&this.logger.warn(`Ignoring duplicate message: ${i}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Vn(e)){if(!e.method.endsWith(jA))return;const t=e.params,{topic:i,message:r,publishedAt:n,attestation:o}=t.data,a={topic:i,message:r,publishedAt:n,transportType:Ve.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Ap({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else $r(e)&&this.events.emit(It.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(It.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=Wi(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Is.payload,this.onPayloadHandler),this.provider.off(Is.connect,this.onConnectHandler),this.provider.off(Is.disconnect,this.onDisconnectHandler),this.provider.off(Is.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await cp();bA(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(It.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},E.toMiliseconds(RA)))))}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}};var sC=Object.defineProperty,Np=Object.getOwnPropertySymbols,iC=Object.prototype.hasOwnProperty,rC=Object.prototype.propertyIsEnumerable,Dh=(s,e,t)=>e in s?sC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,_p=(s,e)=>{for(var t in e||(e={}))iC.call(e,t)&&Dh(s,t,e[t]);if(Np)for(var t of Np(e))rC.call(e,t)&&Dh(s,t,e[t]);return s},Qt=(s,e,t)=>Dh(s,typeof e!="symbol"?e+"":e,t);let Tr=class extends S0{constructor(e,t,i,r=si,n=void 0){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,Qt(this,"map",new Map),Qt(this,"version",LA),Qt(this,"cached",[]),Qt(this,"initialized",!1),Qt(this,"getKey"),Qt(this,"storagePrefix",si),Qt(this,"recentlyDeleted",[]),Qt(this,"recentlyDeletedLimit",200),Qt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Kt(o)?this.map.set(this.getKey(o),o):QE(o)?this.map.set(o.id,o):ZE(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Qt(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())}),Qt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Qt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(l=>Ev(a[l],o[l]))):this.values)),Qt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const l=_p(_p({},this.getData(o)),a);this.map.set(o,l),await this.persist()}),Qt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Ne(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=k("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:i}=k("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=k("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var nC=Object.defineProperty,oC=(s,e,t)=>e in s?nC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ae=(s,e,t)=>oC(s,typeof e!="symbol"?e+"":e,t);let aC=class{constructor(e,t){this.core=e,this.logger=t,ae(this,"name",BA),ae(this,"version",HA),ae(this,"events",new Kn),ae(this,"pairings"),ae(this,"initialized",!1),ae(this,"storagePrefix",si),ae(this,"ignoredPayloadTypes",[gi]),ae(this,"registeredMethods",[]),ae(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ae(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),ae(this,"create",async i=>{this.isInitialized();const r=Ch(),n=await this.core.crypto.setSymKey(r),o=ut(E.FIVE_MINUTES),a={protocol:kw},l={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},c=sp({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(cr.create,l),this.core.expirer.set(n,o),await this.pairings.set(n,l),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:c}}),ae(this,"pair",async i=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[Zs.pairing_started]}});this.isValidPair(i,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:l,methods:c}=tp(i.uri);r.props.properties.topic=n,r.addTrace(Zs.pairing_uri_validation_success),r.addTrace(Zs.pairing_uri_not_expired);let h;if(this.pairings.keys.includes(n)){if(h=this.pairings.get(n),r.addTrace(Zs.existing_pairing),h.active)throw r.setError(hi.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(Zs.pairing_not_expired)}const u=l||ut(E.FIVE_MINUTES),d={topic:n,relay:a,expiry:u,active:!1,methods:c};this.core.expirer.set(n,u),await this.pairings.set(n,d),r.addTrace(Zs.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(cr.create,d),r.addTrace(Zs.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(Zs.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(hi.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw r.setError(hi.subscribe_pairing_topic_failure),p}return r.addTrace(Zs.subscribe_pairing_topic_success),d}),ae(this,"activate",async({topic:i})=>{this.isInitialized();const r=ut(E.FIVE_MINUTES);this.core.expirer.set(i,r),await this.pairings.update(i,{active:!0,expiry:r})}),ae(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=i;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:l}=rr();this.events.once(Ie("pairing_ping",n),({error:c})=>{c?l(c):a()}),await o()}}),ae(this,"updateExpiry",async({topic:i,expiry:r})=>{this.isInitialized(),await this.pairings.update(i,{expiry:r})}),ae(this,"updateMetadata",async({topic:i,metadata:r})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:r})}),ae(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ae(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:r}=i;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Te("USER_DISCONNECTED")),await this.deletePairing(r))}),ae(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=i,l=this.core.crypto.keychain.get(r);return sp({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:l,relay:n,expiryTimestamp:o,methods:a})}),ae(this,"sendRequest",async(i,r,n)=>{const o=Gt(r,n),a=await this.core.crypto.encode(i,o),l=lo[r].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,l),o.id}),ae(this,"sendResult",async(i,r,n)=>{const o=Wi(i,n),a=await this.core.crypto.encode(r,o),l=(await this.core.history.get(r,i)).request.method,c=lo[l].res;await this.core.relayer.publish(r,a,c),await this.core.history.resolve(o)}),ae(this,"sendError",async(i,r,n)=>{const o=ca(i,n),a=await this.core.crypto.encode(r,o),l=(await this.core.history.get(r,i)).request.method,c=lo[l]?lo[l].res:lo.unregistered_method.res;await this.core.relayer.publish(r,a,c),await this.core.history.resolve(o)}),ae(this,"deletePairing",async(i,r)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Te("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),r?Promise.resolve():this.core.expirer.del(i)])}),ae(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(r=>Si(r.expiry));await Promise.all(i.map(r=>this.deletePairing(r.topic)))}),ae(this,"onRelayEventRequest",i=>{const{topic:r,payload:n}=i;switch(n.method){case"wc_pairingPing":return this.onPairingPingRequest(r,n);case"wc_pairingDelete":return this.onPairingDeleteRequest(r,n);default:return this.onUnknownRpcMethodRequest(r,n)}}),ae(this,"onRelayEventResponse",async i=>{const{topic:r,payload:n}=i,o=(await this.core.history.get(r,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,n);default:return this.onUnknownRpcMethodResponse(o)}}),ae(this,"onPairingPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(cr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),ae(this,"onPairingPingResponse",(i,r)=>{const{id:n}=r;setTimeout(()=>{vt(r)?this.events.emit(Ie("pairing_ping",n),{}):st(r)&&this.events.emit(Ie("pairing_ping",n),{error:r.error})},500)}),ae(this,"onPairingDeleteRequest",async(i,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(cr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),ae(this,"onUnknownRpcMethodRequest",async(i,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Te("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),ae(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(Te("WC_METHOD_UNSUPPORTED",i))}),ae(this,"isValidPair",(i,r)=>{var n;if(!is(i)){const{message:a}=k("MISSING_OR_INVALID",`pair() params: ${i}`);throw r.setError(hi.malformed_pairing_uri),new Error(a)}if(!YE(i.uri)){const{message:a}=k("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw r.setError(hi.malformed_pairing_uri),new Error(a)}const o=tp(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=k("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(hi.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=k("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(hi.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&E.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(hi.pairing_expired);const{message:a}=k("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ae(this,"isValidPing",async i=>{if(!is(i)){const{message:n}=k("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),ae(this,"isValidDisconnect",async i=>{if(!is(i)){const{message:n}=k("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),ae(this,"isValidPairingTopic",async i=>{if(!it(i,!1)){const{message:r}=k("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(r)}if(!this.pairings.keys.includes(i)){const{message:r}=k("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(r)}if(Si(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:r}=k("EXPIRED",`pairing topic: ${i}`);throw new Error(r)}}),this.core=e,this.logger=Ne(t,this.name),this.pairings=new Tr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return qe(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(It.message,async e=>{const{topic:t,message:i,transportType:r}=e;if(!this.pairings.keys.includes(t)||r===Ve.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const n=await this.core.crypto.decode(t,i);try{Vn(n)?(this.core.history.set(t,n),this.onRelayEventRequest({topic:t,payload:n})):$r(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(Cs.expired,async e=>{const{topic:t}=nw(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(cr.expire,{topic:t}))})}};var cC=Object.defineProperty,lC=(s,e,t)=>e in s?cC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,St=(s,e,t)=>lC(s,typeof e!="symbol"?e+"":e,t);let hC=class extends A0{constructor(e,t){super(e,t),this.core=e,this.logger=t,St(this,"records",new Map),St(this,"events",new kt.EventEmitter),St(this,"name",WA),St(this,"version",VA),St(this,"cached",[]),St(this,"initialized",!1),St(this,"storagePrefix",si),St(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),St(this,"set",(i,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:i,request:{method:r.method,params:r.params||null},chainId:n,expiry:ut(E.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Os.created,o)}),St(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const r=await this.getRecord(i.id);typeof r.response>"u"&&(r.response=st(i)?{error:i.error}:{result:i.result},this.records.set(r.id,r),this.persist(),this.events.emit(Os.updated,r))}),St(this,"get",async(i,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:r}),await this.getRecord(r))),St(this,"delete",(i,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===i){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(Os.deleted,n)}}),this.persist()}),St(this,"exists",async(i,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===i:!1)),St(this,"on",(i,r)=>{this.events.on(i,r)}),St(this,"once",(i,r)=>{this.events.once(i,r)}),St(this,"off",(i,r)=>{this.events.off(i,r)}),St(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=Ne(t,this.name)}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:Gt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=k("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Os.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=k("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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(Os.created,e=>{const t=Os.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Os.updated,e=>{const t=Os.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Os.deleted,e=>{const t=Os.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(qs.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{E.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Os.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var uC=Object.defineProperty,dC=(s,e,t)=>e in s?uC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ut=(s,e,t)=>dC(s,typeof e!="symbol"?e+"":e,t);let pC=class extends P0{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ut(this,"expirations",new Map),Ut(this,"events",new kt.EventEmitter),Ut(this,"name",KA),Ut(this,"version",GA),Ut(this,"cached",[]),Ut(this,"initialized",!1),Ut(this,"storagePrefix",si),Ut(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ut(this,"has",i=>{try{const r=this.formatTarget(i);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ut(this,"set",(i,r)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(Cs.created,{target:n,expiration:o})}),Ut(this,"get",i=>{this.isInitialized();const r=this.formatTarget(i);return this.getExpiration(r)}),Ut(this,"del",i=>{if(this.isInitialized(),this.has(i)){const r=this.formatTarget(i),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Cs.deleted,{target:r,expiration:n})}}),Ut(this,"on",(i,r)=>{this.events.on(i,r)}),Ut(this,"once",(i,r)=>{this.events.once(i,r)}),Ut(this,"off",(i,r)=>{this.events.off(i,r)}),Ut(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=Ne(t,this.name)}get context(){return qe(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 MI(e);if(typeof e=="number")return OI(e);const{message:t}=k("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Cs.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=k("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:i}=k("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;E.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Cs.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(qs.pulse,()=>this.checkExpirations()),this.events.on(Cs.created,e=>{const t=Cs.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Cs.expired,e=>{const t=Cs.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Cs.deleted,e=>{const t=Cs.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}};var gC=Object.defineProperty,fC=(s,e,t)=>e in s?gC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,rt=(s,e,t)=>fC(s,typeof e!="symbol"?e+"":e,t);let mC=class extends T0{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,rt(this,"name",YA),rt(this,"abortController"),rt(this,"isDevEnv"),rt(this,"verifyUrlV3",ZA),rt(this,"storagePrefix",si),rt(this,"version",Dw),rt(this,"publicKey"),rt(this,"fetchPromise"),rt(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&E.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),rt(this,"register",async r=>{if(!pa()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=r,l=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const c=Vi(),h=this.startAbortTimer(E.ONE_SECOND*5),u=await new Promise((d,p)=>{const g=()=>{window.removeEventListener("message",y),c.body.removeChild(f),p("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const f=c.createElement("iframe");f.src=l,f.style.display="none",f.addEventListener("error",g,{signal:this.abortController.signal});const y=w=>{if(w.data&&typeof w.data=="string")try{const m=JSON.parse(w.data);if(m.type==="verify_attestation"){if(jn(m.attestation).payload.id!==o)return;clearInterval(h),c.body.removeChild(f),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",y),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};c.body.appendChild(f),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(c){this.logger.warn(c)}return""}),rt(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(jn(n).payload.id!==a)return;const c=await this.isValidJwtAttestation(n);if(c){if(!c.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return c}}if(!o)return;const l=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,l)}),rt(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(E.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),rt(this,"getVerifyUrl",r=>{let n=r||Ro;return JA.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Ro}`),n=Ro),n}),rt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(E.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),rt(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),rt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),rt(this,"isValidJwtAttestation",async r=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(r,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),rt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),rt(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 r=await this.fetchPromise;return this.fetchPromise=void 0,r}),rt(this,"validateAttestation",(r,n)=>{const o=jE(r,n.publicKey),a={hasExpired:E.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ne(t,this.name),this.abortController=new AbortController,this.isDevEnv=_u(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return qe(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),E.toMiliseconds(e))}};var wC=Object.defineProperty,yC=(s,e,t)=>e in s?wC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Cp=(s,e,t)=>yC(s,typeof e!="symbol"?e+"":e,t);let bC=class extends M0{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Cp(this,"context",XA),Cp(this,"registerDeviceToken",async i=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=i,l=`${eN}/${this.projectId}/clients`;await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=Ne(t,this.context)}};var vC=Object.defineProperty,Sp=Object.getOwnPropertySymbols,IC=Object.prototype.hasOwnProperty,EC=Object.prototype.propertyIsEnumerable,kh=(s,e,t)=>e in s?vC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,po=(s,e)=>{for(var t in e||(e={}))IC.call(e,t)&&kh(s,t,e[t]);if(Sp)for(var t of Sp(e))EC.call(e,t)&&kh(s,t,e[t]);return s},gt=(s,e,t)=>kh(s,typeof e!="symbol"?e+"":e,t);let AC=class extends O0{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,gt(this,"context",sN),gt(this,"storagePrefix",si),gt(this,"storageVersion",tN),gt(this,"events",new Map),gt(this,"shouldPersist",!1),gt(this,"init",async()=>{if(!_u())try{const r={eventId:$d(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:tw(this.core.relayer.protocol,this.core.relayer.version,$h)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),gt(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:l}}=r,c=$d(),h=this.core.projectId||"",u=Date.now(),d=po({eventId:c,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:l}},bundleId:h,domain:this.getAppDomain()},this.setMethods(c));return this.telemetryEnabled&&(this.events.set(c,d),this.shouldPersist=!0),d}),gt(this,"getEvent",r=>{const{eventId:n,topic:o}=r;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(l=>l.props.properties.topic===o);if(a)return po(po({},a),this.setMethods(a.eventId))}),gt(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),gt(this,"setEventListeners",()=>{this.core.heartbeat.on(qs.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{E.fromMiliseconds(Date.now())-E.fromMiliseconds(r.timestamp)>iN&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),gt(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),gt(this,"addTrace",(r,n)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(n),this.events.set(r,o),this.shouldPersist=!0)}),gt(this,"setError",(r,n)=>{const o=this.events.get(r);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),gt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),gt(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(n=>{this.events.set(n.eventId,po(po({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),gt(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[n,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const n of r)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),gt(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${rN}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${$h}${n}`,{method:"POST",body:JSON.stringify(r)})}),gt(this,"getAppDomain",()=>ew().url),this.logger=Ne(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}};var NC=Object.defineProperty,$p=Object.getOwnPropertySymbols,_C=Object.prototype.hasOwnProperty,CC=Object.prototype.propertyIsEnumerable,jh=(s,e,t)=>e in s?NC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Pp=(s,e)=>{for(var t in e||(e={}))_C.call(e,t)&&jh(s,t,e[t]);if($p)for(var t of $p(e))CC.call(e,t)&&jh(s,t,e[t]);return s},ke=(s,e,t)=>jh(s,typeof e!="symbol"?e+"":e,t);let SC=class Gw extends b0{constructor(e){var t;super(e),ke(this,"protocol",xw),ke(this,"version",Dw),ke(this,"name",Sh),ke(this,"relayUrl"),ke(this,"projectId"),ke(this,"customStoragePrefix"),ke(this,"events",new kt.EventEmitter),ke(this,"logger"),ke(this,"heartbeat"),ke(this,"relayer"),ke(this,"crypto"),ke(this,"storage"),ke(this,"history"),ke(this,"expirer"),ke(this,"pairing"),ke(this,"verify"),ke(this,"echoClient"),ke(this,"linkModeSupportedApps"),ke(this,"eventClient"),ke(this,"initialized",!1),ke(this,"logChunkController"),ke(this,"on",(o,a)=>this.events.on(o,a)),ke(this,"once",(o,a)=>this.events.once(o,a)),ke(this,"off",(o,a)=>this.events.off(o,a)),ke(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),ke(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:l})=>{if(!o||!a)return;const c={topic:o,message:a,publishedAt:Date.now(),transportType:Ve.link_mode};this.relayer.onLinkMessageEvent(c,{sessionExists:l})}),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||jw,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=yi({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:_A.logger,name:Sh}),{logger:r,chunkLoggerController:n}=Au({opts:i,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=n,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,a;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((a=this.logChunkController)==null||a.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ne(r,this.name),this.heartbeat=new jm,this.crypto=new x_(this,this.logger,e==null?void 0:e.keychain),this.history=new hC(this,this.logger),this.expirer=new pC(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new m0(Pp(Pp({},CA),e==null?void 0:e.storageOptions)),this.relayer=new tC({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new aC(this,this.logger),this.verify=new mC(this,this.logger,this.storage),this.echoClient=new bC(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new AC(this,this.logger,e==null?void 0:e.telemetryEnabled)}static async init(e){const t=new Gw(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(UA,i),t}get context(){return qe(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(pp,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(pp)||[],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}}};const $C=SC;var PC=Object.defineProperty,TC=(s,e,t)=>e in s?PC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Tp=(s,e,t)=>TC(s,typeof e!="symbol"?e+"":e,t);let MC=class{constructor(e){this.opts=e,Tp(this,"protocol","wc"),Tp(this,"version",2)}},OC=class{constructor(e){this.client=e}};const Yw="wc",Qw=2,Zw="client",Du=`${Yw}@${Qw}:${Zw}:`,Cl={name:Zw,logger:"error"},Mp="WALLETCONNECT_DEEPLINK_CHOICE",xC="proposal",Op="Proposal expired",DC="session",qr=E.SEVEN_DAYS,kC="engine",ft={wc_sessionPropose:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1104},res:{ttl:E.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1106},res:{ttl:E.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1112},res:{ttl:E.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1114},res:{ttl:E.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:E.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:E.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1119}}},Sl={min:E.FIVE_MINUTES,max:E.SEVEN_DAYS},Vs={idle:"IDLE",active:"ACTIVE"},xp={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},jC="request",RC=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],LC="wc",UC="auth",zC="authKeys",FC="pairingTopics",qC="requests",Kc=`${LC}@${1.5}:${UC}:`,oc=`${Kc}:PUB_KEY`;var BC=Object.defineProperty,HC=Object.defineProperties,WC=Object.getOwnPropertyDescriptors,Dp=Object.getOwnPropertySymbols,VC=Object.prototype.hasOwnProperty,KC=Object.prototype.propertyIsEnumerable,Rh=(s,e,t)=>e in s?BC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ze=(s,e)=>{for(var t in e||(e={}))VC.call(e,t)&&Rh(s,t,e[t]);if(Dp)for(var t of Dp(e))KC.call(e,t)&&Rh(s,t,e[t]);return s},Zt=(s,e)=>HC(s,WC(e)),x=(s,e,t)=>Rh(s,typeof e!="symbol"?e+"":e,t);let GC=class extends OC{constructor(e){super(e),x(this,"name",kC),x(this,"events",new Kn),x(this,"initialized",!1),x(this,"requestQueue",{state:Vs.idle,queue:[]}),x(this,"sessionRequestQueue",{state:Vs.idle,queue:[]}),x(this,"requestQueueDelay",E.ONE_SECOND),x(this,"expectedPairingMethodMap",new Map),x(this,"recentlyDeletedMap",new Map),x(this,"recentlyDeletedLimit",200),x(this,"relayMessageCache",[]),x(this,"pendingSessions",new Map),x(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(ft)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},E.toMiliseconds(this.requestQueueDelay)))}),x(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Zt(Ze({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,relays:l}=i;let c=r,h,u=!1;try{if(c){const N=this.client.core.pairing.pairings.get(c);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),u=N.active}}catch(N){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),N}if(!c||!u){const{topic:N,uri:$}=await this.client.core.pairing.create();c=N,h=$}if(!c){const{message:N}=k("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(N)}const d=await this.client.core.crypto.generateKeyPair(),p=ft.wc_sessionPropose.req.ttl||E.FIVE_MINUTES,g=ut(p),f=Zt(Ze({requiredNamespaces:n,optionalNamespaces:o,relays:l??[{protocol:kw}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:c},a&&{sessionProperties:a}),{id:qt()}),y=Ie("session_connect",f.id),{reject:w,resolve:m,done:b}=rr(p,Op),I=({id:N})=>{N===f.id&&(this.client.events.off("proposal_expire",I),this.pendingSessions.delete(f.id),this.events.emit(y,{error:{message:Op,code:0}}))};return this.client.events.on("proposal_expire",I),this.events.once(y,({error:N,session:$})=>{this.client.events.off("proposal_expire",I),N?w(N):$&&m($)}),await this.sendRequest({topic:c,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:h,approval:b}}),x(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}}),x(this,"approve",async t=>{var i,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=t==null?void 0:t.id)==null?void 0:i.toString(),trace:[xs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(O){throw o.setError(Xi.no_internet_connection),O}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(O){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(Xi.proposal_not_found),O}try{await this.isValidApprove(t)}catch(O){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Xi.session_approve_namespace_validation_failure),O}const{id:a,relayProtocol:l,namespaces:c,sessionProperties:h,sessionConfig:u}=t,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:f,optionalNamespaces:y}=d;let w=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:p});w||(w=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:xs.session_approve_started,properties:{topic:p,trace:[xs.session_approve_started,xs.session_namespaces_validation_success]}}));const m=await this.client.core.crypto.generateKeyPair(),b=g.publicKey,I=await this.client.core.crypto.generateSharedKey(m,b),N=Ze(Ze({relay:{protocol:l??"irn"},namespaces:c,controller:{publicKey:m,metadata:this.client.metadata},expiry:ut(qr)},h&&{sessionProperties:h}),u&&{sessionConfig:u}),$=Ve.relay;w.addTrace(xs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(I,{transportType:$})}catch(O){throw w.setError(Xi.subscribe_session_topic_failure),O}w.addTrace(xs.subscribe_session_topic_success);const P=Zt(Ze({},N),{topic:I,requiredNamespaces:f,optionalNamespaces:y,pairingTopic:p,acknowledged:!1,self:N.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:m,transportType:Ve.relay});await this.client.session.set(I,P),w.addTrace(xs.store_session);try{w.addTrace(xs.publishing_session_settle),await this.sendRequest({topic:I,method:"wc_sessionSettle",params:N,throwOnFailedPublish:!0}).catch(O=>{throw w==null||w.setError(Xi.session_settle_publish_failure),O}),w.addTrace(xs.session_settle_publish_success),w.addTrace(xs.publishing_session_approve),await this.sendResult({id:a,topic:p,result:{relay:{protocol:l??"irn"},responderPublicKey:m},throwOnFailedPublish:!0}).catch(O=>{throw w==null||w.setError(Xi.session_approve_publish_failure),O}),w.addTrace(xs.session_approve_publish_success)}catch(O){throw this.client.logger.error(O),this.client.session.delete(I,Te("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(I),O}return this.client.core.eventClient.deleteEvent({eventId:w.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:g.metadata}),await this.client.proposal.delete(a,Te("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(I,ut(qr)),{topic:I,acknowledged:()=>Promise.resolve(this.client.session.get(I))}}),x(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:r}=t;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&(await this.sendError({id:i,topic:n,error:r,rpcOpts:ft.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Te("USER_DISCONNECTED")))}),x(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:i,namespaces:r}=t,{done:n,resolve:o,reject:a}=rr(),l=qt(),c=gs().toString(),h=this.client.session.get(i).namespaces;return this.events.once(Ie("session_update",l),({error:u})=>{u?a(u):o()}),await this.client.session.update(i,{namespaces:r}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:l,relayRpcId:c}).catch(u=>{this.client.logger.error(u),this.client.session.update(i,{namespaces:h}),a(u)}),{acknowledged:n}}),x(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(l){throw this.client.logger.error("extend() -> isValidExtend() failed"),l}const{topic:i}=t,r=qt(),{done:n,resolve:o,reject:a}=rr();return this.events.once(Ie("session_extend",r),({error:l})=>{l?a(l):o()}),await this.setExpiry(i,ut(qr)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(l=>{a(l)}),{acknowledged:n}}),x(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:i,request:r,topic:n,expiry:o=ft.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===Ve.relay&&await this.confirmOnlineStateOrThrow();const l=qt(),c=gs().toString(),{done:h,resolve:u,reject:d}=rr(o,"Request expired. Please try again.");this.events.once(Ie("session_request",l),({error:w,result:m})=>{w?d(w):u(m)});const p="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:l,relayRpcId:c,topic:n,method:p,params:{request:Zt(Ze({},r),{expiryTimestamp:ut(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:l}),await h();const f={request:Zt(Ze({},r),{expiryTimestamp:ut(o)}),chainId:i},y=this.shouldSetTVF(p,f);return await Promise.all([new Promise(async w=>{await this.sendRequest(Ze({clientRpcId:l,relayRpcId:c,topic:n,method:p,params:f,expiry:o,throwOnFailedPublish:!0},y&&{tvf:this.getTVFParams(l,f)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:l}),w()}),new Promise(async w=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const b=await jI(this.client.core.storage,Mp);await xI({id:l,topic:n,wcDeepLink:b})}w()}),h()]).then(w=>w[2])}),x(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:r}=t,{id:n}=r,o=this.client.session.get(i);o.transportType===Ve.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);vt(r)?await this.sendResult({id:n,topic:i,result:r.result,throwOnFailedPublish:!0,appLink:a}):st(r)&&await this.sendError({id:n,topic:i,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),x(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:i}=t;if(this.client.session.keys.includes(i)){const r=qt(),n=gs().toString(),{done:o,resolve:a,reject:l}=rr();this.events.once(Ie("session_ping",r),({error:c})=>{c?l(c):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),x(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:r,chainId:n}=t,o=gs().toString(),a=qt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),x(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Te("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:r}=k("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(r)}}),x(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(i=>KE(i,t)))),x(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),x(this,"authenticate",async(t,i)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?Ve.link_mode:Ve.relay;o===Ve.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:l="",uri:c,domain:h,nonce:u,type:d,exp:p,nbf:g,methods:f=[],expiry:y}=t,w=[...t.resources||[]],{topic:m,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:b}});const I=await this.client.core.crypto.generateKeyPair(),N=nc(I);if(await Promise.all([this.client.auth.authKeys.set(oc,{responseTopic:N,publicKey:I}),this.client.auth.pairingTopics.set(N,{topic:N,pairingTopic:m})]),await this.client.core.relayer.subscribe(N,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),f.length>0){const{namespace:A}=On(a[0]);let z=C1(A,"request",f);rc(w)&&(z=$1(z,w.pop())),w.push(z)}const $=y&&y>ft.wc_sessionAuthenticate.req.ttl?y:ft.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:d??"caip122",chains:a,statement:l,aud:c,domain:h,version:"1",nonce:u,iat:new Date().toISOString(),exp:p,nbf:g,resources:w},requester:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:ut($)},O={eip155:{chains:a,methods:[...new Set(["personal_sign",...f])],events:["chainChanged","accountsChanged"]}},C={requiredNamespaces:{},optionalNamespaces:O,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:ut(ft.wc_sessionPropose.req.ttl),id:qt()},{done:T,resolve:S,reject:R}=rr($,"Request expired"),L=qt(),q=Ie("session_connect",C.id),B=Ie("session_request",L),U=async({error:A,session:z})=>{this.events.off(B,H),A?R(A):z&&S({session:z})},H=async A=>{var z,Y,K;if(await this.deletePendingAuthRequest(L,{message:"fulfilled",code:0}),A.error){const He=Te("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return A.error.code===He.code?void 0:(this.events.off(q,U),R(A.error.message))}await this.deleteProposal(C.id),this.events.off(q,U);const{cacaos:be,responder:oe}=A.result,Oe=[],lt=[];for(const He of be){await jd({cacao:He,projectId:this.client.core.projectId})||(this.client.logger.error(He,"Signature verification failed"),R(Te("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Qi}=He,Zi=rc(Qi.resources),so=[vh(Qi.iss)],cl=Nc(Qi.iss);if(Zi){const Ji=Rd(Zi),ll=Ld(Zi);Oe.push(...Ji),so.push(...ll)}for(const Ji of so)lt.push(`${Ji}:${cl}`)}const Be=await this.client.core.crypto.generateSharedKey(I,oe.publicKey);let Qe;Oe.length>0&&(Qe={topic:Be,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:oe,controller:oe.publicKey,expiry:ut(qr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:ip([...new Set(Oe)],[...new Set(lt)]),transportType:o},await this.client.core.relayer.subscribe(Be,{transportType:o}),await this.client.session.set(Be,Qe),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:oe.metadata}),Qe=this.client.session.get(Be)),(z=this.client.metadata.redirect)!=null&&z.linkMode&&(Y=oe.metadata.redirect)!=null&&Y.linkMode&&(K=oe.metadata.redirect)!=null&&K.universal&&i&&(this.client.core.addLinkModeSupportedApp(oe.metadata.redirect.universal),this.client.session.update(Be,{transportType:Ve.link_mode})),S({auths:be,session:Qe})};this.events.once(q,U),this.events.once(B,H);let W;try{if(n){const A=Gt("wc_sessionAuthenticate",P,L);this.client.core.history.set(m,A);const z=await this.client.core.crypto.encode("",A,{type:wa,encoding:ao});W=ka(i,m,z)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:P,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:L}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:C,expiry:ft.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:C.id})])}catch(A){throw this.events.off(q,U),this.events.off(B,H),A}return await this.setProposal(C.id,C),await this.setAuthRequest(L,{request:Zt(Ze({},P),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:W??b,response:T}}),x(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[er.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw n.setError(ho.no_internet_connection),y}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(ho.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Ve.relay;a===Ve.relay&&await this.confirmOnlineStateOrThrow();const l=o.requester.publicKey,c=await this.client.core.crypto.generateKeyPair(),h=nc(l),u={type:gi,receiverPublicKey:l,senderPublicKey:c},d=[],p=[];for(const y of r){if(!await jd({cacao:y,projectId:this.client.core.projectId})){n.setError(ho.invalid_cacao);const N=Te("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:h,error:N,encodeOpts:u}),new Error(N.message)}n.addTrace(er.cacaos_verified);const{p:w}=y,m=rc(w.resources),b=[vh(w.iss)],I=Nc(w.iss);if(m){const N=Rd(m),$=Ld(m);d.push(...N),b.push(...$)}for(const N of b)p.push(`${N}:${I}`)}const g=await this.client.core.crypto.generateSharedKey(c,l);n.addTrace(er.create_authenticated_session_topic);let f;if((d==null?void 0:d.length)>0){f={topic:g,acknowledged:!0,self:{publicKey:c,metadata:this.client.metadata},peer:{publicKey:l,metadata:o.requester.metadata},controller:l,expiry:ut(qr),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:ip([...new Set(d)],[...new Set(p)]),transportType:a},n.addTrace(er.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(y){throw n.setError(ho.subscribe_authenticated_session_topic_failure),y}n.addTrace(er.subscribe_authenticated_session_topic_success),await this.client.session.set(g,f),n.addTrace(er.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(er.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:i,result:{cacaos:r,responder:{publicKey:c,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw n.setError(ho.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:f}}),x(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:i,reason:r}=t,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===Ve.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),l=nc(o),c={type:gi,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:l,error:r,encodeOpts:c,rpcOpts:ft.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Te("USER_DISCONNECTED"))}),x(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:r}=t;return gw(i,r)}),x(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),x(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),r=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)===t.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),x(this,"deleteSession",async t=>{var i;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:l}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Te("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(l.publicKey)&&await this.client.core.crypto.deleteKeyPair(l.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Mp).catch(c=>this.client.logger.warn(c)),this.getPendingSessionRequests().forEach(c=>{c.topic===r&&this.deletePendingSessionRequest(c.id,Te("USER_DISCONNECTED"))}),r===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Vs.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),x(this,"deleteProposal",async(t,i)=>{if(i)try{const r=this.client.proposal.get(t),n=this.client.core.eventClient.getEvent({topic:r.pairingTopic});n==null||n.setError(Xi.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Te("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),x(this,"deletePendingSessionRequest",async(t,i,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==t),r&&(this.sessionRequestQueue.state=Vs.idle,this.client.events.emit("session_request_expire",{id:t}))}),x(this,"deletePendingAuthRequest",async(t,i,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)])}),x(this,"setExpiry",async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))}),x(this,"setProposal",async(t,i)=>{this.client.core.expirer.set(t,ut(ft.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),x(this,"setAuthRequest",async(t,i)=>{const{request:r,pairingTopic:n,transportType:o=Ve.relay}=i;this.client.core.expirer.set(t,r.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:t,pairingTopic:n,verifyContext:r.verifyContext,transportType:o})}),x(this,"setPendingSessionRequest",async t=>{const{id:i,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ut(ft.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:r,params:n,verifyContext:o})}),x(this,"sendRequest",async t=>{const{topic:i,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:l,throwOnFailedPublish:c,appLink:h,tvf:u}=t,d=Gt(r,n,l);let p;const g=!!h;try{const w=g?ao:ji;p=await this.client.core.crypto.encode(i,d,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),w}let f;if(RC.includes(r)){const w=di(JSON.stringify(d)),m=di(p);f=await this.client.core.verify.register({id:m,decryptedId:w})}const y=ft[r].req;if(y.attestation=f,o&&(y.ttl=o),a&&(y.id=a),this.client.core.history.set(i,d),g){const w=ka(h,i,p);await _.global.Linking.openURL(w,this.client.name)}else{const w=ft[r].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=Zt(Ze({},u),{correlationId:d.id}),c?(w.internal=Zt(Ze({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,w)):this.client.core.relayer.publish(i,p,w).catch(m=>this.client.logger.error(m))}return d.id}),x(this,"sendResult",async t=>{const{id:i,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:l}=t,c=Wi(i,n);let h;const u=l&&typeof(_.global==null?void 0:_.global.Linking)<"u";try{const g=u?ao:ji;h=await this.client.core.crypto.encode(r,c,Zt(Ze({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let d,p;try{d=await this.client.core.history.get(r,i);const g=d.request;try{this.shouldSetTVF(g.method,g.params)&&(p=this.getTVFParams(i,g.params,n))}catch(f){this.client.logger.warn("sendResult() -> getTVFParams() failed",f)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${i}) failed`),g}if(u){const g=ka(l,r,h);await _.global.Linking.openURL(g,this.client.name)}else{const g=d.request.method,f=ft[g].res;f.tvf=Zt(Ze({},p),{correlationId:i}),o?(f.internal=Zt(Ze({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,h,f)):this.client.core.relayer.publish(r,h,f).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(c)}),x(this,"sendError",async t=>{const{id:i,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:l}=t,c=ca(i,n);let h;const u=l&&typeof(_.global==null?void 0:_.global.Linking)<"u";try{const p=u?ao:ji;h=await this.client.core.crypto.encode(r,c,Zt(Ze({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),p}let d;try{d=await this.client.core.history.get(r,i)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${r}, ${i}) failed`),p}if(u){const p=ka(l,r,h);await _.global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,g=a||ft[p].res;this.client.core.relayer.publish(r,h,g)}await this.client.core.history.resolve(c)}),x(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(r=>{let n=!1;Si(r.expiry)&&(n=!0),this.client.core.crypto.keychain.has(r.topic)||(n=!0),n&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{Si(r.expiryTimestamp)&&i.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...i.map(r=>this.deleteProposal(r))])}),x(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),x(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Vs.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=Vs.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Vs.idle}),x(this,"processRequest",async t=>{const{topic:i,payload:r,attestation:n,transportType:o,encryptedId:a}=t,l=r.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:l}))switch(l){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,r);case"wc_sessionPing":return await this.onSessionPingRequest(i,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${l}`)}}),x(this,"onRelayEventResponse",async t=>{const{topic:i,payload:r,transportType:n}=t,o=(await this.client.core.history.get(i,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,r);case"wc_sessionExtend":return this.onSessionExtendResponse(i,r);case"wc_sessionPing":return this.onSessionPingResponse(i,r);case"wc_sessionRequest":return this.onSessionRequestResponse(i,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),x(this,"onRelayEventUnknownPayload",t=>{const{topic:i}=t,{message:r}=k("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),x(this,"shouldIgnorePairingRequest",t=>{const{topic:i,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),x(this,"onSessionProposeRequest",async t=>{const{topic:i,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:l}=r;try{const c=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),c==null||c.setError(hi.proposal_listener_not_found)),this.isValidConnect(Ze({},r.params));const h=a.expiryTimestamp||ut(ft.wc_sessionPropose.req.ttl),u=Ze({id:l,pairingTopic:i,expiryTimestamp:h},a);await this.setProposal(l,u);const d=await this.getVerifyContext({attestationId:n,hash:di(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});c==null||c.addTrace(Zs.emit_session_proposal),this.client.events.emit("session_proposal",{id:l,params:u,verifyContext:d})}catch(c){await this.sendError({id:l,topic:i,error:c,rpcOpts:ft.wc_sessionPropose.autoReject}),this.client.logger.error(c)}}),x(this,"onSessionProposeResponse",async(t,i,r)=>{const{id:n}=i;if(vt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const l=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const c=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:c});const h=await this.client.core.crypto.generateSharedKey(l,c);this.pendingSessions.set(n,{sessionTopic:h,pairingTopic:t,proposalId:n,publicKey:l});const u=await this.client.core.relayer.subscribe(h,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(st(i)){await this.client.proposal.delete(n,Te("USER_DISCONNECTED"));const o=Ie("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),x(this,"onSessionSettleRequest",async(t,i)=>{const{id:r,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:l,namespaces:c,sessionProperties:h,sessionConfig:u}=i.params,d=[...this.pendingSessions.values()].find(f=>f.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const p=this.client.proposal.get(d.proposalId),g=Zt(Ze(Ze({topic:t,relay:o,expiry:l,namespaces:c,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},h&&{sessionProperties:h}),u&&{sessionConfig:u}),{transportType:Ve.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(Ie("session_connect",d.proposalId),{session:g}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),x(this,"onSessionSettleResponse",async(t,i)=>{const{id:r}=i;vt(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Ie("session_approve",r),{})):st(i)&&(await this.client.session.delete(t,Te("USER_DISCONNECTED")),this.events.emit(Ie("session_approve",r),{error:i.error}))}),x(this,"onSessionUpdateRequest",async(t,i)=>{const{params:r,id:n}=i;try{const o=`${t}_session_update`,a=co.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:t,error:Te("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ze({topic:t},r));try{co.set(o,n),await this.client.session.update(t,{namespaces:r.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(l){throw co.delete(o),l}this.client.events.emit("session_update",{id:n,topic:t,params:r})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}}),x(this,"isRequestOutOfSync",(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3)),x(this,"onSessionUpdateResponse",(t,i)=>{const{id:r}=i,n=Ie("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ie("session_update",r),{}):st(i)&&this.events.emit(Ie("session_update",r),{error:i.error})}),x(this,"onSessionExtendRequest",async(t,i)=>{const{id:r}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ut(qr)),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),x(this,"onSessionExtendResponse",(t,i)=>{const{id:r}=i,n=Ie("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ie("session_extend",r),{}):st(i)&&this.events.emit(Ie("session_extend",r),{error:i.error})}),x(this,"onSessionPingRequest",async(t,i)=>{const{id:r}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),x(this,"onSessionPingResponse",(t,i)=>{const{id:r}=i,n=Ie("session_ping",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);setTimeout(()=>{vt(i)?this.events.emit(Ie("session_ping",r),{}):st(i)&&this.events.emit(Ie("session_ping",r),{error:i.error})},500)}),x(this,"onSessionDeleteRequest",async(t,i)=>{const{id:r}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(It.publish,async()=>{n(await this.deleteSession({topic:t,id:r}))})}),this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Te("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),x(this,"onSessionRequest",async t=>{var i,r,n;const{topic:o,payload:a,attestation:l,encryptedId:c,transportType:h}=t,{id:u,params:d}=a;try{await this.isValidRequest(Ze({topic:o},d));const p=this.client.session.get(o),g=await this.getVerifyContext({attestationId:l,hash:di(JSON.stringify(Gt("wc_sessionRequest",d,u))),encryptedId:c,metadata:p.peer.metadata,transportType:h}),f={id:u,topic:o,params:d,verifyContext:g};await this.setPendingSessionRequest(f),h===Ve.link_mode&&(i=p.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((r=p.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(p){await this.sendError({id:u,topic:o,error:p}),this.client.logger.error(p)}}),x(this,"onSessionRequestResponse",(t,i)=>{const{id:r}=i,n=Ie("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ie("session_request",r),{result:i.result}):st(i)&&this.events.emit(Ie("session_request",r),{error:i.error})}),x(this,"onSessionEventRequest",async(t,i)=>{const{id:r,params:n}=i;try{const o=`${t}_session_event_${n.event.name}`,a=co.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Ze({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),co.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),x(this,"onSessionAuthenticateResponse",(t,i)=>{const{id:r}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),vt(i)?this.events.emit(Ie("session_request",r),{result:i.result}):st(i)&&this.events.emit(Ie("session_request",r),{error:i.error})}),x(this,"onSessionAuthenticateRequest",async t=>{var i;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:l}=t;try{const{requester:c,authPayload:h,expiryTimestamp:u}=n.params,d=await this.getVerifyContext({attestationId:o,hash:di(JSON.stringify(n)),encryptedId:a,metadata:c.metadata,transportType:l}),p={requester:c,pairingTopic:r,id:n.id,authPayload:h,verifyContext:d,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:p,pairingTopic:r,transportType:l}),l===Ve.link_mode&&(i=c.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:d})}catch(c){this.client.logger.error(c);const h=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,l),p={type:gi,receiverPublicKey:h,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:c,encodeOpts:p,rpcOpts:ft.wc_sessionAuthenticate.autoReject,appLink:d})}}),x(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),x(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Vs.idle,this.processSessionRequestQueue()},E.toMiliseconds(this.requestQueueDelay))}),x(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:i})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=Ie("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Ie("session_request",n.request.id),{error:i})})}),x(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Vs.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Vs.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}}),x(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),x(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:Gt("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})}),x(this,"isValidConnect",async t=>{if(!is(t)){const{message:l}=k("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,relays:a}=t;if(Kt(i)||await this.isValidPairingTopic(i),!nA(a)){const{message:l}=k("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(l)}!Kt(r)&&Jo(r)!==0&&this.validateNamespaces(r,"requiredNamespaces"),!Kt(n)&&Jo(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Kt(o)||this.validateSessionProps(o,"sessionProperties")}),x(this,"validateNamespaces",(t,i)=>{const r=rA(t,"connect()",i);if(r)throw new Error(r.message)}),x(this,"isValidApprove",async t=>{if(!is(t))throw new Error(k("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:r,relayProtocol:n,sessionProperties:o}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const a=this.client.proposal.get(i),l=Il(r,"approve()");if(l)throw new Error(l.message);const c=op(a.requiredNamespaces,r,"approve()");if(c)throw new Error(c.message);if(!it(n,!0)){const{message:h}=k("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}Kt(o)||this.validateSessionProps(o,"sessionProperties")}),x(this,"isValidReject",async t=>{if(!is(t)){const{message:n}=k("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:r}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!aA(r)){const{message:n}=k("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),x(this,"isValidSessionSettleRequest",t=>{if(!is(t)){const{message:c}=k("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(c)}const{relay:i,controller:r,namespaces:n,expiry:o}=t;if(!Mw(i)){const{message:c}=k("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}const a=JE(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const l=Il(n,"onSessionSettleRequest()");if(l)throw new Error(l.message);if(Si(o)){const{message:c}=k("EXPIRED","onSessionSettleRequest()");throw new Error(c)}}),x(this,"isValidUpdate",async t=>{if(!is(t)){const{message:l}=k("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(l)}const{topic:i,namespaces:r}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=Il(r,"update()");if(o)throw new Error(o.message);const a=op(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),x(this,"isValidExtend",async t=>{if(!is(t)){const{message:r}=k("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),x(this,"isValidRequest",async t=>{if(!is(t)){const{message:l}=k("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(l)}const{topic:i,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!np(a,n)){const{message:l}=k("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(l)}if(!cA(r)){const{message:l}=k("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(l)}if(!uA(a,n,r.method)){const{message:l}=k("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(l)}if(o&&!fA(o,Sl)){const{message:l}=k("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Sl.min} and ${Sl.max}`);throw new Error(l)}}),x(this,"isValidRespond",async t=>{var i;if(!is(t)){const{message:o}=k("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(i=t==null?void 0:t.response)!=null&&i.id&&this.cleanupAfterResponse(t),o}if(!lA(n)){const{message:o}=k("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),x(this,"isValidPing",async t=>{if(!is(t)){const{message:r}=k("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),x(this,"isValidEmit",async t=>{if(!is(t)){const{message:a}=k("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:i,event:r,chainId:n}=t;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!np(o,n)){const{message:a}=k("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!hA(r)){const{message:a}=k("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!dA(o,n,r.name)){const{message:a}=k("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),x(this,"isValidDisconnect",async t=>{if(!is(t)){const{message:r}=k("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),x(this,"isValidAuthenticate",t=>{const{chains:i,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!it(r,!1))throw new Error("uri is required parameter");if(!it(n,!1))throw new Error("domain is required parameter");if(!it(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(l=>On(l).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=On(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),x(this,"getVerifyContext",async t=>{const{attestationId:i,hash:r,encryptedId:n,metadata:o,transportType:a}=t,l={verified:{verifyUrl:o.verifyUrl||Ro,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Ve.link_mode){const h=this.getAppLinkIfEnabled(o,a);return l.verified.validation=h&&new URL(h).origin===new URL(o.url).origin?"VALID":"INVALID",l}const c=await this.client.core.verify.resolve({attestationId:i,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});c&&(l.verified.origin=c.origin,l.verified.isScam=c.isScam,l.verified.validation=c.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(c){this.client.logger.warn(c)}return this.client.logger.debug(`Verify context: ${JSON.stringify(l)}`),l}),x(this,"validateSessionProps",(t,i)=>{Object.values(t).forEach(r=>{if(!it(r,!1)){const{message:n}=k("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(r)}`);throw new Error(n)}})}),x(this,"getPendingAuthRequest",t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0}),x(this,"addToRecentlyDeleted",(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=n)break;this.recentlyDeletedMap.delete(o)}}}),x(this,"checkRecentlyDeleted",t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:r}=k("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(r)}}),x(this,"isLinkModeEnabled",(t,i)=>{var r,n,o,a,l,c,h,u,d;return!t||i!==Ve.link_mode?!1:((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((c=(l=this.client.metadata)==null?void 0:l.redirect)==null?void 0:c.universal)!==""&&((h=t==null?void 0:t.redirect)==null?void 0:h.universal)!==void 0&&((u=t==null?void 0:t.redirect)==null?void 0:u.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(_.global==null?void 0:_.global.Linking)<"u"}),x(this,"getAppLinkIfEnabled",(t,i)=>{var r;return this.isLinkModeEnabled(t,i)?(r=t==null?void 0:t.redirect)==null?void 0:r.universal:void 0}),x(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Sd(t,"topic")||"",r=decodeURIComponent(Sd(t,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:Ve.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:r,sessionExists:n})}),x(this,"registerLinkModeListeners",async()=>{var t;if(_u()||Gi()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=_.global==null?void 0:_.global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await i.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),x(this,"shouldSetTVF",(t,i)=>{if(!i||t!=="wc_sessionRequest")return!1;const{request:r}=i;return Object.keys(xp).includes(r.method)}),x(this,"getTVFParams",(t,i,r)=>{var n,o;try{const a=i.request.method,l=this.extractTxHashesFromResult(a,r);return Zt(Ze({correlationId:t,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:l})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),x(this,"isValidContractData",t=>{var i;if(!t)return!1;try{const r=(t==null?void 0:t.data)||((i=t==null?void 0:t[0])==null?void 0:i.data);if(!r.startsWith("0x"))return!1;const n=r.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),x(this,"extractTxHashesFromResult",(t,i)=>{try{const r=xp[t];if(typeof i=="string")return[i];const n=i[r.key];if(vr(n))return n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}isInitialized(){if(!this.initialized){const{message:e}=k("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(It.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(oc)?this.client.auth.authKeys.get(oc):{publicKey:void 0},a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===Ve.link_mode?ao:ji});try{Vn(a)?(this.client.core.history.set(t,a),this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:di(i)})):$r(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n})}catch(l){this.client.logger.error(l)}}registerExpirerEvents(){this.client.core.expirer.on(Cs.expired,async e=>{const{topic:t,id:i}=nw(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,k("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,k("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(cr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(cr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!it(e,!1)){const{message:t}=k("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=k("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Si(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=k("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!it(e,!1)){const{message:t}=k("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=k("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Si(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=k("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=k("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(it(e,!1)){const{message:t}=k("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=k("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!oA(e)){const{message:t}=k("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=k("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Si(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=k("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}},YC=class extends Tr{constructor(e,t){super(e,t,xC,Du),this.core=e,this.logger=t}},QC=class extends Tr{constructor(e,t){super(e,t,DC,Du),this.core=e,this.logger=t}},ZC=class extends Tr{constructor(e,t){super(e,t,jC,Du,i=>i.id),this.core=e,this.logger=t}},JC=class extends Tr{constructor(e,t){super(e,t,zC,Kc,()=>oc),this.core=e,this.logger=t}},XC=class extends Tr{constructor(e,t){super(e,t,FC,Kc),this.core=e,this.logger=t}},eS=class extends Tr{constructor(e,t){super(e,t,qC,Kc,i=>i.id),this.core=e,this.logger=t}};var tS=Object.defineProperty,sS=(s,e,t)=>e in s?tS(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,$l=(s,e,t)=>sS(s,typeof e!="symbol"?e+"":e,t);let iS=class{constructor(e,t){this.core=e,this.logger=t,$l(this,"authKeys"),$l(this,"pairingTopics"),$l(this,"requests"),this.authKeys=new JC(this.core,this.logger),this.pairingTopics=new XC(this.core,this.logger),this.requests=new eS(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}};var rS=Object.defineProperty,nS=(s,e,t)=>e in s?rS(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ce=(s,e,t)=>nS(s,typeof e!="symbol"?e+"":e,t);let oS=class Jw extends MC{constructor(e){super(e),ce(this,"protocol",Yw),ce(this,"version",Qw),ce(this,"name",Cl.name),ce(this,"metadata"),ce(this,"core"),ce(this,"logger"),ce(this,"events",new kt.EventEmitter),ce(this,"engine"),ce(this,"session"),ce(this,"proposal"),ce(this,"pendingRequest"),ce(this,"auth"),ce(this,"signConfig"),ce(this,"on",(i,r)=>this.events.on(i,r)),ce(this,"once",(i,r)=>this.events.once(i,r)),ce(this,"off",(i,r)=>this.events.off(i,r)),ce(this,"removeListener",(i,r)=>this.events.removeListener(i,r)),ce(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),ce(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"update",async i=>{try{return await this.engine.update(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"request",async i=>{try{return await this.engine.request(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"find",i=>{try{return this.engine.find(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),ce(this,"authenticate",async(i,r)=>{try{return await this.engine.authenticate(i,r)}catch(n){throw this.logger.error(n.message),n}}),ce(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),ce(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||Cl.name,this.metadata=(e==null?void 0:e.metadata)||ew(),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Wn(yi({level:(e==null?void 0:e.logger)||Cl.logger}));this.core=(e==null?void 0:e.core)||new $C(e),this.logger=Ne(t,this.name),this.session=new QC(this.core,this.logger),this.proposal=new YC(this.core,this.logger),this.pendingRequest=new ZC(this.core,this.logger),this.engine=new GC(this),this.auth=new iS(this.core,this.logger)}static async init(e){const t=new Jw(e);return await t.initialize(),t}get context(){return qe(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()},E.toMiliseconds(E.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const kp="error",aS="wss://relay.walletconnect.org",cS="wc",lS="universal_provider",jp=`${cS}@2:${lS}:`,Xw="https://rpc.walletconnect.org/v1/",yn="generic",hS=`${Xw}bundler`,Ts={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Ra=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof _.global<"u"?_.global:typeof self<"u"?self:{};function uS(){this.__data__=[],this.size=0}var dS=uS;function pS(s,e){return s===e||s!==s&&e!==e}var Gc=pS,gS=Gc;function fS(s,e){for(var t=s.length;t--;)if(gS(s[t][0],e))return t;return-1}var Yc=fS,mS=Yc,wS=Array.prototype,yS=wS.splice;function bS(s){var e=this.__data__,t=mS(e,s);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():yS.call(e,t,1),--this.size,!0}var vS=bS,IS=Yc;function ES(s){var e=this.__data__,t=IS(e,s);return t<0?void 0:e[t][1]}var AS=ES,NS=Yc;function _S(s){return NS(this.__data__,s)>-1}var CS=_S,SS=Yc;function $S(s,e){var t=this.__data__,i=SS(t,s);return i<0?(++this.size,t.push([s,e])):t[i][1]=e,this}var PS=$S,TS=dS,MS=vS,OS=AS,xS=CS,DS=PS;function bn(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}bn.prototype.clear=TS,bn.prototype.delete=MS,bn.prototype.get=OS,bn.prototype.has=xS,bn.prototype.set=DS;var Qc=bn,kS=Qc;function jS(){this.__data__=new kS,this.size=0}var RS=jS;function LS(s){var e=this.__data__,t=e.delete(s);return this.size=e.size,t}var US=LS;function zS(s){return this.__data__.get(s)}var FS=zS;function qS(s){return this.__data__.has(s)}var BS=qS,HS=typeof Ra=="object"&&Ra&&Ra.Object===Object&&Ra,ey=HS,WS=ey,VS=typeof self=="object"&&self&&self.Object===Object&&self,KS=WS||VS||Function("return this")(),Zn=KS,GS=Zn,YS=GS.Symbol,ty=YS,Rp=ty,sy=Object.prototype,QS=sy.hasOwnProperty,ZS=sy.toString,go=Rp?Rp.toStringTag:void 0;function JS(s){var e=QS.call(s,go),t=s[go];try{s[go]=void 0;var i=!0}catch{}var r=ZS.call(s);return i&&(e?s[go]=t:delete s[go]),r}var XS=JS,e$=Object.prototype,t$=e$.toString;function s$(s){return t$.call(s)}var i$=s$,Lp=ty,r$=XS,n$=i$,o$="[object Null]",a$="[object Undefined]",Up=Lp?Lp.toStringTag:void 0;function c$(s){return s==null?s===void 0?a$:o$:Up&&Up in Object(s)?r$(s):n$(s)}var Zc=c$;function l$(s){var e=typeof s;return s!=null&&(e=="object"||e=="function")}var Mr=l$,h$=Zc,u$=Mr,d$="[object AsyncFunction]",p$="[object Function]",g$="[object GeneratorFunction]",f$="[object Proxy]";function m$(s){if(!u$(s))return!1;var e=h$(s);return e==p$||e==g$||e==d$||e==f$}var ku=m$,w$=Zn,y$=w$["__core-js_shared__"],b$=y$,Pl=b$,zp=function(){var s=/[^.]+$/.exec(Pl&&Pl.keys&&Pl.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function v$(s){return!!zp&&zp in s}var I$=v$,E$=Function.prototype,A$=E$.toString;function N$(s){if(s!=null){try{return A$.call(s)}catch{}try{return s+""}catch{}}return""}var _$=N$,C$=ku,S$=I$,$$=Mr,P$=_$,T$=/[\\^$.*+?()[\]{}|]/g,M$=/^\[object .+?Constructor\]$/,O$=Function.prototype,x$=Object.prototype,D$=O$.toString,k$=x$.hasOwnProperty,j$=RegExp("^"+D$.call(k$).replace(T$,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function R$(s){if(!$$(s)||S$(s))return!1;var e=C$(s)?j$:M$;return e.test(P$(s))}var L$=R$;function U$(s,e){return s==null?void 0:s[e]}var z$=U$,F$=L$,q$=z$;function B$(s,e){var t=q$(s,e);return F$(t)?t:void 0}var ju=B$,H$=ju,W$=Zn,V$=H$(W$,"Map"),iy=V$,K$=ju,G$=K$(Object,"create"),Jc=G$,Fp=Jc;function Y$(){this.__data__=Fp?Fp(null):{},this.size=0}var Q$=Y$;function Z$(s){var e=this.has(s)&&delete this.__data__[s];return this.size-=e?1:0,e}var J$=Z$,X$=Jc,eP="__lodash_hash_undefined__",tP=Object.prototype,sP=tP.hasOwnProperty;function iP(s){var e=this.__data__;if(X$){var t=e[s];return t===eP?void 0:t}return sP.call(e,s)?e[s]:void 0}var rP=iP,nP=Jc,oP=Object.prototype,aP=oP.hasOwnProperty;function cP(s){var e=this.__data__;return nP?e[s]!==void 0:aP.call(e,s)}var lP=cP,hP=Jc,uP="__lodash_hash_undefined__";function dP(s,e){var t=this.__data__;return this.size+=this.has(s)?0:1,t[s]=hP&&e===void 0?uP:e,this}var pP=dP,gP=Q$,fP=J$,mP=rP,wP=lP,yP=pP;function vn(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}vn.prototype.clear=gP,vn.prototype.delete=fP,vn.prototype.get=mP,vn.prototype.has=wP,vn.prototype.set=yP;var bP=vn,qp=bP,vP=Qc,IP=iy;function EP(){this.size=0,this.__data__={hash:new qp,map:new(IP||vP),string:new qp}}var AP=EP;function NP(s){var e=typeof s;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?s!=="__proto__":s===null}var _P=NP,CP=_P;function SP(s,e){var t=s.__data__;return CP(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Xc=SP,$P=Xc;function PP(s){var e=$P(this,s).delete(s);return this.size-=e?1:0,e}var TP=PP,MP=Xc;function OP(s){return MP(this,s).get(s)}var xP=OP,DP=Xc;function kP(s){return DP(this,s).has(s)}var jP=kP,RP=Xc;function LP(s,e){var t=RP(this,s),i=t.size;return t.set(s,e),this.size+=t.size==i?0:1,this}var UP=LP,zP=AP,FP=TP,qP=xP,BP=jP,HP=UP;function In(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}In.prototype.clear=zP,In.prototype.delete=FP,In.prototype.get=qP,In.prototype.has=BP,In.prototype.set=HP;var WP=In,VP=Qc,KP=iy,GP=WP,YP=200;function QP(s,e){var t=this.__data__;if(t instanceof VP){var i=t.__data__;if(!KP||i.length<YP-1)return i.push([s,e]),this.size=++t.size,this;t=this.__data__=new GP(i)}return t.set(s,e),this.size=t.size,this}var ZP=QP,JP=Qc,XP=RS,eT=US,tT=FS,sT=BS,iT=ZP;function En(s){var e=this.__data__=new JP(s);this.size=e.size}En.prototype.clear=XP,En.prototype.delete=eT,En.prototype.get=tT,En.prototype.has=sT,En.prototype.set=iT;var rT=En,nT=ju,oT=function(){try{var s=nT(Object,"defineProperty");return s({},"",{}),s}catch{}}(),ry=oT,Bp=ry;function aT(s,e,t){e=="__proto__"&&Bp?Bp(s,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):s[e]=t}var Ru=aT,cT=Ru,lT=Gc;function hT(s,e,t){(t!==void 0&&!lT(s[e],t)||t===void 0&&!(e in s))&&cT(s,e,t)}var ny=hT;function uT(s){return function(e,t,i){for(var r=-1,n=Object(e),o=i(e),a=o.length;a--;){var l=o[s?a:++r];if(t(n[l],l,n)===!1)break}return e}}var dT=uT,pT=dT,gT=pT(),fT=gT,Lh={exports:{}};(function(s,e){var t=Zn,i=e&&!e.nodeType&&e,r=i&&!0&&s&&!s.nodeType&&s,n=r&&r.exports===i,o=n?t.Buffer:void 0,a=o?o.allocUnsafe:void 0;function l(c,h){if(h)return c.slice();var u=c.length,d=a?a(u):new c.constructor(u);return c.copy(d),d}s.exports=l})(Lh,Lh.exports);var mT=Zn,wT=mT.Uint8Array,yT=wT,Hp=yT;function bT(s){var e=new s.constructor(s.byteLength);return new Hp(e).set(new Hp(s)),e}var vT=bT,IT=vT;function ET(s,e){var t=e?IT(s.buffer):s.buffer;return new s.constructor(t,s.byteOffset,s.length)}var AT=ET;function NT(s,e){var t=-1,i=s.length;for(e||(e=Array(i));++t<i;)e[t]=s[t];return e}var _T=NT,CT=Mr,Wp=Object.create,ST=function(){function s(){}return function(e){if(!CT(e))return{};if(Wp)return Wp(e);s.prototype=e;var t=new s;return s.prototype=void 0,t}}(),$T=ST;function PT(s,e){return function(t){return s(e(t))}}var TT=PT,MT=TT,OT=MT(Object.getPrototypeOf,Object),oy=OT,xT=Object.prototype;function DT(s){var e=s&&s.constructor,t=typeof e=="function"&&e.prototype||xT;return s===t}var ay=DT,kT=$T,jT=oy,RT=ay;function LT(s){return typeof s.constructor=="function"&&!RT(s)?kT(jT(s)):{}}var UT=LT;function zT(s){return s!=null&&typeof s=="object"}var ba=zT,FT=Zc,qT=ba,BT="[object Arguments]";function HT(s){return qT(s)&&FT(s)==BT}var WT=HT,Vp=WT,VT=ba,cy=Object.prototype,KT=cy.hasOwnProperty,GT=cy.propertyIsEnumerable,YT=Vp(function(){return arguments}())?Vp:function(s){return VT(s)&&KT.call(s,"callee")&&!GT.call(s,"callee")},ly=YT,QT=Array.isArray,hy=QT,ZT=9007199254740991;function JT(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=ZT}var uy=JT,XT=ku,e2=uy;function t2(s){return s!=null&&e2(s.length)&&!XT(s)}var Lu=t2,s2=Lu,i2=ba;function r2(s){return i2(s)&&s2(s)}var n2=r2,Sc={exports:{}};function o2(){return!1}var a2=o2;(function(s,e){var t=Zn,i=a2,r=e&&!e.nodeType&&e,n=r&&!0&&s&&!s.nodeType&&s,o=n&&n.exports===r,a=o?t.Buffer:void 0,l=a?a.isBuffer:void 0,c=l||i;s.exports=c})(Sc,Sc.exports);var c2=Zc,l2=oy,h2=ba,u2="[object Object]",d2=Function.prototype,p2=Object.prototype,dy=d2.toString,g2=p2.hasOwnProperty,f2=dy.call(Object);function m2(s){if(!h2(s)||c2(s)!=u2)return!1;var e=l2(s);if(e===null)return!0;var t=g2.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&dy.call(t)==f2}var w2=m2,y2=Zc,b2=uy,v2=ba,I2="[object Arguments]",E2="[object Array]",A2="[object Boolean]",N2="[object Date]",_2="[object Error]",C2="[object Function]",S2="[object Map]",$2="[object Number]",P2="[object Object]",T2="[object RegExp]",M2="[object Set]",O2="[object String]",x2="[object WeakMap]",D2="[object ArrayBuffer]",k2="[object DataView]",j2="[object Float32Array]",R2="[object Float64Array]",L2="[object Int8Array]",U2="[object Int16Array]",z2="[object Int32Array]",F2="[object Uint8Array]",q2="[object Uint8ClampedArray]",B2="[object Uint16Array]",H2="[object Uint32Array]",We={};We[j2]=We[R2]=We[L2]=We[U2]=We[z2]=We[F2]=We[q2]=We[B2]=We[H2]=!0,We[I2]=We[E2]=We[D2]=We[A2]=We[k2]=We[N2]=We[_2]=We[C2]=We[S2]=We[$2]=We[P2]=We[T2]=We[M2]=We[O2]=We[x2]=!1;function W2(s){return v2(s)&&b2(s.length)&&!!We[y2(s)]}var V2=W2;function K2(s){return function(e){return s(e)}}var G2=K2,Uh={exports:{}};(function(s,e){var t=ey,i=e&&!e.nodeType&&e,r=i&&!0&&s&&!s.nodeType&&s,n=r&&r.exports===i,o=n&&t.process,a=function(){try{var l=r&&r.require&&r.require("util").types;return l||o&&o.binding&&o.binding("util")}catch{}}();s.exports=a})(Uh,Uh.exports);var Y2=V2,Q2=G2,Kp=Uh.exports,Gp=Kp&&Kp.isTypedArray,Z2=Gp?Q2(Gp):Y2,py=Z2;function J2(s,e){if(!(e==="constructor"&&typeof s[e]=="function")&&e!="__proto__")return s[e]}var gy=J2,X2=Ru,eM=Gc,tM=Object.prototype,sM=tM.hasOwnProperty;function iM(s,e,t){var i=s[e];(!(sM.call(s,e)&&eM(i,t))||t===void 0&&!(e in s))&&X2(s,e,t)}var rM=iM,nM=rM,oM=Ru;function aM(s,e,t,i){var r=!t;t||(t={});for(var n=-1,o=e.length;++n<o;){var a=e[n],l=i?i(t[a],s[a],a,t,s):void 0;l===void 0&&(l=s[a]),r?oM(t,a,l):nM(t,a,l)}return t}var cM=aM;function lM(s,e){for(var t=-1,i=Array(s);++t<s;)i[t]=e(t);return i}var hM=lM,uM=9007199254740991,dM=/^(?:0|[1-9]\d*)$/;function pM(s,e){var t=typeof s;return e=e??uM,!!e&&(t=="number"||t!="symbol"&&dM.test(s))&&s>-1&&s%1==0&&s<e}var fy=pM,gM=hM,fM=ly,mM=hy,wM=Sc.exports,yM=fy,bM=py,vM=Object.prototype,IM=vM.hasOwnProperty;function EM(s,e){var t=mM(s),i=!t&&fM(s),r=!t&&!i&&wM(s),n=!t&&!i&&!r&&bM(s),o=t||i||r||n,a=o?gM(s.length,String):[],l=a.length;for(var c in s)(e||IM.call(s,c))&&!(o&&(c=="length"||r&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||yM(c,l)))&&a.push(c);return a}var AM=EM;function NM(s){var e=[];if(s!=null)for(var t in Object(s))e.push(t);return e}var _M=NM,CM=Mr,SM=ay,$M=_M,PM=Object.prototype,TM=PM.hasOwnProperty;function MM(s){if(!CM(s))return $M(s);var e=SM(s),t=[];for(var i in s)i=="constructor"&&(e||!TM.call(s,i))||t.push(i);return t}var OM=MM,xM=AM,DM=OM,kM=Lu;function jM(s){return kM(s)?xM(s,!0):DM(s)}var my=jM,RM=cM,LM=my;function UM(s){return RM(s,LM(s))}var zM=UM,Yp=ny,FM=Lh.exports,qM=AT,BM=_T,HM=UT,Qp=ly,Zp=hy,WM=n2,VM=Sc.exports,KM=ku,GM=Mr,YM=w2,QM=py,Jp=gy,ZM=zM;function JM(s,e,t,i,r,n,o){var a=Jp(s,t),l=Jp(e,t),c=o.get(l);if(c){Yp(s,t,c);return}var h=n?n(a,l,t+"",s,e,o):void 0,u=h===void 0;if(u){var d=Zp(l),p=!d&&VM(l),g=!d&&!p&&QM(l);h=l,d||p||g?Zp(a)?h=a:WM(a)?h=BM(a):p?(u=!1,h=FM(l,!0)):g?(u=!1,h=qM(l,!0)):h=[]:YM(l)||Qp(l)?(h=a,Qp(a)?h=ZM(a):(!GM(a)||KM(a))&&(h=HM(l))):u=!1}u&&(o.set(l,h),r(h,l,i,n,o),o.delete(l)),Yp(s,t,h)}var XM=JM,eO=rT,tO=ny,sO=fT,iO=XM,rO=Mr,nO=my,oO=gy;function wy(s,e,t,i,r){s!==e&&sO(e,function(n,o){if(r||(r=new eO),rO(n))iO(s,e,o,t,wy,i,r);else{var a=i?i(oO(s,o),n,o+"",s,e,r):void 0;a===void 0&&(a=n),tO(s,o,a)}},nO)}var aO=wy;function cO(s){return s}var yy=cO;function lO(s,e,t){switch(t.length){case 0:return s.call(e);case 1:return s.call(e,t[0]);case 2:return s.call(e,t[0],t[1]);case 3:return s.call(e,t[0],t[1],t[2])}return s.apply(e,t)}var hO=lO,uO=hO,Xp=Math.max;function dO(s,e,t){return e=Xp(e===void 0?s.length-1:e,0),function(){for(var i=arguments,r=-1,n=Xp(i.length-e,0),o=Array(n);++r<n;)o[r]=i[e+r];r=-1;for(var a=Array(e+1);++r<e;)a[r]=i[r];return a[e]=t(o),uO(s,this,a)}}var pO=dO;function gO(s){return function(){return s}}var fO=gO,mO=fO,eg=ry,wO=yy,yO=eg?function(s,e){return eg(s,"toString",{configurable:!0,enumerable:!1,value:mO(e),writable:!0})}:wO,bO=yO,vO=800,IO=16,EO=Date.now;function AO(s){var e=0,t=0;return function(){var i=EO(),r=IO-(i-t);if(t=i,r>0){if(++e>=vO)return arguments[0]}else e=0;return s.apply(void 0,arguments)}}var NO=AO,_O=bO,CO=NO,SO=CO(_O),$O=SO,PO=yy,TO=pO,MO=$O;function OO(s,e){return MO(TO(s,e,PO),s+"")}var xO=OO,DO=Gc,kO=Lu,jO=fy,RO=Mr;function LO(s,e,t){if(!RO(t))return!1;var i=typeof e;return(i=="number"?kO(t)&&jO(e,t.length):i=="string"&&e in t)?DO(t[e],s):!1}var UO=LO,zO=xO,FO=UO;function qO(s){return zO(function(e,t){var i=-1,r=t.length,n=r>1?t[r-1]:void 0,o=r>2?t[2]:void 0;for(n=s.length>3&&typeof n=="function"?(r--,n):void 0,o&&FO(t[0],t[1],o)&&(n=r<3?void 0:n,r=1),e=Object(e);++i<r;){var a=t[i];a&&s(e,a,i,n)}return e})}var BO=qO,HO=aO,WO=BO,VO=WO(function(s,e,t){HO(s,e,t)}),KO=VO,GO=Object.defineProperty,YO=Object.defineProperties,QO=Object.getOwnPropertyDescriptors,tg=Object.getOwnPropertySymbols,ZO=Object.prototype.hasOwnProperty,JO=Object.prototype.propertyIsEnumerable,sg=(s,e,t)=>e in s?GO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,La=(s,e)=>{for(var t in e||(e={}))ZO.call(e,t)&&sg(s,t,e[t]);if(tg)for(var t of tg(e))JO.call(e,t)&&sg(s,t,e[t]);return s},XO=(s,e)=>YO(s,QO(e));function ws(s,e,t){var i;const r=On(s);return((i=e.rpcMap)==null?void 0:i[r.reference])||`${Xw}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Or(s){return s.includes(":")?s.split(":")[1]:s}function by(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function ex(s,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(s));if(!t.length)return[];const i=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;i.push(...n)}),i}function Tl(s={},e={}){const t=ig(s),i=ig(e);return KO(t,i)}function ig(s){var e,t,i,r;const n={};if(!Jo(s))return n;for(const[o,a]of Object.entries(s)){const l=Ou(o)?[o]:a.chains,c=a.methods||[],h=a.events||[],u=a.rpcMap||{},d=Po(o);n[d]=XO(La(La({},n[d]),a),{chains:ic(l,(e=n[d])==null?void 0:e.chains),methods:ic(c,(t=n[d])==null?void 0:t.methods),events:ic(h,(i=n[d])==null?void 0:i.events),rpcMap:La(La({},u),(r=n[d])==null?void 0:r.rpcMap)})}return n}function tx(s){return s.includes(":")?s.split(":")[2]:s}function rg(s){const e={};for(const[t,i]of Object.entries(s)){const r=i.methods||[],n=i.events||[],o=i.accounts||[],a=Ou(t)?[t]:i.chains?i.chains:by(i.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Ml(s){return typeof s=="number"?s:s.includes("0x")?parseInt(s,16):(s=s.includes(":")?s.split(":")[1]:s,isNaN(Number(s))?s:Number(s))}const vy={},we=s=>vy[s],Ol=(s,e)=>{vy[s]=e};var sx=Object.defineProperty,ix=(s,e,t)=>e in s?sx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Br=(s,e,t)=>ix(s,typeof e!="symbol"?e+"":e,t);class rx{constructor(e){Br(this,"name","polkadot"),Br(this,"client"),Br(this,"httpProviders"),Br(this,"events"),Br(this,"namespace"),Br(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Or(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var nx=Object.defineProperty,ox=Object.defineProperties,ax=Object.getOwnPropertyDescriptors,ng=Object.getOwnPropertySymbols,cx=Object.prototype.hasOwnProperty,lx=Object.prototype.propertyIsEnumerable,zh=(s,e,t)=>e in s?nx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,og=(s,e)=>{for(var t in e||(e={}))cx.call(e,t)&&zh(s,t,e[t]);if(ng)for(var t of ng(e))lx.call(e,t)&&zh(s,t,e[t]);return s},ag=(s,e)=>ox(s,ax(e)),Hr=(s,e,t)=>zh(s,typeof e!="symbol"?e+"":e,t);class hx{constructor(e){Hr(this,"name","eip155"),Hr(this,"client"),Hr(this,"chainId"),Hr(this,"namespace"),Hr(this,"httpProviders"),Hr(this,"events"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(Ts.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,t){const i=t||ws(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=parseInt(Or(t));e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let r=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const n=parseInt(r,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:r}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,r;const n=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0];if(!n)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const o=this.client.session.get(e.topic),a=((r=o==null?void 0:o.sessionProperties)==null?void 0:r.capabilities)||{};if(a!=null&&a[n])return a==null?void 0:a[n];const l=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ag(og({},o.sessionProperties||{}),{capabilities:ag(og({},a||{}),{[n]:l})})})}catch(c){console.warn("Failed to update session with capabilities",c)}return l}async getCallStatus(e){var t,i;const r=this.client.session.get(e.topic),n=(t=r.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from bundler",l,a)}}const o=(i=r.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Gt("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${hS}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var ux=Object.defineProperty,dx=(s,e,t)=>e in s?ux(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Wr=(s,e,t)=>dx(s,typeof e!="symbol"?e+"":e,t);class px{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=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Or(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var gx=Object.defineProperty,fx=(s,e,t)=>e in s?gx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Vr=(s,e,t)=>fx(s,typeof e!="symbol"?e+"":e,t);class mx{constructor(e){Vr(this,"name","cosmos"),Vr(this,"client"),Vr(this,"httpProviders"),Vr(this,"events"),Vr(this,"namespace"),Vr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Or(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var wx=Object.defineProperty,yx=(s,e,t)=>e in s?wx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Kr=(s,e,t)=>yx(s,typeof e!="symbol"?e+"":e,t);class bx{constructor(e){Kr(this,"name","algorand"),Kr(this,"client"),Kr(this,"httpProviders"),Kr(this,"events"),Kr(this,"namespace"),Kr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){if(!this.httpProviders[e]){const i=t||ws(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(Ts.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new Ye(new tt(i,we("disableProviderPing")))}}var vx=Object.defineProperty,Ix=(s,e,t)=>e in s?vx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Gr=(s,e,t)=>Ix(s,typeof e!="symbol"?e+"":e,t);class Ex{constructor(e){Gr(this,"name","cip34"),Gr(this,"client"),Gr(this,"httpProviders"),Gr(this,"events"),Gr(this,"namespace"),Gr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),r=Or(t);e[r]=this.createHttpProvider(r,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var Ax=Object.defineProperty,Nx=(s,e,t)=>e in s?Ax(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Yr=(s,e,t)=>Nx(s,typeof e!="symbol"?e+"":e,t);class _x{constructor(e){Yr(this,"name","elrond"),Yr(this,"client"),Yr(this,"httpProviders"),Yr(this,"events"),Yr(this,"namespace"),Yr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Or(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var Cx=Object.defineProperty,Sx=(s,e,t)=>e in s?Cx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Qr=(s,e,t)=>Sx(s,typeof e!="symbol"?e+"":e,t);class $x{constructor(e){Qr(this,"name","multiversx"),Qr(this,"client"),Qr(this,"httpProviders"),Qr(this,"events"),Qr(this,"namespace"),Qr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Or(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var Px=Object.defineProperty,Tx=(s,e,t)=>e in s?Px(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Zr=(s,e,t)=>Tx(s,typeof e!="symbol"?e+"":e,t);class Mx{constructor(e){Zr(this,"name","near"),Zr(this,"client"),Zr(this,"httpProviders"),Zr(this,"events"),Zr(this,"namespace"),Zr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||ws(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Ts.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace);return typeof i>"u"?void 0:new Ye(new tt(i,we("disableProviderPing")))}}var Ox=Object.defineProperty,xx=(s,e,t)=>e in s?Ox(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Jr=(s,e,t)=>xx(s,typeof e!="symbol"?e+"":e,t);class Dx{constructor(e){Jr(this,"name","tezos"),Jr(this,"client"),Jr(this,"httpProviders"),Jr(this,"events"),Jr(this,"namespace"),Jr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||ws(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Ts.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace);return typeof i>"u"?void 0:new Ye(new tt(i))}}var kx=Object.defineProperty,jx=(s,e,t)=>e in s?kx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Xr=(s,e,t)=>jx(s,typeof e!="symbol"?e+"":e,t);class Rx{constructor(e){Xr(this,"name",yn),Xr(this,"client"),Xr(this,"httpProviders"),Xr(this,"events"),Xr(this,"namespace"),Xr(this,"chainId"),this.namespace=e.namespace,this.events=we("events"),this.client=we("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ts.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=On(r);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ws(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,we("disableProviderPing")))}}var Lx=Object.defineProperty,Ux=Object.defineProperties,zx=Object.getOwnPropertyDescriptors,cg=Object.getOwnPropertySymbols,Fx=Object.prototype.hasOwnProperty,qx=Object.prototype.propertyIsEnumerable,Fh=(s,e,t)=>e in s?Lx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ua=(s,e)=>{for(var t in e||(e={}))Fx.call(e,t)&&Fh(s,t,e[t]);if(cg)for(var t of cg(e))qx.call(e,t)&&Fh(s,t,e[t]);return s},xl=(s,e)=>Ux(s,zx(e)),ks=(s,e,t)=>Fh(s,typeof e!="symbol"?e+"":e,t);class Uu{constructor(e){ks(this,"client"),ks(this,"namespaces"),ks(this,"optionalNamespaces"),ks(this,"sessionProperties"),ks(this,"events",new Kn),ks(this,"rpcProviders",{}),ks(this,"session"),ks(this,"providerOpts"),ks(this,"logger"),ks(this,"uri"),ks(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Wn(yi({level:(e==null?void 0:e.logger)||kp})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Uu(e);return await t.initialize(),t}async request(e,t,i){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Ua({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,r){const n=new Date().getTime();this.request(e,i,r).then(o=>t(null,Wi(n,o))).catch(o=>t(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}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:r}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await r();if(this.session=n.session,this.session){const o=rg(this.session.namespaces);this.namespaces=Tl(this.namespaces,o),this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await i();this.session=r;const n=rg(r.namespaces);return this.namespaces=Tl(this.namespaces,n),this.persist("namespaces",this.namespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,r]=this.validateChain(e),n=this.getProvider(i);n.name===yn?n.setDefaultChain(`${i}:${r}`,t):n.setDefaultChain(r,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(vr(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await oS.init({core:this.providerOpts.core,logger:this.providerOpts.logger||kp,relayUrl:this.providerOpts.relayUrl||aS,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.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(t=>Po(t)))];Ol("client",this.client),Ol("events",this.events),Ol("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=ex(t,this.session),r=by(i),n=Tl(this.namespaces,this.optionalNamespaces),o=xl(Ua({},n[t]),{accounts:i,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new hx({namespace:o});break;case"algorand":this.rpcProviders[t]=new bx({namespace:o});break;case"solana":this.rpcProviders[t]=new px({namespace:o});break;case"cosmos":this.rpcProviders[t]=new mx({namespace:o});break;case"polkadot":this.rpcProviders[t]=new rx({namespace:o});break;case"cip34":this.rpcProviders[t]=new Ex({namespace:o});break;case"elrond":this.rpcProviders[t]=new _x({namespace:o});break;case"multiversx":this.rpcProviders[t]=new $x({namespace:o});break;case"near":this.rpcProviders[t]=new Mx({namespace:o});break;case"tezos":this.rpcProviders[t]=new Dx({namespace:o});break;default:this.rpcProviders[yn]?this.rpcProviders[yn].updateNamespace(o):this.rpcProviders[yn]=new Rx({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:t}=e,{event:i}=t;if(i.name==="accountsChanged"){const r=i.data;r&&vr(r)&&this.events.emit("accountsChanged",r.map(tx))}else if(i.name==="chainChanged"){const r=t.chainId,n=t.event.data,o=Po(r),a=Ml(r)!==Ml(n)?`${o}:${Ml(n)}`:r;this.onChainChanged(a)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i;const{namespaces:r}=t,n=(i=this.client)==null?void 0:i.session.get(e);this.session=xl(Ua({},n),{namespaces:r}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",xl(Ua({},Te("USER_DISCONNECTED")),{data:e.topic}))}),this.on(Ts.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[yn]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t,optionalNamespaces:i,sessionProperties:r}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=r,this.persist("namespaces",t),this.persist("optionalNamespaces",i)}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>Po(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const r=Po(Object.keys(this.namespaces)[0]),n=this.rpcProviders[r].getDefaultChain();return[r,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,r]=this.validateChain(e);r&&(t||this.getProvider(i).setDefaultChain(r),this.namespaces[i]?this.namespaces[i].defaultChain=r:this.namespaces[`${i}:${r}`]?this.namespaces[`${i}:${r}`].defaultChain=r:this.namespaces[`${i}:${r}`]={defaultChain:r},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",r))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(e,t){this.client.core.storage.setItem(`${jp}/${e}`,t)}async getFromStore(e){return await this.client.core.storage.getItem(`${jp}/${e}`)}}const Bx=Uu,Iy={caipNetworkIdToNumber(s){return s?Number(s.split(":")[1]):void 0},parseEvmChainId(s){return typeof s=="string"?this.caipNetworkIdToNumber(s):s},getNetworksByNamespace(s,e){return(s==null?void 0:s.filter(t=>t.chainNamespace===e))||[]},getFirstNetworkByNamespace(s,e){return this.getNetworksByNamespace(s,e)[0]}};var Hx=20,Wx=1,Jn=1e6,Vx=1e6,Kx=-7,Gx=21,Yx=!1,va="[big.js] ",xr=va+"Invalid ",el=xr+"decimal places",Qx=xr+"rounding mode",Ey=va+"Division by zero",$e={},ti=void 0,Zx=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Ay(){function s(e){var t=this;if(!(t instanceof s))return e===ti?Ay():new s(e);if(e instanceof s)t.s=e.s,t.e=e.e,t.c=e.c.slice();else{if(typeof e!="string"){if(s.strict===!0&&typeof e!="bigint")throw TypeError(xr+"value");e=e===0&&1/e<0?"-0":String(e)}Jx(t,e)}t.constructor=s}return s.prototype=$e,s.DP=Hx,s.RM=Wx,s.NE=Kx,s.PE=Gx,s.strict=Yx,s.roundDown=0,s.roundHalfUp=1,s.roundHalfEven=2,s.roundUp=3,s}function Jx(s,e){var t,i,r;if(!Zx.test(e))throw Error(xr+"number");for(s.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(t=e.indexOf("."))>-1&&(e=e.replace(".","")),(i=e.search(/e/i))>0?(t<0&&(t=i),t+=+e.slice(i+1),e=e.substring(0,i)):t<0&&(t=e.length),r=e.length,i=0;i<r&&e.charAt(i)=="0";)++i;if(i==r)s.c=[s.e=0];else{for(;r>0&&e.charAt(--r)=="0";);for(s.e=t-i-1,s.c=[],t=0;i<=r;)s.c[t++]=+e.charAt(i++)}return s}function Dr(s,e,t,i){var r=s.c;if(t===ti&&(t=s.constructor.RM),t!==0&&t!==1&&t!==2&&t!==3)throw Error(Qx);if(e<1)i=t===3&&(i||!!r[0])||e===0&&(t===1&&r[0]>=5||t===2&&(r[0]>5||r[0]===5&&(i||r[1]!==ti))),r.length=1,i?(s.e=s.e-e+1,r[0]=1):r[0]=s.e=0;else if(e<r.length){if(i=t===1&&r[e]>=5||t===2&&(r[e]>5||r[e]===5&&(i||r[e+1]!==ti||r[e-1]&1))||t===3&&(i||!!r[0]),r.length=e,i){for(;++r[--e]>9;)if(r[e]=0,e===0){++s.e,r.unshift(1);break}}for(e=r.length;!r[--e];)r.pop()}return s}function kr(s,e,t){var i=s.e,r=s.c.join(""),n=r.length;if(e)r=r.charAt(0)+(n>1?"."+r.slice(1):"")+(i<0?"e":"e+")+i;else if(i<0){for(;++i;)r="0"+r;r="0."+r}else if(i>0)if(++i>n)for(i-=n;i--;)r+="0";else i<n&&(r=r.slice(0,i)+"."+r.slice(i));else n>1&&(r=r.charAt(0)+"."+r.slice(1));return s.s<0&&t?"-"+r:r}$e.abs=function(){var s=new this.constructor(this);return s.s=1,s};$e.cmp=function(s){var e,t=this,i=t.c,r=(s=new t.constructor(s)).c,n=t.s,o=s.s,a=t.e,l=s.e;if(!i[0]||!r[0])return i[0]?n:r[0]?-o:0;if(n!=o)return n;if(e=n<0,a!=l)return a>l^e?1:-1;for(o=(a=i.length)<(l=r.length)?a:l,n=-1;++n<o;)if(i[n]!=r[n])return i[n]>r[n]^e?1:-1;return a==l?0:a>l^e?1:-1};$e.div=function(s){var e=this,t=e.constructor,i=e.c,r=(s=new t(s)).c,n=e.s==s.s?1:-1,o=t.DP;if(o!==~~o||o<0||o>Jn)throw Error(el);if(!r[0])throw Error(Ey);if(!i[0])return s.s=n,s.c=[s.e=0],s;var a,l,c,h,u,d=r.slice(),p=a=r.length,g=i.length,f=i.slice(0,a),y=f.length,w=s,m=w.c=[],b=0,I=o+(w.e=e.e-s.e)+1;for(w.s=n,n=I<0?0:I,d.unshift(0);y++<a;)f.push(0);do{for(c=0;c<10;c++){if(a!=(y=f.length))h=a>y?1:-1;else for(u=-1,h=0;++u<a;)if(r[u]!=f[u]){h=r[u]>f[u]?1:-1;break}if(h<0){for(l=y==a?r:d;y;){if(f[--y]<l[y]){for(u=y;u&&!f[--u];)f[u]=9;--f[u],f[y]+=10}f[y]-=l[y]}for(;!f[0];)f.shift()}else break}m[b++]=h?c:++c,f[0]&&h?f[y]=i[p]||0:f=[i[p]]}while((p++<g||f[0]!==ti)&&n--);return!m[0]&&b!=1&&(m.shift(),w.e--,I--),b>I&&Dr(w,I,t.RM,f[0]!==ti),w};$e.eq=function(s){return this.cmp(s)===0};$e.gt=function(s){return this.cmp(s)>0};$e.gte=function(s){return this.cmp(s)>-1};$e.lt=function(s){return this.cmp(s)<0};$e.lte=function(s){return this.cmp(s)<1};$e.minus=$e.sub=function(s){var e,t,i,r,n=this,o=n.constructor,a=n.s,l=(s=new o(s)).s;if(a!=l)return s.s=-l,n.plus(s);var c=n.c.slice(),h=n.e,u=s.c,d=s.e;if(!c[0]||!u[0])return u[0]?s.s=-l:c[0]?s=new o(n):s.s=1,s;if(a=h-d){for((r=a<0)?(a=-a,i=c):(d=h,i=u),i.reverse(),l=a;l--;)i.push(0);i.reverse()}else for(t=((r=c.length<u.length)?c:u).length,a=l=0;l<t;l++)if(c[l]!=u[l]){r=c[l]<u[l];break}if(r&&(i=c,c=u,u=i,s.s=-s.s),(l=(t=u.length)-(e=c.length))>0)for(;l--;)c[e++]=0;for(l=e;t>a;){if(c[--t]<u[t]){for(e=t;e&&!c[--e];)c[e]=9;--c[e],c[t]+=10}c[t]-=u[t]}for(;c[--l]===0;)c.pop();for(;c[0]===0;)c.shift(),--d;return c[0]||(s.s=1,c=[d=0]),s.c=c,s.e=d,s};$e.mod=function(s){var e,t=this,i=t.constructor,r=t.s,n=(s=new i(s)).s;if(!s.c[0])throw Error(Ey);return t.s=s.s=1,e=s.cmp(t)==1,t.s=r,s.s=n,e?new i(t):(r=i.DP,n=i.RM,i.DP=i.RM=0,t=t.div(s),i.DP=r,i.RM=n,this.minus(t.times(s)))};$e.neg=function(){var s=new this.constructor(this);return s.s=-s.s,s};$e.plus=$e.add=function(s){var e,t,i,r=this,n=r.constructor;if(s=new n(s),r.s!=s.s)return s.s=-s.s,r.minus(s);var o=r.e,a=r.c,l=s.e,c=s.c;if(!a[0]||!c[0])return c[0]||(a[0]?s=new n(r):s.s=r.s),s;if(a=a.slice(),e=o-l){for(e>0?(l=o,i=c):(e=-e,i=a),i.reverse();e--;)i.push(0);i.reverse()}for(a.length-c.length<0&&(i=c,c=a,a=i),e=c.length,t=0;e;a[e]%=10)t=(a[--e]=a[e]+c[e]+t)/10|0;for(t&&(a.unshift(t),++l),e=a.length;a[--e]===0;)a.pop();return s.c=a,s.e=l,s};$e.pow=function(s){var e=this,t=new e.constructor("1"),i=t,r=s<0;if(s!==~~s||s<-1e6||s>Vx)throw Error(xr+"exponent");for(r&&(s=-s);s&1&&(i=i.times(e)),s>>=1,!!s;)e=e.times(e);return r?t.div(i):i};$e.prec=function(s,e){if(s!==~~s||s<1||s>Jn)throw Error(xr+"precision");return Dr(new this.constructor(this),s,e)};$e.round=function(s,e){if(s===ti)s=0;else if(s!==~~s||s<-1e6||s>Jn)throw Error(el);return Dr(new this.constructor(this),s+this.e+1,e)};$e.sqrt=function(){var s,e,t,i=this,r=i.constructor,n=i.s,o=i.e,a=new r("0.5");if(!i.c[0])return new r(i);if(n<0)throw Error(va+"No square root");n=Math.sqrt(+kr(i,!0,!0)),n===0||n===1/0?(e=i.c.join(""),e.length+o&1||(e+="0"),n=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),s=new r((n==1/0?"5e":(n=n.toExponential()).slice(0,n.indexOf("e")+1))+o)):s=new r(n+""),o=s.e+(r.DP+=4);do t=s,s=a.times(t.plus(i.div(t)));while(t.c.slice(0,o).join("")!==s.c.slice(0,o).join(""));return Dr(s,(r.DP-=4)+s.e+1,r.RM)};$e.times=$e.mul=function(s){var e,t=this,i=t.constructor,r=t.c,n=(s=new i(s)).c,o=r.length,a=n.length,l=t.e,c=s.e;if(s.s=t.s==s.s?1:-1,!r[0]||!n[0])return s.c=[s.e=0],s;for(s.e=l+c,o<a&&(e=r,r=n,n=e,c=o,o=a,a=c),e=new Array(c=o+a);c--;)e[c]=0;for(l=a;l--;){for(a=0,c=o+l;c>l;)a=e[c]+n[l]*r[c-l-1]+a,e[c--]=a%10,a=a/10|0;e[c]=a}for(a?++s.e:e.shift(),l=e.length;!e[--l];)e.pop();return s.c=e,s};$e.toExponential=function(s,e){var t=this,i=t.c[0];if(s!==ti){if(s!==~~s||s<0||s>Jn)throw Error(el);for(t=Dr(new t.constructor(t),++s,e);t.c.length<s;)t.c.push(0)}return kr(t,!0,!!i)};$e.toFixed=function(s,e){var t=this,i=t.c[0];if(s!==ti){if(s!==~~s||s<0||s>Jn)throw Error(el);for(t=Dr(new t.constructor(t),s+t.e+1,e),s=s+t.e+1;t.c.length<s;)t.c.push(0)}return kr(t,!1,!!i)};$e[Symbol.for("nodejs.util.inspect.custom")]=$e.toJSON=$e.toString=function(){var s=this,e=s.constructor;return kr(s,s.e<=e.NE||s.e>=e.PE,!!s.c[0])};$e.toNumber=function(){var s=+kr(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(s.toString()))throw Error(va+"Imprecise conversion");return s};$e.toPrecision=function(s,e){var t=this,i=t.constructor,r=t.c[0];if(s!==ti){if(s!==~~s||s<1||s>Jn)throw Error(xr+"precision");for(t=Dr(new i(t),s,e);t.c.length<s;)t.c.push(0)}return kr(t,s<=t.e||t.e<=i.NE||t.e>=i.PE,!!r)};$e.valueOf=function(){var s=this,e=s.constructor;if(e.strict===!0)throw Error(va+"valueOf disallowed");return kr(s,s.e<=e.NE||s.e>=e.PE,!0)};var fo=Ay();const za={bigNumber(s){return s?new fo(s):new fo(0)},multiply(s,e){if(s===void 0||e===void 0)return new fo(0);const t=new fo(s),i=new fo(e);return t.times(i)},formatNumberToLocalString(s,e=2){return s===void 0?"0.00":typeof s=="number"?s.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(s).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(s){return s===void 0?0:parseFloat(s.replace(/,/gu,""))}},Xx=[{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"}]}],eD=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],tD=[{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"}]}],Q={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"},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"},sD={getERC20Abi:s=>Q.USDT_CONTRACT_ADDRESSES.includes(s)?tD:Xx,getSwapAbi:()=>eD},Ii={validateCaipAddress(s){var e;if(((e=s.split(":"))==null?void 0:e.length)!==3)throw new Error("Invalid CAIP Address");return s},parseCaipAddress(s){const e=s.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${s}`);const[t,i,r]=e;if(!t||!i||!r)throw new Error(`Invalid CAIP-10 address: ${s}`);return{chainNamespace:t,chainId:i,address:r}},parseCaipNetworkId(s){const e=s.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${s}`);const[t,i]=e;if(!t||!i)throw new Error(`Invalid CAIP-2 network id: ${s}`);return{chainNamespace:t,chainId:i}}},re={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"};function Dl(s){if(!s)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${s}:connected_connector_id`}const ee={setItem(s,e){To()&&e!==void 0&&localStorage.setItem(s,e)},getItem(s){if(To())return localStorage.getItem(s)||void 0},removeItem(s){To()&&localStorage.removeItem(s)},clear(){To()&&localStorage.clear()}};function To(){return typeof window<"u"&&typeof localStorage<"u"}function Ri(s,e){return e==="light"?{"--w3m-accent":(s==null?void 0:s["--w3m-accent"])||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":(s==null?void 0:s["--w3m-accent"])||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const iD=Symbol(),lg=Object.getPrototypeOf,qh=new WeakMap,rD=s=>s&&(qh.has(s)?qh.get(s):lg(s)===Object.prototype||lg(s)===Array.prototype),nD=s=>rD(s)&&s[iD]||null,hg=(s,e=!0)=>{qh.set(s,e)},$c={},kl=s=>typeof s=="object"&&s!==null,$i=new WeakMap,Mo=new WeakSet,oD=(s=Object.is,e=(c,h)=>new Proxy(c,h),t=c=>kl(c)&&!Mo.has(c)&&(Array.isArray(c)||!(Symbol.iterator in c))&&!(c instanceof WeakMap)&&!(c instanceof WeakSet)&&!(c instanceof Error)&&!(c instanceof Number)&&!(c instanceof Date)&&!(c instanceof String)&&!(c instanceof RegExp)&&!(c instanceof ArrayBuffer),i=c=>{switch(c.status){case"fulfilled":return c.value;case"rejected":throw c.reason;default:throw c}},r=new WeakMap,n=(c,h,u=i)=>{const d=r.get(c);if((d==null?void 0:d[0])===h)return d[1];const p=Array.isArray(c)?[]:Object.create(Object.getPrototypeOf(c));return hg(p,!0),r.set(c,[h,p]),Reflect.ownKeys(c).forEach(g=>{if(Object.getOwnPropertyDescriptor(p,g))return;const f=Reflect.get(c,g),{enumerable:y}=Reflect.getOwnPropertyDescriptor(c,g),w={value:f,enumerable:y,configurable:!0};if(Mo.has(f))hg(f,!1);else if(f instanceof Promise)delete w.value,w.get=()=>u(f);else if($i.has(f)){const[m,b]=$i.get(f);w.value=n(m,b(),u)}Object.defineProperty(p,g,w)}),Object.preventExtensions(p)},o=new WeakMap,a=[1,1],l=c=>{if(!kl(c))throw new Error("object required");const h=o.get(c);if(h)return h;let u=a[0];const d=new Set,p=(C,T=++a[0])=>{u!==T&&(u=T,d.forEach(S=>S(C,T)))};let g=a[1];const f=(C=++a[1])=>(g!==C&&!d.size&&(g=C,w.forEach(([T])=>{const S=T[1](C);S>u&&(u=S)})),u),y=C=>(T,S)=>{const R=[...T];R[1]=[C,...R[1]],p(R,S)},w=new Map,m=(C,T)=>{if(($c?"production":void 0)!=="production"&&w.has(C))throw new Error("prop listener already exists");if(d.size){const S=T[3](y(C));w.set(C,[T,S])}else w.set(C,[T])},b=C=>{var T;const S=w.get(C);S&&(w.delete(C),(T=S[1])==null||T.call(S))},I=C=>(d.add(C),d.size===1&&w.forEach(([S,R],L)=>{if(($c?"production":void 0)!=="production"&&R)throw new Error("remove already exists");const q=S[3](y(L));w.set(L,[S,q])}),()=>{d.delete(C),d.size===0&&w.forEach(([S,R],L)=>{R&&(R(),w.set(L,[S]))})}),N=Array.isArray(c)?[]:Object.create(Object.getPrototypeOf(c)),P=e(N,{deleteProperty(C,T){const S=Reflect.get(C,T);b(T);const R=Reflect.deleteProperty(C,T);return R&&p(["delete",[T],S]),R},set(C,T,S,R){const L=Reflect.has(C,T),q=Reflect.get(C,T,R);if(L&&(s(q,S)||o.has(S)&&s(q,o.get(S))))return!0;b(T),kl(S)&&(S=nD(S)||S);let B=S;if(S instanceof Promise)S.then(U=>{S.status="fulfilled",S.value=U,p(["resolve",[T],U])}).catch(U=>{S.status="rejected",S.reason=U,p(["reject",[T],U])});else{!$i.has(S)&&t(S)&&(B=l(S));const U=!Mo.has(B)&&$i.get(B);U&&m(T,U)}return Reflect.set(C,T,B,R),p(["set",[T],S,q]),!0}});o.set(c,P);const O=[N,f,n,I];return $i.set(P,O),Reflect.ownKeys(c).forEach(C=>{const T=Object.getOwnPropertyDescriptor(c,C);"value"in T&&(P[C]=c[C],delete T.value,delete T.writable),Object.defineProperty(N,C,T)}),P})=>[l,$i,Mo,s,e,t,i,r,n,o,a],[aD]=oD();function Xe(s={}){return aD(s)}function Yt(s,e,t){const i=$i.get(s);($c?"production":void 0)!=="production"&&!i&&console.warn("Please use proxy object");let r;const n=[],o=i[3];let a=!1;const c=o(h=>{n.push(h),r||(r=Promise.resolve().then(()=>{r=void 0,a&&e(n.splice(0))}))});return a=!0,()=>{a=!1,c()}}function Xo(s,e){const t=$i.get(s);($c?"production":void 0)!=="production"&&!t&&console.warn("Please use proxy object");const[i,r,n]=t;return n(i,r(),e)}function Ir(s){return Mo.add(s),s}function vs(s,e,t,i){let r=s[e];return Yt(s,()=>{const n=s[e];Object.is(r,n)||t(r=n)})}function cD(s){const e=Xe({data:Array.from([]),has(t){return this.data.some(i=>i[0]===t)},set(t,i){const r=this.data.find(n=>n[0]===t);return r?r[1]=i:this.data.push([t,i]),this},get(t){var i;return(i=this.data.find(r=>r[0]===t))==null?void 0:i[1]},delete(t){const i=this.data.findIndex(r=>r[0]===t);return i===-1?!1:(this.data.splice(i,1),!0)},clear(){this.data.splice(0)},get size(){return this.data.length},toJSON(){return new Map(this.data)},forEach(t){this.data.forEach(i=>{t(i[1],i[0],this)})},keys(){return this.data.map(t=>t[0]).values()},values(){return this.data.map(t=>t[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 ug={};const jl=(typeof _.process<"u"&&typeof ug<"u"?ug.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",os={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:jl,SECURE_SITE_DASHBOARD:`${jl}/dashboard`,SECURE_SITE_FAVICON:`${jl}/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","solana"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in a new browser tab"},DEFAULT_FEATURES:{swaps:!0,onramp:!0,receive:!0,send:!0,email:!0,emailShowWallets:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],history:!0,analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0},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"}},G={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(s,e){return Date.now()-s>e},getActiveNetworkProps(){const s=G.getActiveNamespace(),e=G.getActiveCaipNetworkId(),t=e?e.split(":")[1]:void 0,i=t?isNaN(Number(t))?t:Number(t):void 0;return{namespace:s,caipNetworkId:e,chainId:i}},setWalletConnectDeepLink({name:s,href:e}){try{ee.setItem(re.DEEPLINK_CHOICE,JSON.stringify({href:e,name:s}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const s=ee.getItem(re.DEEPLINK_CHOICE);if(s)return JSON.parse(s)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{ee.removeItem(re.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(s){try{ee.setItem(re.ACTIVE_NAMESPACE,s)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(s){try{ee.setItem(re.ACTIVE_CAIP_NETWORK_ID,s),G.setActiveNamespace(s.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return ee.getItem(re.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{ee.removeItem(re.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(s){try{const e=Dl(s);ee.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(s){try{const e=G.getRecentWallets();e.find(i=>i.id===s.id)||(e.unshift(s),e.length>2&&e.pop(),ee.setItem(re.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const s=ee.getItem(re.RECENT_WALLETS);return s?JSON.parse(s):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(s,e){try{const t=Dl(s);ee.setItem(t,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return ee.getItem(re.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(s){if(s)try{const e=Dl(s);return ee.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",s)}},setConnectedSocialProvider(s){try{ee.setItem(re.CONNECTED_SOCIAL,s)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return ee.getItem(re.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{ee.removeItem(re.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return ee.getItem(re.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var t;const s=ee.getItem(re.ACTIVE_CAIP_NETWORK_ID);return(t=s==null?void 0:s.split(":"))==null?void 0:t[1]},setConnectionStatus(s){try{ee.setItem(re.CONNECTION_STATUS,s)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return ee.getItem(re.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const s=ee.getItem(re.CONNECTED_NAMESPACES);return s!=null&&s.length?s.split(","):[]}catch{return[]}},setConnectedNamespaces(s){try{const e=Array.from(new Set(s));ee.setItem(re.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(s){try{const e=G.getConnectedNamespaces();e.includes(s)||(e.push(s),G.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(s){try{const e=G.getConnectedNamespaces(),t=e.indexOf(s);t>-1&&(e.splice(t,1),G.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return ee.getItem(re.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(s){try{ee.setItem(re.TELEGRAM_SOCIAL_PROVIDER,s)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{ee.removeItem(re.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let s={};try{const e=ee.getItem(re.PORTFOLIO_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return s},removeAddressFromBalanceCache(s){try{const e=G.getBalanceCache();ee.setItem(re.PORTFOLIO_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove address from balance cache",s)}},getBalanceCacheForCaipAddress(s){try{const t=G.getBalanceCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;G.removeAddressFromBalanceCache(s)}catch{console.info("Unable to get balance cache for address",s)}},updateBalanceCache(s){try{const e=G.getBalanceCache();e[s.caipAddress]=s,ee.setItem(re.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",s)}},getNativeBalanceCache(){let s={};try{const e=ee.getItem(re.NATIVE_BALANCE_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return s},removeAddressFromNativeBalanceCache(s){try{const e=G.getBalanceCache();ee.setItem(re.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove address from balance cache",s)}},getNativeBalanceCacheForCaipAddress(s){try{const t=G.getNativeBalanceCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",s),G.removeAddressFromBalanceCache(s)}catch{console.info("Unable to get balance cache for address",s)}},updateNativeBalanceCache(s){try{const e=G.getNativeBalanceCache();e[s.caipAddress]=s,ee.setItem(re.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",s)}},getEnsCache(){let s={};try{const e=ee.getItem(re.ENS_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return s},getEnsFromCacheForAddress(s){try{const t=G.getEnsCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;G.removeEnsFromCache(s)}catch{console.info("Unable to get ens name from cache",s)}},updateEnsCache(s){try{const e=G.getEnsCache();e[s.address]=s,ee.setItem(re.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",s)}},removeEnsFromCache(s){try{const e=G.getEnsCache();ee.setItem(re.ENS_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove ens name from cache",s)}},getIdentityCache(){let s={};try{const e=ee.getItem(re.IDENTITY_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return s},getIdentityFromCacheForAddress(s){try{const t=G.getIdentityCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;G.removeIdentityFromCache(s)}catch{console.info("Unable to get identity from cache",s)}},updateIdentityCache(s){try{const e=G.getIdentityCache();e[s.address]={identity:s.identity,timestamp:s.timestamp},ee.setItem(re.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",s)}},removeIdentityFromCache(s){try{const e=G.getIdentityCache();ee.setItem(re.IDENTITY_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove identity from cache",s)}},clearAddressCache(){try{ee.removeItem(re.PORTFOLIO_CACHE),ee.removeItem(re.NATIVE_BALANCE_CACHE),ee.removeItem(re.ENS_CACHE),ee.removeItem(re.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}}},se={isMobile(){var s;return this.isClient()?!!((s=window==null?void 0:window.matchMedia("(pointer:coarse)"))!=null&&s.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(s,e=""){return s==null?void 0:s.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const s=window==null?void 0:window.navigator.userAgent.toLowerCase();return se.isMobile()&&s.includes("android")},isIos(){if(!this.isMobile())return!1;const s=window==null?void 0:window.navigator.userAgent.toLowerCase();return s.includes("iphone")||s.includes("ipad")},isSafari(){return this.isClient()?(window==null?void 0:window.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(s){return s?s-Date.now()<=os.TEN_SEC_MS:!0},isAllowedRetry(s,e=os.ONE_SEC_MS){return Date.now()-s>=e},copyToClopboard(s){navigator.clipboard.writeText(s)},isIframe(){try{return(window==null?void 0:window.self)!==(window==null?void 0:window.top)}catch{return!1}},getPairingExpiry(){return Date.now()+os.FOUR_MINUTES_MS},getNetworkId(s){return s==null?void 0:s.split(":")[1]},getPlainAddress(s){return s==null?void 0:s.split(":")[2]},async wait(s){return new Promise(e=>{setTimeout(e,s)})},debounce(s,e=500){let t;return(...i)=>{function r(){s(...i)}t&&clearTimeout(t),t=setTimeout(r,e)}},isHttpUrl(s){return s.startsWith("http://")||s.startsWith("https://")},formatNativeUrl(s,e){if(se.isHttpUrl(s))return this.formatUniversalUrl(s,e);let t=s;t.includes("://")||(t=s.replaceAll("/","").replaceAll(":",""),t=`${t}://`),t.endsWith("/")||(t=`${t}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const i=encodeURIComponent(e);return{redirect:`${t}wc?uri=${i}`,href:t}},formatUniversalUrl(s,e){if(!se.isHttpUrl(s))return this.formatNativeUrl(s,e);let t=s;t.endsWith("/")||(t=`${t}/`);const i=encodeURIComponent(e);return{redirect:`${t}wc?uri=${i}`,href:t}},getOpenTargetForPlatform(s){return s==="popupWindow"?s:this.isTelegram()?G.getTelegramSocialProvider()?"_top":"_blank":s},openHref(s,e,t){window==null||window.open(s,this.getOpenTargetForPlatform(e),t||"noreferrer noopener")},returnOpenHref(s,e,t){return window==null?void 0:window.open(s,this.getOpenTargetForPlatform(e),t||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},async preloadImage(s){const e=new Promise((t,i)=>{const r=new Image;r.onload=t,r.onerror=i,r.crossOrigin="anonymous",r.src=s});return Promise.race([e,se.wait(2e3)])},formatBalance(s,e){let t="0.000";if(typeof s=="string"){const i=Number(s);if(i){const r=Math.floor(i*1e3)/1e3;r&&(t=r.toString())}}return`${t}${e?` ${e}`:""}`},formatBalance2(s,e){var i;let t;if(s==="0")t="0";else if(typeof s=="string"){const r=Number(s);r&&(t=(i=r.toString().match(/^-?\d+(?:\.\d{0,3})?/u))==null?void 0:i[0])}return{value:t??"0",rest:t==="0"?"000":"",symbol:e}},getApiUrl(){return Q.W3M_API_URL},getBlockchainApiUrl(){return Q.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return Q.PULSE_API_URL},getUUID(){return crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})},parseError(s){var e,t;return typeof s=="string"?s:typeof((t=(e=s==null?void 0:s.issues)==null?void 0:e[0])==null?void 0:t.message)=="string"?s.issues[0].message:s instanceof Error?s.message:"Unknown error"},sortRequestedNetworks(s,e=[]){const t={};return e&&s&&(s.forEach((i,r)=>{t[i]=r}),e.sort((i,r)=>{const n=t[i.id],o=t[r.id];return n!==void 0&&o!==void 0?n-o:n!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(s){let e=0;for(const t of s)e+=t.value??0;return e},formatTokenBalance(s){const e=s.toFixed(2),[t,i]=e.split(".");return{dollars:t,pennies:i}},isAddress(s,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(s)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(s)||/^(?:0x)?[0-9A-F]{40}$/iu.test(s))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(s);default:return!1}},uniqueBy(s,e){const t=new Set;return s.filter(i=>{const r=i[e];return t.has(r)?!1:(t.add(r),!0)})},generateSdkVersion(s,e,t){const r=s.length===0?os.ADAPTER_TYPES.UNIVERSAL:s.map(n=>n.adapterType).join(",");return`${e}-${r}-${t}`},createAccount(s,e,t,i,r){return{namespace:s,address:e,type:t,publicKey:i,path:r}},isCaipAddress(s){if(typeof s!="string")return!1;const e=s.split(":"),t=e[0];return e.filter(Boolean).length===3&&t in Q.CHAIN_NAME_MAP},isMac(){const s=window==null?void 0:window.navigator.userAgent.toLowerCase();return s.includes("macintosh")&&!s.includes("safari")},formatTelegramSocialLoginUrl(s){const e=`--${encodeURIComponent(window==null?void 0:window.location.href)}`,t="state=";if(new URL(s).host==="auth.magic.link"){const r="provider_authorization_url=",n=s.substring(s.indexOf(r)+r.length),o=this.injectIntoUrl(decodeURIComponent(n),t,e);return s.replace(n,encodeURIComponent(o))}return this.injectIntoUrl(s,t,e)},injectIntoUrl(s,e,t){const i=s.indexOf(e);if(i===-1)throw new Error(`${e} parameter not found in the URL: ${s}`);const r=s.indexOf("&",i),n=e.length,o=r!==-1?r:s.length,a=s.substring(0,i+n),l=s.substring(i+n,o),c=s.substring(r),h=l+t;return a+h+c}};async function mo(...s){const e=await fetch(...s);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class tl{constructor({baseUrl:e,clientId:t}){this.baseUrl=e,this.clientId=t}async get({headers:e,signal:t,cache:i,...r}){const n=this.createUrl(r);return(await mo(n,{method:"GET",headers:e,signal:t,cache:i})).json()}async getBlob({headers:e,signal:t,...i}){const r=this.createUrl(i);return(await mo(r,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await mo(n,{method:"POST",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}async put({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await mo(n,{method:"PUT",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}async delete({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await mo(n,{method:"DELETE",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}createUrl({path:e,params:t}){const i=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([r,n])=>{n&&i.searchParams.append(r,n)}),this.clientId&&i.searchParams.append("clientId",this.clientId),i}}const lD={handleSolanaDeeplinkRedirect(s){if(v.state.activeChain===Q.CHAIN.SOLANA){const e=window.location.href,t=encodeURIComponent(e);if(s==="Phantom"&&!("phantom"in window)){const i=e.startsWith("https")?"https":"http",r=e.split("/")[2],n=encodeURIComponent(`${i}://${r}`);window.location.href=`https://phantom.app/ul/browse/${t}?ref=${n}`}s==="Coinbase Wallet"&&!("coinbaseSolana"in window)&&(window.location.href=`https://go.cb-w.com/dapp?cb_url=${t}`)}}},as=Xe({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Fs={state:as,subscribeNetworkImages(s){return Yt(as.networkImages,()=>s(as.networkImages))},subscribeKey(s,e){return vs(as,s,e)},subscribe(s){return Yt(as,()=>s(as))},setWalletImage(s,e){as.walletImages[s]=e},setNetworkImage(s,e){as.networkImages[s]=e},setChainImage(s,e){as.chainImages[s]=e},setConnectorImage(s,e){as.connectorImages={...as.connectorImages,[s]:e}},setTokenImage(s,e){as.tokenImages[s]=e},setCurrencyImage(s,e){as.currencyImages[s]=e}},hD={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},Rl=Xe({networkImagePromises:{}}),Ny={async fetchWalletImage(s){if(s)return await ie._fetchWalletImage(s),this.getWalletImageById(s)},async fetchNetworkImage(s){if(!s)return;const e=this.getNetworkImageById(s);return e||(Rl.networkImagePromises[s]||(Rl.networkImagePromises[s]=ie._fetchNetworkImage(s)),await Rl.networkImagePromises[s],this.getNetworkImageById(s))},getWalletImageById(s){if(s)return Fs.state.walletImages[s]},getWalletImage(s){if(s!=null&&s.image_url)return s==null?void 0:s.image_url;if(s!=null&&s.image_id)return Fs.state.walletImages[s.image_id]},getNetworkImage(s){var e,t,i;if((e=s==null?void 0:s.assets)!=null&&e.imageUrl)return(t=s==null?void 0:s.assets)==null?void 0:t.imageUrl;if((i=s==null?void 0:s.assets)!=null&&i.imageId)return Fs.state.networkImages[s.assets.imageId]},getNetworkImageById(s){if(s)return Fs.state.networkImages[s]},getConnectorImage(s){if(s!=null&&s.imageUrl)return s.imageUrl;if(s!=null&&s.imageId)return Fs.state.connectorImages[s.imageId]},getChainImage(s){return Fs.state.networkImages[hD[s]]}},uD={getFeatureValue(s,e){const t=e==null?void 0:e[s];return t===void 0?os.DEFAULT_FEATURES[s]:t},filterSocialsByPlatform(s){if(!s||!s.length)return s;if(se.isTelegram()){if(se.isIos())return s.filter(e=>e!=="google");if(se.isMac())return s.filter(e=>e!=="x");if(se.isAndroid())return s.filter(e=>!["facebook","x"].includes(e))}return s}},J=Xe({features:os.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:os.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0}),D={state:J,subscribeKey(s,e){return vs(J,s,e)},setOptions(s){Object.assign(J,s)},setFeatures(s){if(!s)return;J.features||(J.features=os.DEFAULT_FEATURES);const e={...J.features,...s};J.features=e,J.features.socials&&(J.features.socials=uD.filterSocialsByPlatform(J.features.socials))},setProjectId(s){J.projectId=s},setCustomRpcUrls(s){J.customRpcUrls=s},setAllWallets(s){J.allWallets=s},setIncludeWalletIds(s){J.includeWalletIds=s},setExcludeWalletIds(s){J.excludeWalletIds=s},setFeaturedWalletIds(s){J.featuredWalletIds=s},setTokens(s){J.tokens=s},setTermsConditionsUrl(s){J.termsConditionsUrl=s},setPrivacyPolicyUrl(s){J.privacyPolicyUrl=s},setCustomWallets(s){J.customWallets=s},setIsSiweEnabled(s){J.isSiweEnabled=s},setIsUniversalProvider(s){J.isUniversalProvider=s},setSdkVersion(s){J.sdkVersion=s},setMetadata(s){J.metadata=s},setDisableAppend(s){J.disableAppend=s},setEIP6963Enabled(s){J.enableEIP6963=s},setDebug(s){J.debug=s},setEnableWalletConnect(s){J.enableWalletConnect=s},setEnableWalletGuide(s){J.enableWalletGuide=s},setEnableAuthLogger(s){J.enableAuthLogger=s},setEnableWallets(s){J.enableWallets=s},setHasMultipleAddresses(s){J.hasMultipleAddresses=s},setSIWX(s){J.siwx=s},setConnectMethodsOrder(s){J.features={...J.features,connectMethodsOrder:s}},setWalletFeaturesOrder(s){J.features={...J.features,walletFeaturesOrder:s}},setSocialsOrder(s){J.features={...J.features,socials:s}},setCollapseWallets(s){J.features={...J.features,collapseWallets:s}},setEnableEmbedded(s){J.enableEmbedded=s},setAllowUnsupportedChain(s){J.allowUnsupportedChain=s},setManualWCControl(s){J.manualWCControl=s},setEnableNetworkSwitch(s){J.enableNetworkSwitch=s},setDefaultAccountTypes(s={}){Object.entries(s).forEach(([e,t])=>{t&&(J.defaultAccountTypes[e]=t)})},setUniversalProviderConfigOverride(s){J.universalProviderConfigOverride=s},getUniversalProviderConfigOverride(){return J.universalProviderConfigOverride},getSnapshot(){return Xo(J)}},Ei=Xe({message:"",variant:"info",open:!1}),ac={state:Ei,subscribeKey(s,e){return vs(Ei,s,e)},open(s,e){const{debug:t}=D.state,{shortMessage:i,longMessage:r}=s;t&&(Ei.message=i,Ei.variant=e,Ei.open=!0),r&&console.error(typeof r=="function"?r():r)},close(){Ei.open=!1,Ei.message="",Ei.variant="info"}},dD=se.getAnalyticsUrl(),pD=new tl({baseUrl:dD,clientId:null}),gD=["MODAL_CREATED"],oi=Xe({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),ze={state:oi,subscribe(s){return Yt(oi,()=>s(oi))},getSdkProperties(){const{projectId:s,sdkType:e,sdkVersion:t}=D.state;return{projectId:s,st:e,sv:t||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(s){try{const e=Z.state.address;if(gD.includes(s.data.event)||typeof window>"u")return;await pD.post({path:"/e",params:ze.getSdkProperties(),body:{eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:s.timestamp,props:{...s.data,address:e}}}),oi.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===Q.HTTP_STATUS_CODES.FORBIDDEN&&!oi.reportedErrors.FORBIDDEN&&(ac.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${To()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),oi.reportedErrors.FORBIDDEN=!0)}},sendEvent(s){var e;oi.timestamp=Date.now(),oi.data=s,(e=D.state.features)!=null&&e.analytics&&ze._sendAnalyticsEvent(oi)}},fD=se.getApiUrl(),zt=new tl({baseUrl:fD,clientId:null}),mD="40",dg="4",wD=20,_e=Xe({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),ie={state:_e,subscribeKey(s,e){return vs(_e,s,e)},_getSdkProperties(){const{projectId:s,sdkType:e,sdkVersion:t}=D.state;return{projectId:s,st:e||"appkit",sv:t||"html-wagmi-4.2.2"}},_filterOutExtensions(s){return D.state.isUniversalProvider?s.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):s},async _fetchWalletImage(s){const e=`${zt.baseUrl}/getWalletImage/${s}`,t=await zt.getBlob({path:e,params:ie._getSdkProperties()});Fs.setWalletImage(s,URL.createObjectURL(t))},async _fetchNetworkImage(s){const e=`${zt.baseUrl}/public/getAssetImage/${s}`,t=await zt.getBlob({path:e,params:ie._getSdkProperties()});Fs.setNetworkImage(s,URL.createObjectURL(t))},async _fetchConnectorImage(s){const e=`${zt.baseUrl}/public/getAssetImage/${s}`,t=await zt.getBlob({path:e,params:ie._getSdkProperties()});Fs.setConnectorImage(s,URL.createObjectURL(t))},async _fetchCurrencyImage(s){const e=`${zt.baseUrl}/public/getCurrencyImage/${s}`,t=await zt.getBlob({path:e,params:ie._getSdkProperties()});Fs.setCurrencyImage(s,URL.createObjectURL(t))},async _fetchTokenImage(s){const e=`${zt.baseUrl}/public/getTokenImage/${s}`,t=await zt.getBlob({path:e,params:ie._getSdkProperties()});Fs.setTokenImage(s,URL.createObjectURL(t))},async fetchNetworkImages(){const s=v.getAllRequestedCaipNetworks(),e=s==null?void 0:s.map(({assets:t})=>t==null?void 0:t.imageId).filter(Boolean).filter(t=>!Ny.getNetworkImageById(t));e&&await Promise.allSettled(e.map(t=>ie._fetchNetworkImage(t)))},async fetchConnectorImages(){const{connectors:s}=te.state,e=s.map(({imageId:t})=>t).filter(Boolean);await Promise.allSettled(e.map(t=>ie._fetchConnectorImage(t)))},async fetchCurrencyImages(s=[]){await Promise.allSettled(s.map(e=>ie._fetchCurrencyImage(e)))},async fetchTokenImages(s=[]){await Promise.allSettled(s.map(e=>ie._fetchTokenImage(e)))},async fetchFeaturedWallets(){const{featuredWalletIds:s}=D.state;if(s!=null&&s.length){const{data:e}=await zt.get({path:"/getWallets",params:{...ie._getSdkProperties(),page:"1",entries:s!=null&&s.length?String(s.length):dg,include:s==null?void 0:s.join(",")}});e.sort((i,r)=>s.indexOf(i.id)-s.indexOf(r.id));const t=e.map(i=>i.image_id).filter(Boolean);await Promise.allSettled(t.map(i=>ie._fetchWalletImage(i))),_e.featured=e,_e.allFeatured=e}},async fetchRecommendedWallets(){try{_e.isFetchingRecommendedWallets=!0;const{includeWalletIds:s,excludeWalletIds:e,featuredWalletIds:t}=D.state,i=[...e??[],...t??[]].filter(Boolean),r=v.getRequestedCaipNetworkIds().join(","),{data:n,count:o}=await zt.get({path:"/getWallets",params:{...ie._getSdkProperties(),page:"1",chains:r,entries:dg,include:s==null?void 0:s.join(","),exclude:i==null?void 0:i.join(",")}}),a=G.getRecentWallets(),l=n.map(h=>h.image_id).filter(Boolean),c=a.map(h=>h.image_id).filter(Boolean);await Promise.allSettled([...l,...c].map(h=>ie._fetchWalletImage(h))),_e.recommended=n,_e.allRecommended=n,_e.count=o??0}catch{}finally{_e.isFetchingRecommendedWallets=!1}},async fetchWallets({page:s}){const{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:i}=D.state,r=v.getRequestedCaipNetworkIds().join(","),n=[..._e.recommended.map(({id:c})=>c),...t??[],...i??[]].filter(Boolean),{data:o,count:a}=await zt.get({path:"/getWallets",params:{...ie._getSdkProperties(),page:String(s),entries:mD,chains:r,include:e==null?void 0:e.join(","),exclude:n.join(",")}}),l=o.slice(0,wD).map(c=>c.image_id).filter(Boolean);await Promise.allSettled(l.map(c=>ie._fetchWalletImage(c))),_e.wallets=se.uniqueBy([..._e.wallets,...ie._filterOutExtensions(o)],"id"),_e.count=a>_e.count?a:_e.count,_e.page=s},async initializeExcludedWallets({ids:s}){const e=v.getRequestedCaipNetworkIds().join(","),{data:t}=await zt.get({path:"/getWallets",params:{...ie._getSdkProperties(),page:"1",entries:String(s.length),chains:e,include:s==null?void 0:s.join(",")}});t&&t.forEach(i=>{i!=null&&i.rdns&&_e.excludedWallets.push({rdns:i.rdns,name:i.name})})},async searchWallet({search:s,badge:e}){const{includeWalletIds:t,excludeWalletIds:i}=D.state;_e.search=[];const r=v.getRequestedCaipNetworkIds().join(","),{data:n}=await zt.get({path:"/getWallets",params:{...ie._getSdkProperties(),page:"1",entries:"100",search:s==null?void 0:s.trim(),badge_type:e,chains:r,include:t==null?void 0:t.join(","),exclude:i==null?void 0:i.join(",")}});ze.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:s??""}});const o=n.map(a=>a.image_id).filter(Boolean);await Promise.allSettled([...o.map(a=>ie._fetchWalletImage(a)),se.wait(300)]),_e.search=ie._filterOutExtensions(n)},initPromise(s,e){const t=_e.promises[s];return t||(_e.promises[s]=e())},prefetch({fetchConnectorImages:s=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:t=!0,fetchNetworkImages:i=!0}={}){const r=[s&&ie.initPromise("connectorImages",ie.fetchConnectorImages),e&&ie.initPromise("featuredWallets",ie.fetchFeaturedWallets),t&&ie.initPromise("recommendedWallets",ie.fetchRecommendedWallets),i&&ie.initPromise("networkImages",ie.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(r)},prefetchAnalyticsConfig(){var s;(s=D.state.features)!=null&&s.analytics&&ie.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:s}=await zt.get({path:"/getAnalyticsConfig",params:ie._getSdkProperties()});D.setFeatures({analytics:s})}catch{D.setFeatures({analytics:!1})}},setFilterByNamespace(s){if(!s){_e.featured=_e.allFeatured,_e.recommended=_e.allRecommended;return}const e=v.getRequestedCaipNetworkIds().join(",");_e.featured=_e.allFeatured.filter(t=>{var i;return(i=t.chains)==null?void 0:i.some(r=>e.includes(r))}),_e.recommended=_e.allRecommended.filter(t=>{var i;return(i=t.chains)==null?void 0:i.some(r=>e.includes(r))})}},ve=Xe({view:"Connect",history:["Connect"],transactionStack:[]}),Se={state:ve,subscribeKey(s,e){return vs(ve,s,e)},pushTransactionStack(s){ve.transactionStack.push(s)},popTransactionStack(s){var t,i;const e=ve.transactionStack.pop();if(e)if(s)this.goBack(),(t=e==null?void 0:e.onCancel)==null||t.call(e);else{if(e.goBack)this.goBack();else if(e.replace){const n=ve.history.indexOf("ConnectingSiwe");n>0?this.goBackToIndex(n-1):(ct.close(),ve.history=[])}else e.view&&this.reset(e.view);(i=e==null?void 0:e.onSuccess)==null||i.call(e)}},push(s,e){s!==ve.view&&(ve.view=s,ve.history.push(s),ve.data=e)},reset(s,e){ve.view=s,ve.history=[s],ve.data=e},replace(s,e){ve.history.at(-1)===s||(ve.view=s,ve.history[ve.history.length-1]=s,ve.data=e)},goBack(){var e;const s=!v.state.activeCaipAddress&&this.state.view==="ConnectingFarcaster";if(ve.history.length>1&&!ve.history.includes("UnsupportedChain")){ve.history.pop();const[t]=ve.history.slice(-1);t&&(ve.view=t)}else ct.close();(e=ve.data)!=null&&e.wallet&&(ve.data.wallet=void 0),setTimeout(()=>{var t,i,r;if(s){Z.setFarcasterUrl(void 0,v.state.activeChain);const n=te.getAuthConnector();(t=n==null?void 0:n.provider)==null||t.reload();const o=Xo(D.state);(r=(i=n==null?void 0:n.provider)==null?void 0:i.syncDappData)==null||r.call(i,{metadata:o.metadata,sdkVersion:o.sdkVersion,projectId:o.projectId,sdkType:o.sdkType})}},100)},goBackToIndex(s){if(ve.history.length>1){ve.history=ve.history.slice(0,s+1);const[e]=ve.history.slice(-1);e&&(ve.view=e)}}},ai=Xe({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Vt={state:ai,subscribe(s){return Yt(ai,()=>s(ai))},setThemeMode(s){ai.themeMode=s;try{const e=te.getAuthConnector();if(e){const t=Vt.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:s,themeVariables:t,w3mThemeVariables:Ri(t,s)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(s){ai.themeVariables={...ai.themeVariables,...s};try{const e=te.getAuthConnector();if(e){const t=Vt.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:Ri(ai.themeVariables,ai.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Xo(ai)}},_y={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0},Ce=Xe({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{..._y}}),te={state:Ce,subscribe(s){return Yt(Ce,()=>{s(Ce)})},subscribeKey(s,e){return vs(Ce,s,e)},initialize(s){s.forEach(e=>{const t=G.getConnectedConnectorId(e);t&&this.setConnectorId(t,e)})},setActiveConnector(s){s&&(Ce.activeConnector=Ir(s))},setConnectors(s){s.filter(t=>!Ce.allConnectors.some(i=>i.id===t.id&&this.getConnectorName(i.name)===this.getConnectorName(t.name)&&i.chain===t.chain)).forEach(t=>{t.type!=="MULTI_CHAIN"&&Ce.allConnectors.push(Ir(t))}),Ce.connectors=this.mergeMultiChainConnectors(Ce.allConnectors)},removeAdapter(s){Ce.allConnectors=Ce.allConnectors.filter(e=>e.chain!==s),Ce.connectors=this.mergeMultiChainConnectors(Ce.allConnectors)},mergeMultiChainConnectors(s){const e=this.generateConnectorMapByName(s),t=[];return e.forEach(i=>{const r=i[0],n=(r==null?void 0:r.id)===Q.CONNECTOR_ID.AUTH;i.length>1&&r?t.push({name:r.name,imageUrl:r.imageUrl,imageId:r.imageId,connectors:[...i],type:n?"AUTH":"MULTI_CHAIN",chain:"eip155",id:(r==null?void 0:r.id)||""}):r&&t.push(r)}),t},generateConnectorMapByName(s){const e=new Map;return s.forEach(t=>{const{name:i}=t,r=this.getConnectorName(i);if(!r)return;const n=e.get(r)||[];n.find(a=>a.chain===t.chain)||n.push(t),e.set(r,n)}),e},getConnectorName(s){return s&&({"Trust Wallet":"Trust"}[s]||s)},getUniqueConnectorsByName(s){const e=[];return s.forEach(t=>{e.find(i=>i.chain===t.chain)||e.push(t)}),e},addConnector(s){var e,t,i;if(s.id===Q.CONNECTOR_ID.AUTH){const r=s,n=Xo(D.state),o=Vt.getSnapshot().themeMode,a=Vt.getSnapshot().themeVariables;(t=(e=r==null?void 0:r.provider)==null?void 0:e.syncDappData)==null||t.call(e,{metadata:n.metadata,sdkVersion:n.sdkVersion,projectId:n.projectId,sdkType:n.sdkType}),(i=r==null?void 0:r.provider)==null||i.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:Ri(a,o)}),this.setConnectors([s])}else this.setConnectors([s])},getAuthConnector(s){var i;const e=s||v.state.activeChain,t=Ce.connectors.find(r=>r.id===Q.CONNECTOR_ID.AUTH);if(t)return(i=t==null?void 0:t.connectors)!=null&&i.length?t.connectors.find(n=>n.chain===e):t},getAnnouncedConnectorRdns(){return Ce.connectors.filter(s=>s.type==="ANNOUNCED").map(s=>{var e;return(e=s.info)==null?void 0:e.rdns})},getConnectorById(s){return Ce.allConnectors.find(e=>e.id===s)},getConnector(s,e){return Ce.allConnectors.filter(i=>i.chain===v.state.activeChain).find(i=>{var r;return i.explorerId===s||((r=i.info)==null?void 0:r.rdns)===e})},syncIfAuthConnector(s){var n,o;if(s.id!=="ID_AUTH")return;const e=s,t=Xo(D.state),i=Vt.getSnapshot().themeMode,r=Vt.getSnapshot().themeVariables;(o=(n=e==null?void 0:e.provider)==null?void 0:n.syncDappData)==null||o.call(n,{metadata:t.metadata,sdkVersion:t.sdkVersion,sdkType:t.sdkType,projectId:t.projectId}),e.provider.syncTheme({themeMode:i,themeVariables:r,w3mThemeVariables:Ri(r,i)})},getConnectorsByNamespace(s){const e=Ce.allConnectors.filter(t=>t.chain===s);return this.mergeMultiChainConnectors(e)},selectWalletConnector(s){const e=te.getConnector(s.id,s.rdns);v.state.activeChain===Q.CHAIN.SOLANA&&lD.handleSolanaDeeplinkRedirect((e==null?void 0:e.name)||s.name||""),e?Se.push("ConnectingExternal",{connector:e}):Se.push("ConnectingWalletConnect",{wallet:s})},getConnectors(s){return s?this.getConnectorsByNamespace(s):this.mergeMultiChainConnectors(Ce.allConnectors)},setFilterByNamespace(s){Ce.filterByNamespace=s,Ce.connectors=this.getConnectors(s),ie.setFilterByNamespace(s)},setConnectorId(s,e){s&&(Ce.activeConnectorIds={...Ce.activeConnectorIds,[e]:s},G.setConnectedConnectorId(e,s))},removeConnectorId(s){Ce.activeConnectorIds={...Ce.activeConnectorIds,[s]:void 0},G.deleteConnectedConnectorId(s)},getConnectorId(s){if(s)return Ce.activeConnectorIds[s]},isConnected(s){return s?!!Ce.activeConnectorIds[s]:Object.values(Ce.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){Ce.activeConnectorIds={..._y}}};function Fa(s,e){return te.getConnectorId(s)===e}function yD(s){const e=Array.from(v.state.chains.keys());let t=[];return s?(t.push([s,v.state.chains.get(s)]),Fa(s,Q.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(i=>{i!==s&&Fa(i,Q.CONNECTOR_ID.WALLET_CONNECT)&&t.push([i,v.state.chains.get(i)])}):Fa(s,Q.CONNECTOR_ID.AUTH)&&e.forEach(i=>{i!==s&&Fa(i,Q.CONNECTOR_ID.AUTH)&&t.push([i,v.state.chains.get(i)])})):t=Array.from(v.state.chains.entries()),t}var bD=Object.defineProperty,vD=(s,e,t)=>e in s?bD(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,pg=(s,e,t)=>vD(s,typeof e!="symbol"?e+"":e,t);let ID=class extends bs{constructor(e){super(),this.opts=e,pg(this,"protocol","wc"),pg(this,"version",2)}};var ED=Object.defineProperty,AD=(s,e,t)=>e in s?ED(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ND=(s,e,t)=>AD(s,e+"",t);let _D=class extends bs{constructor(e,t){super(),this.core=e,this.logger=t,ND(this,"records",new Map)}},CD=class{constructor(e,t){this.logger=e,this.core=t}},SD=class extends bs{constructor(e,t){super(),this.relayer=e,this.logger=t}},$D=class extends bs{constructor(e){super()}},PD=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},TD=class extends bs{constructor(e,t){super(),this.relayer=e,this.logger=t}},MD=class extends bs{constructor(e,t){super(),this.core=e,this.logger=t}},OD=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},xD=class{constructor(e,t){this.projectId=e,this.logger=t}},DD=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};var kD=Object.defineProperty,jD=(s,e,t)=>e in s?kD(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,gg=(s,e,t)=>jD(s,typeof e!="symbol"?e+"":e,t);let RD=class{constructor(e){this.opts=e,gg(this,"protocol","wc"),gg(this,"version",2)}},LD=class{constructor(e){this.client=e}};const Pi={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"}},nr=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),ht=Xe({...nr}),xt={state:ht,subscribeKey(s,e){return vs(ht,s,e)},showLoading(s,e={}){this._showMessage({message:s,variant:"loading",...e})},showSuccess(s){this._showMessage({message:s,variant:"success"})},showSvg(s,e){this._showMessage({message:s,svg:e})},showError(s){const e=se.parseError(s);this._showMessage({message:e,variant:"error"})},hide(){ht.message=nr.message,ht.variant=nr.variant,ht.svg=nr.svg,ht.open=nr.open,ht.autoClose=nr.autoClose},_showMessage({message:s,svg:e,variant:t="success",autoClose:i=nr.autoClose}){ht.open?(ht.open=!1,setTimeout(()=>{ht.message=s,ht.variant=t,ht.svg=e,ht.open=!0,ht.autoClose=i},150)):(ht.message=s,ht.variant=t,ht.svg=e,ht.open=!0,ht.autoClose=i)}},Lo={getSIWX(){return D.state.siwx},async initializeIfEnabled(){var n;const s=D.state.siwx,e=v.getActiveCaipAddress();if(!(s&&e))return;const[t,i,r]=e.split(":");if(v.checkIfSupportedNetwork(t))try{if((await s.getSessions(`${t}:${i}`,r)).length)return;await ct.open({view:"SIWXSignMessage"})}catch(o){console.error("SIWXUtil:initializeIfEnabled",o),ze.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await((n=Ue._getClient())==null?void 0:n.disconnect().catch(console.error)),Se.reset("Connect"),xt.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const s=D.state.siwx,e=se.getPlainAddress(v.getActiveCaipAddress()),t=v.getActiveCaipNetwork(),i=Ue._getClient();if(!s)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!t)throw new Error("No ActiveCaipNetwork or client found");if(!i)throw new Error("No ConnectionController client found");try{const r=await s.createMessage({chainId:t.caipNetworkId,accountAddress:e}),n=r.toString();te.getConnectorId(t.chainNamespace)===Q.CONNECTOR_ID.AUTH&&Se.pushTransactionStack({view:null,goBack:!1,replace:!0});const a=await i.signMessage(n);await s.addSession({data:r,message:n,signature:a}),ct.close(),ze.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){const n=this.getSIWXEventProperties();(!ct.state.open||Se.state.view==="ApproveTransaction")&&await ct.open({view:"SIWXSignMessage"}),n.isSmartAccount?xt.showError("This application might not support Smart Accounts"):xt.showError("Signature declined"),ze.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:n}),console.error("SWIXUtil:requestSignMessage",r)}},async cancelSignMessage(){var s;try{const e=this.getSIWX();((s=e==null?void 0:e.getRequired)==null?void 0:s.call(e))?await Ue.disconnect():ct.close(),Se.reset("Connect"),ze.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getSessions(){const s=D.state.siwx,e=se.getPlainAddress(v.getActiveCaipAddress()),t=v.getActiveCaipNetwork();return s&&e&&t?s.getSessions(t.caipNetworkId,e):[]},async isSIWXCloseDisabled(){var e;const s=this.getSIWX();if(s){const t=Se.state.view==="ApproveTransaction",i=Se.state.view==="SIWXSignMessage";if(t||i)return((e=s.getRequired)==null?void 0:e.call(s))&&(await this.getSessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:s,chains:e,methods:t}){var a,l,c;const i=Lo.getSIWX(),r=new Set(e.map(h=>h.split(":")[0]));if(!i||r.size!==1||!r.has("eip155"))return!1;const n=await i.createMessage({chainId:((a=v.getActiveCaipNetwork())==null?void 0:a.caipNetworkId)||"",accountAddress:""}),o=await s.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:t,chains:[n.chainId,...e.filter(h=>h!==n.chainId)]});if(xt.showLoading("Authenticating...",{autoClose:!1}),Z.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:(l=o.session.peer.metadata.icons)==null?void 0:l[0],type:"WALLET_CONNECT"},Array.from(r)[0]),(c=o==null?void 0:o.auths)!=null&&c.length){const h=o.auths.map(u=>{const d=s.client.formatAuthMessage({request:u.p,iss:u.p.iss});return{data:{...u.p,accountAddress:u.p.iss.split(":").slice(-1).join(""),chainId:u.p.iss.split(":").slice(2,4).join(":"),uri:u.p.aud,version:u.p.version||n.version,expirationTime:u.p.exp,issuedAt:u.p.iat,notBefore:u.p.nbf},message:d,signature:u.s.s,cacao:u}});try{await i.setSessions(h),ze.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:Lo.getSIWXEventProperties()})}catch(u){throw console.error("SIWX:universalProviderAuth - failed to set sessions",u),ze.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:Lo.getSIWXEventProperties()}),await s.disconnect().catch(console.error),u}finally{xt.hide()}}return!0},getSIWXEventProperties(){var s;return{network:((s=v.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||"",isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const s=this.getSIWX();s&&await s.setSessions([])}},je=Xe({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),UD={state:je,subscribe(s){return Yt(je,()=>s(je))},setLastNetworkInView(s){je.lastNetworkInView=s},async fetchTransactions(s,e){var t;if(!s)throw new Error("Transactions can't be fetched without an accountAddress");je.loading=!0;try{const i=await X.fetchTransactions({account:s,cursor:je.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:(t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId}),r=this.filterSpamTransactions(i.data),n=this.filterByConnectedChain(r),o=[...je.transactions,...n];je.loading=!1,e==="coinbase"?je.coinbaseTransactions=this.groupTransactionsByYearAndMonth(je.coinbaseTransactions,i.data):(je.transactions=o,je.transactionsByYear=this.groupTransactionsByYearAndMonth(je.transactionsByYear,n)),je.empty=o.length===0,je.next=i.next?i.next:void 0}catch{ze.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:s,projectId:D.state.projectId,cursor:je.next,isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT}}),xt.showError("Failed to fetch transactions"),je.loading=!1,je.empty=!0,je.next=void 0}},groupTransactionsByYearAndMonth(s={},e=[]){const t=s;return e.forEach(i=>{const r=new Date(i.metadata.minedAt).getFullYear(),n=new Date(i.metadata.minedAt).getMonth(),o=t[r]??{},l=(o[n]??[]).filter(c=>c.id!==i.id);t[r]={...o,[n]:[...l,i].sort((c,h)=>new Date(h.metadata.minedAt).getTime()-new Date(c.metadata.minedAt).getTime())}}),t},filterSpamTransactions(s){return s.filter(e=>!e.transfers.every(i=>{var r;return((r=i.nft_info)==null?void 0:r.flags.is_spam)===!0}))},filterByConnectedChain(s){var i;const e=(i=v.state.activeCaipNetwork)==null?void 0:i.caipNetworkId;return s.filter(r=>r.metadata.chain===e)},clearCursor(){je.next=void 0},resetTransactions(){je.transactions=[],je.transactionsByYear={},je.lastNetworkInView=void 0,je.loading=!1,je.empty=!1,je.next=void 0}},Re=Xe({wcError:!1,buffering:!1,status:"disconnected"});let en;const Ue={state:Re,subscribeKey(s,e){return vs(Re,s,e)},_getClient(){return Re._client},setClient(s){Re._client=Ir(s)},async connectWalletConnect(){var s,e,t,i;if(se.isTelegram()||se.isSafari()&&se.isIos()){if(en){await en,en=void 0;return}if(!se.isPairingExpired(Re==null?void 0:Re.wcPairingExpiry)){const r=Re.wcUri;Re.wcUri=r;return}en=(e=(s=this._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:e.call(s).catch(()=>{}),this.state.status="connecting",await en,en=void 0,Re.wcPairingExpiry=void 0,this.state.status="connected"}else await((i=(t=this._getClient())==null?void 0:t.connectWalletConnect)==null?void 0:i.call(t))},async connectExternal(s,e,t=!0){var i,r;await((r=(i=this._getClient())==null?void 0:i.connectExternal)==null?void 0:r.call(i,s)),t&&v.setActiveNamespace(e)},async reconnectExternal(s){var t,i;await((i=(t=this._getClient())==null?void 0:t.reconnectExternal)==null?void 0:i.call(t,s));const e=s.chain||v.state.activeChain;e&&te.setConnectorId(s.id,e)},async setPreferredAccountType(s){var t;ct.setLoading(!0,v.state.activeChain);const e=te.getAuthConnector();e&&(await(e==null?void 0:e.provider.setPreferredAccount(s)),await this.reconnectExternal(e),ct.setLoading(!1,v.state.activeChain),ze.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:s,network:((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)||""}}))},async signMessage(s){var e;return(e=this._getClient())==null?void 0:e.signMessage(s)},parseUnits(s,e){var t;return(t=this._getClient())==null?void 0:t.parseUnits(s,e)},formatUnits(s,e){var t;return(t=this._getClient())==null?void 0:t.formatUnits(s,e)},async sendTransaction(s){var e;return(e=this._getClient())==null?void 0:e.sendTransaction(s)},async getCapabilities(s){var e;return(e=this._getClient())==null?void 0:e.getCapabilities(s)},async grantPermissions(s){var e;return(e=this._getClient())==null?void 0:e.grantPermissions(s)},async walletGetAssets(s){var e;return((e=this._getClient())==null?void 0:e.walletGetAssets(s))??{}},async estimateGas(s){var e;return(e=this._getClient())==null?void 0:e.estimateGas(s)},async writeContract(s){var e;return(e=this._getClient())==null?void 0:e.writeContract(s)},async getEnsAddress(s){var e;return(e=this._getClient())==null?void 0:e.getEnsAddress(s)},async getEnsAvatar(s){var e;return(e=this._getClient())==null?void 0:e.getEnsAvatar(s)},checkInstalled(s){var e,t;return((t=(e=this._getClient())==null?void 0:e.checkInstalled)==null?void 0:t.call(e,s))||!1},resetWcConnection(){Re.wcUri=void 0,Re.wcPairingExpiry=void 0,Re.wcLinking=void 0,Re.recentWallet=void 0,Re.status="disconnected",UD.resetTransactions(),G.deleteWalletConnectDeepLink()},resetUri(){Re.wcUri=void 0,Re.wcPairingExpiry=void 0},finalizeWcConnection(){var t,i;const{wcLinking:s,recentWallet:e}=Ue.state;s&&G.setWalletConnectDeepLink(s),e&&G.setAppKitRecent(e),ze.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:s?"mobile":"qrcode",name:((i=(t=Se.state.data)==null?void 0:t.wallet)==null?void 0:i.name)||"Unknown"}})},setWcBasic(s){Re.wcBasic=s},setUri(s){Re.wcUri=s,Re.wcPairingExpiry=se.getPairingExpiry()},setWcLinking(s){Re.wcLinking=s},setWcError(s){Re.wcError=s,Re.buffering=!1},setRecentWallet(s){Re.recentWallet=s},setBuffering(s){Re.buffering=s},setStatus(s){Re.status=s},async disconnect(s){try{ct.setLoading(!0,s),await Lo.clearSessions(),await v.disconnect(s),ct.setLoading(!1,s),te.setFilterByNamespace(void 0)}catch{throw new Error("Failed to disconnect")}}},wo=Xe({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),fi={state:wo,subscribe(s){return Yt(wo,()=>s(wo))},set(s){Object.assign(wo,{...wo,...s})}},Ll={createBalance(s,e){const t={name:s.metadata.name||"",symbol:s.metadata.symbol||"",decimals:s.metadata.decimals||0,value:s.metadata.value||0,price:s.metadata.price||0,iconUrl:s.metadata.iconUrl||""};return{name:t.name,symbol:t.symbol,chainId:e,address:s.address==="native"?void 0:this.convertAddressToCAIP10Address(s.address,e),value:t.value,price:t.price,quantity:{decimals:t.decimals.toString(),numeric:this.convertHexToBalance({hex:s.balance,decimals:t.decimals})},iconUrl:t.iconUrl}},convertHexToBalance({hex:s,decimals:e}){return Av(BigInt(s),e)},convertAddressToCAIP10Address(s,e){return`${e}:${s}`},createCAIP2ChainId(s,e){return`${e}:${parseInt(s,16)}`},getChainIdHexFromCAIP2ChainId(s){const e=s.split(":");if(e.length<2||!e[1])return"0x0";const t=e[1],i=parseInt(t,10);return isNaN(i)?"0x0":`0x${i.toString(16)}`},isWalletGetAssetsResponse(s){return typeof s!="object"||s===null?!1:Object.values(s).every(e=>Array.isArray(e)&&e.every(t=>this.isValidAsset(t)))},isValidAsset(s){return typeof s=="object"&&s!==null&&typeof s.address=="string"&&typeof s.balance=="string"&&(s.type==="ERC20"||s.type==="NATIVE")&&typeof s.metadata=="object"&&s.metadata!==null&&typeof s.metadata.name=="string"&&typeof s.metadata.symbol=="string"&&typeof s.metadata.decimals=="number"&&typeof s.metadata.price=="number"&&typeof s.metadata.iconUrl=="string"}},fg={async getMyTokensWithBalance(s){const e=Z.state.address,t=v.state.activeCaipNetwork;if(!e||!t)return[];if(t.chainNamespace==="eip155"){const r=await this.getEIP155Balances(e,t);if(r)return this.filterLowQualityTokens(r)}const i=await X.getBalance(e,t.caipNetworkId,s);return this.filterLowQualityTokens(i.balances)},async getEIP155Balances(s,e){var t,i;try{const r=Ll.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),n=await Ue.getCapabilities(s);if(!((i=(t=n==null?void 0:n[r])==null?void 0:t.assetDiscovery)!=null&&i.supported))return null;const o=await Ue.walletGetAssets({account:s,chainFilter:[r]});return Ll.isWalletGetAssetsResponse(o)?(o[r]||[]).map(l=>Ll.createBalance(l,e.caipNetworkId)):null}catch{return null}},filterLowQualityTokens(s){return s.filter(e=>e.quantity.decimals!=="0")},mapBalancesToSwapTokens(s){return(s==null?void 0:s.map(e=>({...e,address:e!=null&&e.address?e.address:v.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]}},ue=Xe({tokenBalances:[],loading:!1}),mg={state:ue,subscribe(s){return Yt(ue,()=>s(ue))},subscribeKey(s,e){return vs(ue,s,e)},setToken(s){s&&(ue.token=Ir(s))},setTokenAmount(s){ue.sendTokenAmount=s},setReceiverAddress(s){ue.receiverAddress=s},setReceiverProfileImageUrl(s){ue.receiverProfileImageUrl=s},setReceiverProfileName(s){ue.receiverProfileName=s},setGasPrice(s){ue.gasPrice=s},setGasPriceInUsd(s){ue.gasPriceInUSD=s},setNetworkBalanceInUsd(s){ue.networkBalanceInUSD=s},setLoading(s){ue.loading=s},sendToken(){var s;switch((s=v.state.activeCaipNetwork)==null?void 0:s.chainNamespace){case"eip155":this.sendEvmToken();return;case"solana":this.sendSolanaToken();return;default:throw new Error("Unsupported chain")}},sendEvmToken(){var s,e,t,i,r;(s=this.state.token)!=null&&s.address&&this.state.sendTokenAmount&&this.state.receiverAddress?(ze.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token.address,amount:this.state.sendTokenAmount,network:((e=v.state.activeCaipNetwork)==null?void 0:e.caipNetworkId)||""}}),this.sendERC20Token({receiverAddress:this.state.receiverAddress,tokenAddress:this.state.token.address,sendTokenAmount:this.state.sendTokenAmount,decimals:this.state.token.quantity.decimals})):this.state.receiverAddress&&this.state.sendTokenAmount&&this.state.gasPrice&&((t=this.state.token)!=null&&t.quantity.decimals)&&(ze.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT,token:(i=this.state.token)==null?void 0:i.symbol,amount:this.state.sendTokenAmount,network:((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||""}}),this.sendNativeToken({receiverAddress:this.state.receiverAddress,sendTokenAmount:this.state.sendTokenAmount,gasPrice:this.state.gasPrice,decimals:this.state.token.quantity.decimals}))},async fetchTokenBalance(s){var n,o;ue.loading=!0;const e=(n=v.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,t=(o=v.state.activeCaipNetwork)==null?void 0:o.chainNamespace,i=v.state.activeCaipAddress,r=i?se.getPlainAddress(i):void 0;if(ue.lastRetry&&!se.isAllowedRetry(ue.lastRetry,30*os.ONE_SEC_MS))return ue.loading=!1,[];try{if(r&&e&&t){const a=await fg.getMyTokensWithBalance();return ue.tokenBalances=a,ue.lastRetry=void 0,a}}catch(a){ue.lastRetry=Date.now(),s==null||s(a),xt.showError("Token Balance Unavailable")}finally{ue.loading=!1}return[]},fetchNetworkBalance(){if(ue.tokenBalances.length===0)return;const s=fg.mapBalancesToSwapTokens(ue.tokenBalances);if(!s)return;const e=s.find(t=>t.address===v.getActiveNetworkTokenAddress());e&&(ue.networkBalanceInUSD=e?za.multiply(e.quantity.numeric,e.price).toString():"0")},isInsufficientNetworkTokenForGas(s,e){const t=e||"0";return za.bigNumber(s).eq(0)?!0:za.bigNumber(za.bigNumber(t)).gt(s)},hasInsufficientGasFunds(){let s=!0;return Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT?s=!1:ue.networkBalanceInUSD&&(s=this.isInsufficientNetworkTokenForGas(ue.networkBalanceInUSD,ue.gasPriceInUSD)),s},async sendNativeToken(s){var n,o,a,l;Se.pushTransactionStack({view:"Account",goBack:!1});const e=s.receiverAddress,t=Z.state.address,i=Ue.parseUnits(s.sendTokenAmount.toString(),Number(s.decimals)),r="0x";try{await Ue.sendTransaction({chainNamespace:"eip155",to:e,address:t,data:r,value:i??BigInt(0),gasPrice:s.gasPrice}),xt.showSuccess("Transaction started"),ze.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT,token:((n=this.state.token)==null?void 0:n.symbol)||"",amount:s.sendTokenAmount,network:((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)||""}}),this.resetSend()}catch(c){console.error("SendController:sendERC20Token - failed to send native token",c);const h=c instanceof Error?c.message:"Unknown error";ze.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:h,isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT,token:((a=this.state.token)==null?void 0:a.symbol)||"",amount:s.sendTokenAmount,network:((l=v.state.activeCaipNetwork)==null?void 0:l.caipNetworkId)||""}}),xt.showError("Something went wrong")}},async sendERC20Token(s){var t,i;Se.pushTransactionStack({view:"Account",goBack:!1});const e=Ue.parseUnits(s.sendTokenAmount.toString(),Number(s.decimals));try{if(Z.state.address&&s.sendTokenAmount&&s.receiverAddress&&s.tokenAddress){const r=se.getPlainAddress(s.tokenAddress);await Ue.writeContract({fromAddress:Z.state.address,tokenAddress:r,args:[s.receiverAddress,e??BigInt(0)],method:"transfer",abi:sD.getERC20Abi(r),chainNamespace:"eip155"}),xt.showSuccess("Transaction started"),this.resetSend()}}catch(r){console.error("SendController:sendERC20Token - failed to send erc20 token",r);const n=r instanceof Error?r.message:"Unknown error";ze.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:n,isSmartAccount:Z.state.preferredAccountType===Pi.ACCOUNT_TYPES.SMART_ACCOUNT,token:((t=this.state.token)==null?void 0:t.symbol)||"",amount:s.sendTokenAmount,network:((i=v.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||""}}),xt.showError("Something went wrong")}},sendSolanaToken(){if(!this.state.sendTokenAmount||!this.state.receiverAddress){xt.showError("Please enter a valid amount and receiver address");return}Se.pushTransactionStack({view:"Account",goBack:!1}),Ue.sendTransaction({chainNamespace:"solana",to:this.state.receiverAddress,value:this.state.sendTokenAmount}).then(()=>{this.resetSend(),Z.fetchTokenBalance()}).catch(s=>{xt.showError("Failed to send transaction. Please try again."),console.error("SendController:sendToken - failed to send solana transaction",s)})},resetSend(){ue.token=void 0,ue.sendTokenAmount=void 0,ue.receiverAddress=void 0,ue.receiverProfileImageUrl=void 0,ue.receiverProfileName=void 0,ue.loading=!1,ue.tokenBalances=[]}},Ul={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},qa={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},F=Xe({chains:cD(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),v={state:F,subscribe(s){return Yt(F,()=>{s(F)})},subscribeKey(s,e){return vs(F,s,e)},subscribeChainProp(s,e,t){let i;return Yt(F.chains,()=>{var n;const r=t||F.activeChain;if(r){const o=(n=F.chains.get(r))==null?void 0:n[s];i!==o&&(i=o,e(o))}})},initialize(s,e,t){const{chainId:i,namespace:r}=G.getActiveNetworkProps(),n=e==null?void 0:e.find(c=>c.id.toString()===(i==null?void 0:i.toString())),a=s.find(c=>(c==null?void 0:c.namespace)===r)||(s==null?void 0:s[0]),l=new Set([...(e==null?void 0:e.map(c=>c.chainNamespace))??[]]);((s==null?void 0:s.length)===0||!a)&&(F.noAdapters=!0),F.noAdapters||(F.activeChain=a==null?void 0:a.namespace,F.activeCaipNetwork=n,this.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:n}),F.activeChain&&fi.set({activeChain:a==null?void 0:a.namespace})),l.forEach(c=>{const h=e==null?void 0:e.filter(u=>u.chainNamespace===c);v.state.chains.set(c,{namespace:c,networkState:Xe({...qa,caipNetwork:h==null?void 0:h[0]}),accountState:Xe(Ul),caipNetworks:h??[],...t}),this.setRequestedCaipNetworks(h??[],c)})},removeAdapter(s){var e,t;if(F.activeChain===s){const i=Array.from(F.chains.entries()).find(([r])=>r!==s);if(i){const r=(t=(e=i[1])==null?void 0:e.caipNetworks)==null?void 0:t[0];r&&this.setActiveCaipNetwork(r)}}F.chains.delete(s)},addAdapter(s,{networkControllerClient:e,connectionControllerClient:t},i){F.chains.set(s.namespace,{namespace:s.namespace,networkState:{...qa,caipNetwork:i[0]},accountState:Ul,caipNetworks:i,connectionControllerClient:t,networkControllerClient:e}),this.setRequestedCaipNetworks((i==null?void 0:i.filter(r=>r.chainNamespace===s.namespace))??[],s.namespace)},addNetwork(s){var t;const e=F.chains.get(s.chainNamespace);if(e){const i=[...e.caipNetworks||[]];(t=e.caipNetworks)!=null&&t.find(r=>r.id===s.id)||i.push(s),F.chains.set(s.chainNamespace,{...e,caipNetworks:i}),this.setRequestedCaipNetworks(i,s.chainNamespace)}},removeNetwork(s,e){var i,r,n;const t=F.chains.get(s);if(t){const o=((i=F.activeCaipNetwork)==null?void 0:i.id)===e,a=[...((r=t.caipNetworks)==null?void 0:r.filter(l=>l.id!==e))||[]];o&&((n=t==null?void 0:t.caipNetworks)!=null&&n[0])&&this.setActiveCaipNetwork(t.caipNetworks[0]),F.chains.set(s,{...t,caipNetworks:a}),this.setRequestedCaipNetworks(a||[],s)}},setAdapterNetworkState(s,e){const t=F.chains.get(s);t&&(t.networkState={...t.networkState||qa,...e},F.chains.set(s,t))},setChainAccountData(s,e,t=!0){if(!s)throw new Error("Chain is required to update chain account data");const i=F.chains.get(s);if(i){const r={...i.accountState||Ul,...e};F.chains.set(s,{...i,accountState:r}),(F.chains.size===1||F.activeChain===s)&&(e.caipAddress&&(F.activeCaipAddress=e.caipAddress),Z.replaceState(r))}},setChainNetworkData(s,e){if(!s)return;const t=F.chains.get(s);if(t){const i={...t.networkState||qa,...e};F.chains.set(s,{...t,networkState:i})}},setAccountProp(s,e,t,i=!0){this.setChainAccountData(t,{[s]:e},i),s==="status"&&e==="disconnected"&&t&&te.removeConnectorId(t)},setActiveNamespace(s){var i,r;F.activeChain=s;const e=s?F.chains.get(s):void 0,t=(i=e==null?void 0:e.networkState)==null?void 0:i.caipNetwork;t!=null&&t.id&&s&&(F.activeCaipAddress=(r=e==null?void 0:e.accountState)==null?void 0:r.caipAddress,F.activeCaipNetwork=t,this.setChainNetworkData(s,{caipNetwork:t}),G.setActiveCaipNetworkId(t==null?void 0:t.caipNetworkId),fi.set({activeChain:s,selectedNetworkId:t==null?void 0:t.caipNetworkId}))},setActiveCaipNetwork(s){var i,r,n;if(!s)return;F.activeChain!==s.chainNamespace&&this.setIsSwitchingNamespace(!0);const e=F.chains.get(s.chainNamespace);F.activeChain=s.chainNamespace,F.activeCaipNetwork=s,this.setChainNetworkData(s.chainNamespace,{caipNetwork:s}),(i=e==null?void 0:e.accountState)!=null&&i.address?F.activeCaipAddress=`${s.chainNamespace}:${s.id}:${(r=e==null?void 0:e.accountState)==null?void 0:r.address}`:F.activeCaipAddress=void 0,this.setAccountProp("caipAddress",F.activeCaipAddress,s.chainNamespace),e&&Z.replaceState(e.accountState),mg.resetSend(),fi.set({activeChain:F.activeChain,selectedNetworkId:(n=F.activeCaipNetwork)==null?void 0:n.caipNetworkId}),G.setActiveCaipNetworkId(s.caipNetworkId),!this.checkIfSupportedNetwork(s.chainNamespace)&&D.state.enableNetworkSwitch&&!D.state.allowUnsupportedChain&&!Ue.state.wcBasic&&this.showUnsupportedChainUI()},addCaipNetwork(s){var t;if(!s)return;const e=F.chains.get(s.chainNamespace);e&&((t=e==null?void 0:e.caipNetworks)==null||t.push(s))},async switchActiveNamespace(s){var r;if(!s)return;const e=s!==v.state.activeChain,t=(r=v.getNetworkData(s))==null?void 0:r.caipNetwork,i=v.getCaipNetworkByNamespace(s,t==null?void 0:t.id);e&&i&&await v.switchActiveNetwork(i)},async switchActiveNetwork(s){var r;const e=v.state.chains.get(v.state.activeChain);!((r=e==null?void 0:e.caipNetworks)!=null&&r.some(n=>{var o;return n.id===((o=F.activeCaipNetwork)==null?void 0:o.id)}))&&Se.goBack();const i=this.getNetworkControllerClient(s.chainNamespace);i&&(await i.switchCaipNetwork(s),ze.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:s.caipNetworkId}}))},getNetworkControllerClient(s){const e=s||F.activeChain,t=F.chains.get(e);if(!t)throw new Error("Chain adapter not found");if(!t.networkControllerClient)throw new Error("NetworkController client not set");return t.networkControllerClient},getConnectionControllerClient(s){const e=s||F.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const t=F.chains.get(e);if(!(t!=null&&t.connectionControllerClient))throw new Error("ConnectionController client not set");return t.connectionControllerClient},getAccountProp(s,e){var r;let t=F.activeChain;if(e&&(t=e),!t)return;const i=(r=F.chains.get(t))==null?void 0:r.accountState;if(i)return i[s]},getNetworkProp(s,e){var i;const t=(i=F.chains.get(e))==null?void 0:i.networkState;if(t)return t[s]},getRequestedCaipNetworks(s){const e=F.chains.get(s),{approvedCaipNetworkIds:t=[],requestedCaipNetworks:i=[]}=(e==null?void 0:e.networkState)||{};return se.sortRequestedNetworks(t,i)},getAllRequestedCaipNetworks(){const s=[];return F.chains.forEach(e=>{const t=this.getRequestedCaipNetworks(e.namespace);s.push(...t)}),s},setRequestedCaipNetworks(s,e){this.setAdapterNetworkState(e,{requestedCaipNetworks:s})},getAllApprovedCaipNetworkIds(){const s=[];return F.chains.forEach(e=>{const t=this.getApprovedCaipNetworkIds(e.namespace);s.push(...t)}),s},getActiveCaipNetwork(){return F.activeCaipNetwork},getActiveCaipAddress(){return F.activeCaipAddress},getApprovedCaipNetworkIds(s){var i;const e=F.chains.get(s);return((i=e==null?void 0:e.networkState)==null?void 0:i.approvedCaipNetworkIds)||[]},async setApprovedCaipNetworksData(s){const e=this.getNetworkControllerClient(),t=await(e==null?void 0:e.getApprovedCaipNetworksData());this.setAdapterNetworkState(s,{approvedCaipNetworkIds:t==null?void 0:t.approvedCaipNetworkIds,supportsAllNetworks:t==null?void 0:t.supportsAllNetworks})},checkIfSupportedNetwork(s,e){const t=e||F.activeCaipNetwork,i=this.getRequestedCaipNetworks(s);return i.length?i==null?void 0:i.some(r=>r.id===(t==null?void 0:t.id)):!0},checkIfSupportedChainId(s){if(!F.activeChain)return!0;const e=this.getRequestedCaipNetworks(F.activeChain);return e==null?void 0:e.some(t=>t.id===s)},setSmartAccountEnabledNetworks(s,e){this.setAdapterNetworkState(e,{smartAccountEnabledNetworks:s})},checkIfSmartAccountEnabled(){var i;const s=Iy.caipNetworkIdToNumber((i=F.activeCaipNetwork)==null?void 0:i.caipNetworkId),e=F.activeChain;if(!e||!s)return!1;const t=this.getNetworkProp("smartAccountEnabledNetworks",e);return!!(t!=null&&t.includes(Number(s)))},getActiveNetworkTokenAddress(){var i,r;const s=((i=F.activeCaipNetwork)==null?void 0:i.chainNamespace)||"eip155",e=((r=F.activeCaipNetwork)==null?void 0:r.id)||1,t=os.NATIVE_TOKEN_ADDRESS[s];return`${s}:${e}:${t}`},showUnsupportedChainUI(){ct.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const s=F.activeCaipNetwork;return!!(s!=null&&s.chainNamespace&&os.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(s.chainNamespace))},resetNetwork(s){this.setAdapterNetworkState(s,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(s){const e=s;if(!e)throw new Error("Chain is required to set account prop");F.activeCaipAddress=void 0,this.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),te.removeConnectorId(e)},async disconnect(s){const e=yD(s);try{mg.resetSend();const t=await Promise.allSettled(e.map(async([r,n])=>{var o;try{const{caipAddress:a}=this.getAccountData(r)||{};a&&((o=n.connectionControllerClient)!=null&&o.disconnect)&&await n.connectionControllerClient.disconnect(r),this.resetAccount(r),this.resetNetwork(r)}catch(a){throw new Error(`Failed to disconnect chain ${r}: ${a.message}`)}}));Ue.resetWcConnection();const i=t.filter(r=>r.status==="rejected");if(i.length>0)throw new Error(i.map(r=>r.reason.message).join(", "));G.deleteConnectedSocialProvider(),s?te.removeConnectorId(s):te.resetConnectorIds(),ze.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:s||"all"}})}catch(t){console.error(t.message||"Failed to disconnect chains"),ze.sendEvent({type:"track",event:"DISCONNECT_ERROR",properties:{message:t.message||"Failed to disconnect chains"}})}},setIsSwitchingNamespace(s){F.isSwitchingNamespace=s},getFirstCaipNetworkSupportsAuthConnector(){var t,i;const s=[];let e;if(F.chains.forEach(r=>{Q.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===r.namespace)&&r.namespace&&s.push(r.namespace)}),s.length>0){const r=s[0];return e=r?(i=(t=F.chains.get(r))==null?void 0:t.caipNetworks)==null?void 0:i[0]:void 0,e}},getAccountData(s){var e;return s?(e=v.state.chains.get(s))==null?void 0:e.accountState:Z.state},getNetworkData(s){var t;const e=s||F.activeChain;if(e)return(t=v.state.chains.get(e))==null?void 0:t.networkState},getCaipNetworkByNamespace(s,e){var r,n,o;if(!s)return;const t=v.state.chains.get(s),i=(r=t==null?void 0:t.caipNetworks)==null?void 0:r.find(a=>a.id===e);return i||((n=t==null?void 0:t.networkState)==null?void 0:n.caipNetwork)||((o=t==null?void 0:t.caipNetworks)==null?void 0:o[0])},getRequestedCaipNetworkIds(){const s=te.state.filterByNamespace;return(s?[F.chains.get(s)]:Array.from(F.chains.values())).flatMap(t=>(t==null?void 0:t.caipNetworks)||[]).map(t=>t.caipNetworkId)}},zD={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"}]}]},Cy=se.getBlockchainApiUrl(),cs=Xe({clientId:null,api:new tl({baseUrl:Cy,clientId:null}),supportedChains:{http:[],ws:[]}}),X={state:cs,async get(s){const{st:e,sv:t}=X.getSdkProperties(),i=D.state.projectId,r={...s.params||{},st:e,sv:t,projectId:i};return cs.api.get({...s,params:r})},getSdkProperties(){const{sdkType:s,sdkVersion:e}=D.state;return{st:s||"unknown",sv:e||"unknown"}},async isNetworkSupported(s){if(!s)return!1;try{cs.supportedChains.http.length||await X.getSupportedNetworks()}catch{return!1}return cs.supportedChains.http.includes(s)},async getSupportedNetworks(){const s=await X.get({path:"v1/supported-chains"});return cs.supportedChains=s,s},async fetchIdentity({address:s,caipNetworkId:e}){if(!await X.isNetworkSupported(e))return{avatar:"",name:""};const i=G.getIdentityFromCacheForAddress(s);if(i)return i;const r=await X.get({path:`/v1/identity/${s}`,params:{sender:v.state.activeCaipAddress?se.getPlainAddress(v.state.activeCaipAddress):void 0}});return G.updateIdentityCache({address:s,identity:r,timestamp:Date.now()}),r},async fetchTransactions({account:s,cursor:e,onramp:t,signal:i,cache:r,chainId:n}){var a;return await X.isNetworkSupported((a=v.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?X.get({path:`/v1/account/${s}/history`,params:{cursor:e,onramp:t,chainId:n},signal:i,cache:r}):{data:[],next:void 0}},async fetchSwapQuote({amount:s,userAddress:e,from:t,to:i,gasPrice:r}){var o;return await X.isNetworkSupported((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?X.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:s,userAddress:e,from:t,to:i,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:s}){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?X.get({path:"/v1/convert/tokens",params:{chainId:s}}):{tokens:[]}},async fetchTokenPrice({addresses:s}){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?cs.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:s,projectId:D.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:s,userAddress:e}){var i;return await X.isNetworkSupported((i=v.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?X.get({path:"/v1/convert/allowance",params:{tokenAddress:s,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:s}){var r;const{st:e,sv:t}=X.getSdkProperties();if(!await X.isNetworkSupported((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))throw new Error("Network not supported for Gas Price");return X.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:s,st:e,sv:t}})},async generateSwapCalldata({amount:s,from:e,to:t,userAddress:i,disableEstimate:r}){var o;if(!await X.isNetworkSupported((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return cs.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:s,eip155:{slippage:os.CONVERT_SLIPPAGE_TOLERANCE},projectId:D.state.projectId,from:e,to:t,userAddress:i,disableEstimate:r}})},async generateApproveCalldata({from:s,to:e,userAddress:t}){var o;const{st:i,sv:r}=X.getSdkProperties();if(!await X.isNetworkSupported((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return X.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:t,from:s,to:e,st:i,sv:r}})},async getBalance(s,e,t){var c;const{st:i,sv:r}=X.getSdkProperties();if(!await X.isNetworkSupported((c=v.state.activeCaipNetwork)==null?void 0:c.caipNetworkId))return xt.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${s}`,a=G.getBalanceCacheForCaipAddress(o);if(a)return a;const l=await X.get({path:`/v1/account/${s}/balance`,params:{currency:"usd",chainId:e,forceUpdate:t,st:i,sv:r}});return G.updateBalanceCache({caipAddress:o,balance:l,timestamp:Date.now()}),l},async lookupEnsName(s){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?X.get({path:`/v1/profile/account/${s}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:s}){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?X.get({path:`/v1/profile/reverse/${s}`,params:{sender:Z.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(s){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?X.get({path:`/v1/profile/suggestions/${s}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:s,address:e,message:t,signature:i}){var n;return await X.isNetworkSupported((n=v.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?cs.api.post({path:"/v1/profile/account",body:{coin_type:s,address:e,message:t,signature:i},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:s,partnerUserId:e,defaultNetwork:t,purchaseAmount:i,paymentAmount:r}){var a;return await X.isNetworkSupported((a=v.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await cs.api.post({path:"/v1/generators/onrampurl",params:{projectId:D.state.projectId},body:{destinationWallets:s,defaultNetwork:t,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:i,presetFiatAmount:r}})).url:""},async getOnrampOptions(){var e;if(!await X.isNetworkSupported((e=v.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await X.get({path:"/v1/onramp/options"})}catch{return zD}},async getOnrampQuote({purchaseCurrency:s,paymentCurrency:e,amount:t,network:i}){var r;try{return await X.isNetworkSupported((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?await cs.api.post({path:"/v1/onramp/quote",params:{projectId:D.state.projectId},body:{purchaseCurrency:s,paymentCurrency:e,amount:t,network:i}}):null}catch{return{coinbaseFee:{amount:t,currency:e.id},networkFee:{amount:t,currency:e.id},paymentSubtotal:{amount:t,currency:e.id},paymentTotal:{amount:t,currency:e.id},purchaseAmount:{amount:t,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(s){var t;return await X.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?X.get({path:`/v1/sessions/${s}`}):[]},async revokeSmartSession(s,e,t){var r;return await X.isNetworkSupported((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?cs.api.post({path:`/v1/sessions/${s}/revoke`,params:{projectId:D.state.projectId},body:{pci:e,signature:t}}):{success:!1}},setClientId(s){cs.clientId=s,cs.api=new tl({baseUrl:Cy,clientId:s})}},Ks=Xe({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),Z={state:Ks,replaceState(s){s&&Object.assign(Ks,Ir(s))},subscribe(s){return v.subscribeChainProp("accountState",e=>{if(e)return s(e)})},subscribeKey(s,e,t){let i;return v.subscribeChainProp("accountState",r=>{if(r){const n=r[s];i!==n&&(i=n,e(n))}},t)},setStatus(s,e){v.setAccountProp("status",s,e)},getCaipAddress(s){return v.getAccountProp("caipAddress",s)},setCaipAddress(s,e){const t=s?se.getPlainAddress(s):void 0;e===v.state.activeChain&&(v.state.activeCaipAddress=s),v.setAccountProp("caipAddress",s,e),v.setAccountProp("address",t,e)},setBalance(s,e,t){v.setAccountProp("balance",s,t),v.setAccountProp("balanceSymbol",e,t)},setProfileName(s,e){v.setAccountProp("profileName",s,e)},setProfileImage(s,e){v.setAccountProp("profileImage",s,e)},setUser(s,e){v.setAccountProp("user",s,e)},setAddressExplorerUrl(s,e){v.setAccountProp("addressExplorerUrl",s,e)},setSmartAccountDeployed(s,e){v.setAccountProp("smartAccountDeployed",s,e)},setCurrentTab(s){v.setAccountProp("currentTab",s,v.state.activeChain)},setTokenBalance(s,e){s&&v.setAccountProp("tokenBalance",s,e)},setShouldUpdateToAddress(s,e){v.setAccountProp("shouldUpdateToAddress",s,e)},setAllAccounts(s,e){v.setAccountProp("allAccounts",s,e)},addAddressLabel(s,e,t){const i=v.getAccountProp("addressLabels",t)||new Map;i.set(s,e),v.setAccountProp("addressLabels",i,t)},removeAddressLabel(s,e){const t=v.getAccountProp("addressLabels",e)||new Map;t.delete(s),v.setAccountProp("addressLabels",t,e)},setConnectedWalletInfo(s,e){v.setAccountProp("connectedWalletInfo",s,e,!1)},setPreferredAccountType(s,e){v.setAccountProp("preferredAccountType",s,e)},setSocialProvider(s,e){s&&v.setAccountProp("socialProvider",s,e)},setSocialWindow(s,e){v.setAccountProp("socialWindow",s?Ir(s):void 0,e)},setFarcasterUrl(s,e){v.setAccountProp("farcasterUrl",s,e)},async fetchTokenBalance(s){var n,o;Ks.balanceLoading=!0;const e=(n=v.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,t=(o=v.state.activeCaipNetwork)==null?void 0:o.chainNamespace,i=v.state.activeCaipAddress,r=i?se.getPlainAddress(i):void 0;if(Ks.lastRetry&&!se.isAllowedRetry(Ks.lastRetry,30*os.ONE_SEC_MS))return Ks.balanceLoading=!1,[];try{if(r&&e&&t){const l=(await X.getBalance(r,e)).balances.filter(c=>c.quantity.decimals!=="0");return this.setTokenBalance(l,t),Ks.lastRetry=void 0,Ks.balanceLoading=!1,l}}catch(a){Ks.lastRetry=Date.now(),s==null||s(a),xt.showError("Token Balance Unavailable")}finally{Ks.balanceLoading=!1}return[]},resetAccount(s){v.resetAccount(s)}},Jt=Xe({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),ct={state:Jt,subscribe(s){return Yt(Jt,()=>s(Jt))},subscribeKey(s,e){return vs(Jt,s,e)},async open(s){var r;const e=Z.state.status==="connected";Ue.state.wcBasic?ie.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await ie.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),s!=null&&s.namespace?(await v.switchActiveNamespace(s.namespace),ct.setLoading(!0,s.namespace)):ct.setLoading(!0),te.setFilterByNamespace(s==null?void 0:s.namespace);const t=(r=v.getAccountData(s==null?void 0:s.namespace))==null?void 0:r.caipAddress;v.state.noAdapters&&!t?se.isMobile()?Se.reset("AllWallets"):Se.reset("ConnectingWalletConnectBasic"):s!=null&&s.view?Se.reset(s.view):t?Se.reset("Account"):Se.reset("Connect"),Jt.open=!0,fi.set({open:!0}),ze.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!t}})},close(){const s=D.state.enableEmbedded,e=!!v.state.activeCaipAddress;Jt.open&&ze.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),Jt.open=!1,ct.clearLoading(),s?e?Se.replace("Account"):Se.push("Connect"):fi.set({open:!1}),Ue.resetUri()},setLoading(s,e){e&&Jt.loadingNamespaceMap.set(e,s),Jt.loading=s,fi.set({loading:s})},clearLoading(){Jt.loadingNamespaceMap.clear(),Jt.loading=!1},shake(){Jt.shake||(Jt.shake=!0,setTimeout(()=>{Jt.shake=!1},500))}},wg=2147483648,FD={convertEVMChainIdToCoinType(s){if(s>=wg)throw new Error("Invalid chainId");return(wg|s)>>>0}},Es=Xe({suggestions:[],loading:!1}),Sy={state:Es,subscribe(s){return Yt(Es,()=>s(Es))},subscribeKey(s,e){return vs(Es,s,e)},async resolveName(s){var e,t;try{return await X.lookupEnsName(s)}catch(i){const r=i;throw new Error(((t=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:t.description)||"Error resolving name")}},async isNameRegistered(s){try{return await X.lookupEnsName(s),!0}catch{return!1}},async getSuggestions(s){try{Es.loading=!0,Es.suggestions=[];const e=await X.getEnsNameSuggestions(s);return Es.suggestions=e.suggestions.map(t=>({...t,name:t.name}))||[],Es.suggestions}catch(e){const t=this.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(t)}finally{Es.loading=!1}},async getNamesForAddress(s){try{if(!v.state.activeCaipNetwork)return[];const t=G.getEnsFromCacheForAddress(s);if(t)return t;const i=await X.reverseLookupEnsName({address:s});return G.updateEnsCache({address:s,ens:i,timestamp:Date.now()}),i}catch(e){const t=this.parseEnsApiError(e,"Error fetching names for address");throw new Error(t)}},async registerName(s){const e=v.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const t=Z.state.address,i=te.getAuthConnector();if(!t||!i)throw new Error("Address or auth connector not found");Es.loading=!0;try{const r=JSON.stringify({name:s,attributes:{},timestamp:Math.floor(Date.now()/1e3)});Se.pushTransactionStack({view:"RegisterAccountNameSuccess",goBack:!1,replace:!0,onCancel(){Es.loading=!1}});const n=await Ue.signMessage(r),o=e.id;if(!o)throw new Error("Network not found");const a=FD.convertEVMChainIdToCoinType(Number(o));await X.registerEnsName({coinType:a,address:t,signature:n,message:r}),Z.setProfileName(s,e.chainNamespace),Se.replace("RegisterAccountNameSuccess")}catch(r){const n=this.parseEnsApiError(r,`Error registering name ${s}`);throw Se.replace("RegisterAccountName"),new Error(n)}finally{Es.loading=!1}},validateName(s){return/^[a-zA-Z0-9-]{4,}$/u.test(s)},parseEnsApiError(s,e){var i,r;const t=s;return((r=(i=t==null?void 0:t.reasons)==null?void 0:i[0])==null?void 0:r.description)||e}};function qD(s){return!s||typeof s.then!="function"?Promise.resolve(s):s}function bt(s,...e){try{return qD(s(...e))}catch(t){return Promise.reject(t)}}function BD(s){const e=typeof s;return s===null||e!=="object"&&e!=="function"}function HD(s){const e=Object.getPrototypeOf(s);return!e||e.isPrototypeOf(Object)}function cc(s){if(BD(s))return String(s);if(HD(s)||Array.isArray(s))return JSON.stringify(s);if(typeof s.toJSON=="function")return cc(s.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Bh="base64:";function WD(s){return typeof s=="string"?s:Bh+GD(s)}function VD(s){return typeof s!="string"||!s.startsWith(Bh)?s:KD(s.slice(Bh.length))}function KD(s){return globalThis.Buffer?_.Buffer.from(s,"base64"):Uint8Array.from(globalThis.atob(s),e=>e.codePointAt(0))}function GD(s){return globalThis.Buffer?_.Buffer.from(s).toString("base64"):globalThis.btoa(String.fromCodePoint(...s))}function ss(s){var e;return s&&((e=s.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function YD(...s){return ss(s.join(":"))}function Ba(s){return s=ss(s),s?s+":":""}function QD(s,e){if(e===void 0)return!0;let t=0,i=s.indexOf(":");for(;i>-1;)t++,i=s.indexOf(":",i+1);return t<=e}function ZD(s,e){return e?s.startsWith(e)&&s[s.length-1]!=="$":s[s.length-1]!=="$"}const JD="memory",XD=()=>{const s=new Map;return{name:JD,getInstance:()=>s,hasItem(e){return s.has(e)},getItem(e){return s.get(e)??null},getItemRaw(e){return s.get(e)??null},setItem(e,t){s.set(e,t)},setItemRaw(e,t){s.set(e,t)},removeItem(e){s.delete(e)},getKeys(){return[...s.keys()]},clear(){s.clear()},dispose(){s.clear()}}};function ek(s={}){const e={mounts:{"":s.driver||XD()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=c=>{for(const h of e.mountpoints)if(c.startsWith(h))return{base:h,relativeKey:c.slice(h.length),driver:e.mounts[h]};return{base:"",relativeKey:c,driver:e.mounts[""]}},i=(c,h)=>e.mountpoints.filter(u=>u.startsWith(c)||h&&c.startsWith(u)).map(u=>({relativeBase:c.length>u.length?c.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(c,h)=>{if(e.watching){h=ss(h);for(const u of e.watchListeners)u(c,h)}},n=async()=>{if(!e.watching){e.watching=!0;for(const c in e.mounts)e.unwatch[c]=await yg(e.mounts[c],r,c)}},o=async()=>{if(e.watching){for(const c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},a=(c,h,u)=>{const d=new Map,p=g=>{let f=d.get(g.base);return f||(f={driver:g.driver,base:g.base,items:[]},d.set(g.base,f)),f};for(const g of c){const f=typeof g=="string",y=ss(f?g:g.key),w=f?void 0:g.value,m=f||!g.options?h:{...h,...g.options},b=t(y);p(b).items.push({key:y,value:w,relativeKey:b.relativeKey,options:m})}return Promise.all([...d.values()].map(g=>u(g))).then(g=>g.flat())},l={hasItem(c,h={}){c=ss(c);const{relativeKey:u,driver:d}=t(c);return bt(d.hasItem,u,h)},getItem(c,h={}){c=ss(c);const{relativeKey:u,driver:d}=t(c);return bt(d.getItem,u,h).then(p=>Di(p))},getItems(c,h={}){return a(c,h,u=>u.driver.getItems?bt(u.driver.getItems,u.items.map(d=>({key:d.relativeKey,options:d.options})),h).then(d=>d.map(p=>({key:YD(u.base,p.key),value:Di(p.value)}))):Promise.all(u.items.map(d=>bt(u.driver.getItem,d.relativeKey,d.options).then(p=>({key:d.key,value:Di(p)})))))},getItemRaw(c,h={}){c=ss(c);const{relativeKey:u,driver:d}=t(c);return d.getItemRaw?bt(d.getItemRaw,u,h):bt(d.getItem,u,h).then(p=>VD(p))},async setItem(c,h,u={}){if(h===void 0)return l.removeItem(c);c=ss(c);const{relativeKey:d,driver:p}=t(c);p.setItem&&(await bt(p.setItem,d,cc(h),u),p.watch||r("update",c))},async setItems(c,h){await a(c,h,async u=>{if(u.driver.setItems)return bt(u.driver.setItems,u.items.map(d=>({key:d.relativeKey,value:cc(d.value),options:d.options})),h);u.driver.setItem&&await Promise.all(u.items.map(d=>bt(u.driver.setItem,d.relativeKey,cc(d.value),d.options)))})},async setItemRaw(c,h,u={}){if(h===void 0)return l.removeItem(c,u);c=ss(c);const{relativeKey:d,driver:p}=t(c);if(p.setItemRaw)await bt(p.setItemRaw,d,h,u);else if(p.setItem)await bt(p.setItem,d,WD(h),u);else return;p.watch||r("update",c)},async removeItem(c,h={}){typeof h=="boolean"&&(h={removeMeta:h}),c=ss(c);const{relativeKey:u,driver:d}=t(c);d.removeItem&&(await bt(d.removeItem,u,h),(h.removeMeta||h.removeMata)&&await bt(d.removeItem,u+"$",h),d.watch||r("remove",c))},async getMeta(c,h={}){typeof h=="boolean"&&(h={nativeOnly:h}),c=ss(c);const{relativeKey:u,driver:d}=t(c),p=Object.create(null);if(d.getMeta&&Object.assign(p,await bt(d.getMeta,u,h)),!h.nativeOnly){const g=await bt(d.getItem,u+"$",h).then(f=>Di(f));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(p,g))}return p},setMeta(c,h,u={}){return this.setItem(c+"$",h,u)},removeMeta(c,h={}){return this.removeItem(c+"$",h)},async getKeys(c,h={}){var y;c=Ba(c);const u=i(c,!0);let d=[];const p=[];let g=!0;for(const w of u){(y=w.driver.flags)!=null&&y.maxDepth||(g=!1);const m=await bt(w.driver.getKeys,w.relativeBase,h);for(const b of m){const I=w.mountpoint+ss(b);d.some(N=>I.startsWith(N))||p.push(I)}d=[w.mountpoint,...d.filter(b=>!b.startsWith(w.mountpoint))]}const f=h.maxDepth!==void 0&&!g;return p.filter(w=>(!f||QD(w,h.maxDepth))&&ZD(w,c))},async clear(c,h={}){c=Ba(c),await Promise.all(i(c,!1).map(async u=>{if(u.driver.clear)return bt(u.driver.clear,u.relativeBase,h);if(u.driver.removeItem){const d=await u.driver.getKeys(u.relativeBase||"",h);return Promise.all(d.map(p=>u.driver.removeItem(p,h)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>bg(c)))},async watch(c){return await n(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(h=>h!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,h){if(c=Ba(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((u,d)=>d.length-u.length)),e.mounts[c]=h,e.watching&&Promise.resolve(yg(h,r,c)).then(u=>{e.unwatch[c]=u}).catch(console.error),l},async unmount(c,h=!0){var u,d;c=Ba(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&((d=(u=e.unwatch)[c])==null||d.call(u),delete e.unwatch[c]),h&&await bg(e.mounts[c]),e.mountpoints=e.mountpoints.filter(p=>p!==c),delete e.mounts[c])},getMount(c=""){c=ss(c)+":";const h=t(c);return{driver:h.driver,base:h.base}},getMounts(c="",h={}){return c=ss(c),i(c,h.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(c,h={})=>l.getKeys(c,h),get:(c,h={})=>l.getItem(c,h),set:(c,h,u={})=>l.setItem(c,h,u),has:(c,h={})=>l.hasItem(c,h),del:(c,h={})=>l.removeItem(c,h),remove:(c,h={})=>l.removeItem(c,h)};return l}function yg(s,e,t){return s.watch?s.watch((i,r)=>e(i,t+r)):()=>{}}async function bg(s){typeof s.dispose=="function"&&await bt(s.dispose)}const tk="idb-keyval";var sk=(s={})=>{const e=s.base&&s.base.length>0?`${s.base}:`:"",t=r=>e+r;let i;return s.dbName&&s.storeName&&(i=Im(s.dbName,s.storeName)),{name:tk,options:s,async hasItem(r){return!(typeof await bc(t(r),i)>"u")},async getItem(r){return await bc(t(r),i)??null},setItem(r,n){return _m(t(r),n,i)},removeItem(r){return Nm(t(r),i)},getKeys(){return Am(i)},clear(){return Em(i)}}};const ik="WALLET_CONNECT_V2_INDEXED_DB",rk="keyvaluestorage";let nk=class{constructor(){this.indexedDb=ek({driver:sk({dbName:ik,storeName:rk})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,Sr(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var zl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof _.global<"u"?_.global:typeof self<"u"?self:{},lc={exports:{}};(function(){let s;function e(){}s=e,s.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},s.prototype.setItem=function(t,i){this[t]=String(i)},s.prototype.removeItem=function(t){delete this[t]},s.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(i){t[i]=void 0,delete t[i]})},s.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},s.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof zl<"u"&&zl.localStorage?lc.exports=zl.localStorage:typeof window<"u"&&window.localStorage?lc.exports=window.localStorage:lc.exports=new e})();function ok(s){var e;return[s[0],wi((e=s[1])!=null?e:"")]}let ak=class{constructor(){this.localStorage=lc.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(ok)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return wi(t)}async setItem(e,t){this.localStorage.setItem(e,Sr(t))}async removeItem(e){this.localStorage.removeItem(e)}};const ck="wc_storage_version",vg=1,lk=async(s,e,t)=>{const i=ck,r=await e.getItem(i);if(r&&r>=vg){t(e);return}const n=await s.getKeys();if(!n.length){t(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const l=a.toLowerCase();if(l.includes("wc@")||l.includes("walletconnect")||l.includes("wc_")||l.includes("wallet_connect")){const c=await s.getItem(a);await e.setItem(a,c),o.push(a)}}await e.setItem(i,vg),t(e),hk(s,o)},hk=async(s,e)=>{e.length&&e.forEach(async t=>{await s.removeItem(t)})};let uk=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new ak;this.storage=e;try{const t=new nk;lk(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}};function ea(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function Ig(s){return ea(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const $y="2.23.2";let yo={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${$y}`};class Er extends Error{constructor(e,t={}){var a;const i=(()=>{var l;return t.cause instanceof Er?t.cause.details:(l=t.cause)!=null&&l.message?t.cause.message:t.details})(),r=t.cause instanceof Er&&t.cause.docsPath||t.docsPath,n=(a=yo.getDocsUrl)==null?void 0:a.call(yo,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...yo.version?[`Version: ${yo.version}`]:[]].join(`
13
+ `);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=$y}walk(e){return Py(this,e)}}function Py(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?Py(s.cause,e):e?null:s}class Ty extends Er{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Xn(s,{dir:e,size:t=32}={}){return typeof s=="string"?dk(s,{dir:e,size:t}):pk(s,{dir:e,size:t})}function dk(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new Ty({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function pk(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new Ty({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}class gk extends Er{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class fk extends Er{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function eo(s,{size:e}){if(Ig(s)>e)throw new fk({givenSize:Ig(s),maxSize:e})}function Hh(s,e={}){const{signed:t}=e;e.size&&eo(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function mk(s,e={}){return Number(Hh(s,e))}const wk=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Wh(s,e={}){return typeof s=="number"||typeof s=="bigint"?Oy(s,e):typeof s=="string"?vk(s,e):typeof s=="boolean"?yk(s,e):My(s,e)}function yk(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(eo(t,{size:e.size}),Xn(t,{size:e.size})):t}function My(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=wk[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(eo(i,{size:e.size}),Xn(i,{dir:"right",size:e.size})):i}function Oy(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const l=typeof s=="bigint"?"n":"";throw new gk({max:n?`${n}${l}`:void 0,min:`${o}${l}`,signed:t,size:i,value:`${s}${l}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?Xn(a,{size:i}):a}const bk=new TextEncoder;function vk(s,e={}){const t=bk.encode(s);return My(t,e)}const Ik=new TextEncoder;function Ek(s,e={}){return typeof s=="number"||typeof s=="bigint"?Nk(s,e):typeof s=="boolean"?Ak(s,e):ea(s)?xy(s,e):Dy(s,e)}function Ak(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(eo(t,{size:e.size}),Xn(t,{size:e.size})):t}const ci={zero:48,nine:57,A:65,F:70,a:97,f:102};function Eg(s){if(s>=ci.zero&&s<=ci.nine)return s-ci.zero;if(s>=ci.A&&s<=ci.F)return s-(ci.A-10);if(s>=ci.a&&s<=ci.f)return s-(ci.a-10)}function xy(s,e={}){let t=s;e.size&&(eo(t,{size:e.size}),t=Xn(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const l=Eg(i.charCodeAt(a++)),c=Eg(i.charCodeAt(a++));if(l===void 0||c===void 0)throw new Er(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=l*16+c}return n}function Nk(s,e){const t=Oy(s,e);return xy(t)}function Dy(s,e={}){const t=Ik.encode(s);return typeof e.size=="number"?(eo(t,{size:e.size}),Xn(t,{dir:"right",size:e.size})):t}function Pc(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function _k(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function sl(s,...e){if(!_k(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function yq(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Pc(s.outputLen),Pc(s.blockLen)}function Ag(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ck(s,e){sl(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Ha=BigInt(2**32-1),Ng=BigInt(32);function Sk(s,e=!1){return e?{h:Number(s&Ha),l:Number(s>>Ng&Ha)}:{h:Number(s>>Ng&Ha)|0,l:Number(s&Ha)|0}}function $k(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=Sk(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const Pk=(s,e,t)=>s<<t|e>>>32-t,Tk=(s,e,t)=>e<<t|s>>>32-t,Mk=(s,e,t)=>e<<t-32|s>>>64-t,Ok=(s,e,t)=>s<<t-32|e>>>64-t,tn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function xk(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function bq(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function vq(s,e){return s<<32-e|s>>>e}const _g=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Dk(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Cg(s){for(let e=0;e<s.length;e++)s[e]=Dk(s[e])}function kk(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function ky(s){return typeof s=="string"&&(s=kk(s)),sl(s),s}function Iq(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];sl(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}class jk{clone(){return this._cloneInto()}}function Rk(s){const e=i=>s().update(ky(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Eq(s=32){if(tn&&typeof tn.getRandomValues=="function")return tn.getRandomValues(new Uint8Array(s));if(tn&&typeof tn.randomBytes=="function")return tn.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const jy=[],Ry=[],Ly=[],Lk=BigInt(0),bo=BigInt(1),Uk=BigInt(2),zk=BigInt(7),Fk=BigInt(256),qk=BigInt(113);for(let s=0,e=bo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],jy.push(2*(5*i+t)),Ry.push((s+1)*(s+2)/2%64);let r=Lk;for(let n=0;n<7;n++)e=(e<<bo^(e>>zk)*qk)%Fk,e&Uk&&(r^=bo<<(bo<<BigInt(n))-bo);Ly.push(r)}const[Bk,Hk]=$k(Ly,!0),Sg=(s,e,t)=>t>32?Mk(s,e,t):Pk(s,e,t),$g=(s,e,t)=>t>32?Ok(s,e,t):Tk(s,e,t);function Wk(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,l=(o+2)%10,c=t[l],h=t[l+1],u=Sg(c,h,1)^t[a],d=$g(c,h,1)^t[a+1];for(let p=0;p<50;p+=10)s[o+p]^=u,s[o+p+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Ry[o],l=Sg(r,n,a),c=$g(r,n,a),h=jy[o];r=s[h],n=s[h+1],s[h]=l,s[h+1]=c}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=Bk[i],s[1]^=Hk[i]}t.fill(0)}class zu extends jk{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Pc(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=xk(this.state)}keccak(){_g||Cg(this.state32),Wk(this.state32,this.rounds),_g||Cg(this.state32),this.posOut=0,this.pos=0}update(e){Ag(this);const{blockLen:t,state:i}=this;e=ky(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Ag(this,!1),sl(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Pc(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ck(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:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new zu(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Vk=(s,e,t)=>Rk(()=>new zu(e,s,t)),Kk=Vk(1,136,256/8);function Uy(s,e){const t=e||"hex",i=Kk(ea(s,{strict:!1})?Ek(s):s);return t==="bytes"?i:Wh(i)}class Gk extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const Fl=new Gk(8192);function Yk(s,e){if(Fl.has(`${s}.${e}`))return Fl.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=Uy(Dy(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Fl.set(`${s}.${e}`,n),n}function Qk(s){const e=Uy(`0x${s.substring(4)}`).substring(26);return Yk(`0x${e}`)}async function Zk({hash:s,signature:e}){const t=ea(s)?s:Wh(s),{secp256k1:i}=await Vo(async()=>{const{secp256k1:o}=await import("./secp256k1-OI4v3wvK.js");return{secp256k1:o}},__vite__mapDeps([11,1,2,7,8,9,10,3,4]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:c,s:h,v:u,yParity:d}=e,p=Number(d??u),g=Pg(p);return new i.Signature(Hh(c),Hh(h)).addRecoveryBit(g)}const o=ea(e)?e:Wh(e),a=mk(`0x${o.slice(130)}`),l=Pg(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(l)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Pg(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function Jk({hash:s,signature:e}){return Qk(await Zk({hash:s,signature:e}))}function Xk(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<s.length;c++){const h=s.charAt(c),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=c}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,u=0,d=0;const p=c.length;for(;d!==p&&c[d]===0;)d++,h++;const g=(p-d)*n+1>>>0,f=new Uint8Array(g);for(;d!==p;){let m=c[d],b=0;for(let I=g-1;(m!==0||b<u)&&I!==-1;I--,b++)m+=256*f[I]>>>0,f[I]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");u=b,d++}let y=g-u;for(;y!==g&&f[y]===0;)y++;let w=i.repeat(h);for(;y<g;++y)w+=s.charAt(f[y]);return w}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;c[h]===i;)u++,h++;const p=(c.length-h)*r+1>>>0,g=new Uint8Array(p);for(;h<c.length;){const m=c.charCodeAt(h);if(m>255)return;let b=e[m];if(b===255)return;let I=0;for(let N=p-1;(b!==0||I<d)&&N!==-1;N--,I++)b+=t*g[N]>>>0,g[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=I,h++}let f=p-d;for(;f!==p&&g[f]===0;)f++;const y=new Uint8Array(u+(p-f));let w=u;for(;f!==p;)y[w++]=g[f++];return y}function l(c){const h=a(c);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:l}}var e3="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const zy=Xk(e3);var t3={};const s3=":";function xn(s){const[e,t]=s.split(s3);return{namespace:e,reference:t}}function Fy(s,e){return s.includes(":")?[s]:e.chains||[]}const i3="ReactNative",ms={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},r3="js";function Tc(){return typeof _.process<"u"&&typeof _.process.versions<"u"&&typeof _.process.versions.node<"u"}function Yi(){return!Vi()&&!!zc()&&navigator.product===i3}function n3(){return Yi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="android"}function o3(){return Yi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="ios"}function Ia(){return!Tc()&&!!zc()&&!!Vi()}function Ea(){return Yi()?ms.reactNative:Tc()?ms.node:Ia()?ms.browser:ms.unknown}function Tg(){var s;try{return Yi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Application)<"u"?(s=_.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function a3(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function qy(){return Tm()||{name:"",description:"",url:"",icons:[""]}}function c3(){if(Ea()===ms.reactNative&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"){const{OS:t,Version:i}=_.global.Platform;return[t,i].join("-")}const s=Sm();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function l3(){var s;const e=Ea();return e===ms.browser?[e,((s=Mm())==null?void 0:s.host)||"unknown"].join(":"):e}function By(s,e,t){const i=c3(),r=l3();return[[s,e].join("-"),[r3,t].join("-"),i,r].join("/")}function h3({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:l}){const c=t.split("?"),h=By(s,e,i),u={auth:r,ua:h,projectId:n,useOnCloseEvent:o,packageName:l||void 0,bundleId:a||void 0},d=a3(c[1]||"",u);return c[0]+"?"+d}function pr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Vh(s){return Object.fromEntries(s.entries())}function Kh(s){return new Map(Object.entries(s))}function or(s=E.FIVE_MINUTES,e){const t=E.toMiliseconds(s||E.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,l)=>{if(o)return a(o);n=setTimeout(()=>{const c=new Error(e);o=Promise.reject(c),l(c)},t),i=a,r=l})}}function Li(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function Hy(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.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: ${s}`)}function u3(s){return Hy("topic",s)}function d3(s){return Hy("id",s)}function Wy(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function dt(s,e){return E.fromMiliseconds(Date.now()+E.toMiliseconds(s))}function Ti(s){return Date.now()>=E.toMiliseconds(s)}function Ee(s,e){return`${s}${e?`:${e}`:""}`}function hc(s=[],e=[]){return[...new Set([...s,...e])]}async function p3({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=g3(n,s,e),a=Ea();if(a===ms.browser){if(!((i=Vi())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}f3(o)}else a===ms.reactNative&&typeof(_.global==null?void 0:_.global.Linking)<"u"&&await _.global.Linking.openURL(o)}catch(r){console.error(r)}}function g3(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${b3(i,!0)}`}else r=`${r}/wc?${i}`;return r}function f3(s){let e="_self";y3()?e="_top":(w3()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function m3(s,e){let t="";try{if(Ia()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Mg(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Og(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function Fu(){return typeof _.process<"u"&&t3.IS_VITEST==="true"}function w3(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function y3(){try{return window.self!==window.top}catch{return!1}}function b3(s,e=!1){const t=_.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Vy(s){return _.Buffer.from(s,"base64").toString("utf-8")}function v3(s){return new Promise(e=>setTimeout(e,s))}function ta(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function I3(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function il(s,...e){if(!I3(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function qu(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ta(s.outputLen),ta(s.blockLen)}function zn(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ky(s,e){il(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Wa=BigInt(2**32-1),xg=BigInt(32);function E3(s,e=!1){return e?{h:Number(s&Wa),l:Number(s>>xg&Wa)}:{h:Number(s>>xg&Wa)|0,l:Number(s&Wa)|0}}function A3(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=E3(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const N3=(s,e,t)=>s<<t|e>>>32-t,_3=(s,e,t)=>e<<t|s>>>32-t,C3=(s,e,t)=>e<<t-32|s>>>64-t,S3=(s,e,t)=>s<<t-32|e>>>64-t,sn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function $3(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function ql(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Gs(s,e){return s<<32-e|s>>>e}const Dg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function P3(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function kg(s){for(let e=0;e<s.length;e++)s[e]=P3(s[e])}function T3(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Fn(s){return typeof s=="string"&&(s=T3(s)),il(s),s}let Bu=class{clone(){return this._cloneInto()}};function Gy(s){const e=i=>s().update(Fn(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Aa(s=32){if(sn&&typeof sn.getRandomValues=="function")return sn.getRandomValues(new Uint8Array(s));if(sn&&typeof sn.randomBytes=="function")return sn.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Yy=[],Qy=[],Zy=[],M3=BigInt(0),vo=BigInt(1),O3=BigInt(2),x3=BigInt(7),D3=BigInt(256),k3=BigInt(113);for(let s=0,e=vo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Yy.push(2*(5*i+t)),Qy.push((s+1)*(s+2)/2%64);let r=M3;for(let n=0;n<7;n++)e=(e<<vo^(e>>x3)*k3)%D3,e&O3&&(r^=vo<<(vo<<BigInt(n))-vo);Zy.push(r)}const[j3,R3]=A3(Zy,!0),jg=(s,e,t)=>t>32?C3(s,e,t):N3(s,e,t),Rg=(s,e,t)=>t>32?S3(s,e,t):_3(s,e,t);function L3(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,l=(o+2)%10,c=t[l],h=t[l+1],u=jg(c,h,1)^t[a],d=Rg(c,h,1)^t[a+1];for(let p=0;p<50;p+=10)s[o+p]^=u,s[o+p+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Qy[o],l=jg(r,n,a),c=Rg(r,n,a),h=Yy[o];r=s[h],n=s[h+1],s[h]=l,s[h+1]=c}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=j3[i],s[1]^=R3[i]}t.fill(0)}let U3=class Jy extends Bu{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ta(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=$3(this.state)}keccak(){Dg||kg(this.state32),L3(this.state32,this.rounds),Dg||kg(this.state32),this.posOut=0,this.pos=0}update(e){zn(this);const{blockLen:t,state:i}=this;e=Fn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){zn(this,!1),il(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ta(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ky(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:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Jy(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const z3=(s,e,t)=>Gy(()=>new U3(e,s,t)),F3=z3(1,136,256/8),q3="https://rpc.walletconnect.org/v1";function Xy(s){const e=`Ethereum Signed Message:
14
14
  ${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+_.Buffer.from(F3(t)).toString("hex")}async function B3(s,e,t,i,r,n){switch(t.t){case"eip191":return await H3(s,e,t.s);case"eip1271":return await W3(s,e,t.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function H3(s,e,t){return(await Jk({hash:Xy(e),signature:t})).toLowerCase()===s.toLowerCase()}async function W3(s,e,t,i,r,n){const o=xn(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",l="0000000000000000000000000000000000000000000000000000000000000040",c="0000000000000000000000000000000000000000000000000000000000000041",h=t.substring(2),u=Xy(e).substring(2),d=a+u+l+c+h,p=await fetch(`${n||q3}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:V3(),jsonrpc:"2.0",method:"eth_call",params:[{to:s,data:d},"latest"]})}),{result:g}=await p.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function V3(){return Date.now()+Math.floor(Math.random()*1e3)}function K3(s){const e=atob(s),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);const i=t[0];if(i===0)throw new Error("No signatures found");const r=1+i*64;if(t.length<r)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const n=_.Buffer.from(s,"base64").slice(1,65);return zy.encode(n)}var G3=Object.defineProperty,Y3=Object.defineProperties,Q3=Object.getOwnPropertyDescriptors,Lg=Object.getOwnPropertySymbols,Z3=Object.prototype.hasOwnProperty,J3=Object.prototype.propertyIsEnumerable,Ug=(s,e,t)=>e in s?G3(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,X3=(s,e)=>{for(var t in e||(e={}))Z3.call(e,t)&&Ug(s,t,e[t]);if(Lg)for(var t of Lg(e))J3.call(e,t)&&Ug(s,t,e[t]);return s},e4=(s,e)=>Y3(s,Q3(e));const t4="did:pkh:",Hu=s=>s==null?void 0:s.split(":"),s4=s=>{const e=s&&Hu(s);if(e)return s.includes(t4)?e[3]:e[1]},Gh=s=>{const e=s&&Hu(s);if(e)return e[2]+":"+e[3]},Mc=s=>{const e=s&&Hu(s);if(e)return e.pop()};async function zg(s){const{cacao:e,projectId:t}=s,{s:i,p:r}=e,n=eb(r,r.iss),o=Mc(r.iss);return await B3(o,n,i,Gh(r.iss),t)}const eb=(s,e)=>{const t=`${s.domain} wants you to sign in with your Ethereum account:`,i=Mc(e);if(!s.aud&&!s.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=s.statement||void 0;const n=`URI: ${s.aud||s.uri}`,o=`Version: ${s.version}`,a=`Chain ID: ${s4(e)}`,l=`Nonce: ${s.nonce}`,c=`Issued At: ${s.iat}`,h=s.exp?`Expiration Time: ${s.exp}`:void 0,u=s.nbf?`Not Before: ${s.nbf}`:void 0,d=s.requestId?`Request ID: ${s.requestId}`:void 0,p=s.resources?`Resources:${s.resources.map(f=>`
15
15
  - ${f}`).join("")}`:void 0,g=uc(s.resources);if(g){const f=sa(g);r=u4(r,f)}return[t,i,"",r,"",n,o,a,l,c,h,u,d,p].filter(f=>f!=null).join(`
16
- `)};function i4(s){return _.Buffer.from(JSON.stringify(s)).toString("base64")}function r4(s){return JSON.parse(_.Buffer.from(s,"base64").toString("utf-8"))}function Ar(s){if(!s)throw new Error("No recap provided, value is undefined");if(!s.att)throw new Error("No `att` property found");const e=Object.keys(s.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=s.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(r=>{const n=i[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function n4(s,e,t,i={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[s]:o4(e,t,i)}}}function o4(s,e,t={}){e=e==null?void 0:e.sort((r,n)=>r.localeCompare(n));const i=e.map(r=>({[`${s}/${r}`]:[t]}));return Object.assign({},...i)}function tb(s){return Ar(s),`urn:recap:${i4(s).replace(/=/g,"")}`}function sa(s){const e=r4(s.replace("urn:recap:",""));return Ar(e),e}function a4(s,e,t){const i=n4(s,e,t);return tb(i)}function c4(s){return s&&s.includes("urn:recap:")}function l4(s,e){const t=sa(s),i=sa(e),r=h4(t,i);return tb(r)}function h4(s,e){Ar(s),Ar(e);const t=Object.keys(s.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),i={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=s.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,l)=>a.localeCompare(l)).forEach(a=>{var l,c;i.att[r]=e4(X3({},i.att[r]),{[a]:((l=s.att[r])==null?void 0:l[a])||((c=e.att[r])==null?void 0:c[a])})})}),i}function u4(s="",e){Ar(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(s.includes(t))return s;const i=[];let r=0;Object.keys(e.att).forEach(a=>{const l=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));l.sort((u,d)=>u.action.localeCompare(d.action));const c={};l.forEach(u=>{c[u.ability]||(c[u.ability]=[]),c[u.ability].push(u.action)});const h=Object.keys(c).map(u=>(r++,`(${r}) '${u}': '${c[u].join("', '")}' for '${a}'.`));i.push(h.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${s?s+" ":""}${o}`}function Fg(s){var e;const t=sa(s);Ar(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function qg(s){const e=sa(s);Ar(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(r=>{var n;(n=r==null?void 0:r[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function uc(s){if(!s)return;const e=s==null?void 0:s[s.length-1];return c4(e)?e:void 0}function Bl(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function sb(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ps(s,...e){if(!sb(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Bg(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function d4(s,e){ps(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Hg(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}const Fi=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),p4=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),g4=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!g4)throw new Error("Non little-endian hardware is not supported");function f4(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Yh(s){if(typeof s=="string")s=f4(s);else if(sb(s))s=Qh(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function m4(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function w4(s,e){if(s.length!==e.length)return!1;let t=0;for(let i=0;i<s.length;i++)t|=s[i]^e[i];return t===0}const y4=(s,e)=>{function t(i,...r){if(ps(i),s.nonceLength!==void 0){const c=r[0];if(!c)throw new Error("nonce / iv required");s.varSizeNonce?ps(c):ps(c,s.nonceLength)}const n=s.tagLength;n&&r[1]!==void 0&&ps(r[1]);const o=e(i,...r),a=(c,h)=>{if(h!==void 0){if(c!==2)throw new Error("cipher output not supported");ps(h)}};let l=!1;return{encrypt(c,h){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ps(c),a(o.encrypt.length,h),o.encrypt(c,h)},decrypt(c,h){if(ps(c),n&&c.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,h),o.decrypt(c,h)}}}return Object.assign(t,s),t};function Wg(s,e,t=!0){if(e===void 0)return new Uint8Array(s);if(e.length!==s)throw new Error("invalid output length, expected "+s+", got: "+e.length);if(t&&!b4(e))throw new Error("invalid output, must be aligned");return e}function Vg(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);s.setUint32(e+4,o,i),s.setUint32(e+0,a,i)}function b4(s){return s.byteOffset%4===0}function Qh(s){return Uint8Array.from(s)}function qn(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}const ib=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),v4=ib("expand 16-byte k"),I4=ib("expand 32-byte k"),E4=Fi(v4),A4=Fi(I4);function ge(s,e){return s<<e|s>>>32-e}function Zh(s){return s.byteOffset%4===0}const Va=64,N4=16,rb=2**32-1,Kg=new Uint32Array;function _4(s,e,t,i,r,n,o,a){const l=r.length,c=new Uint8Array(Va),h=Fi(c),u=Zh(r)&&Zh(n),d=u?Fi(r):Kg,p=u?Fi(n):Kg;for(let g=0;g<l;o++){if(s(e,t,i,h,o,a),o>=rb)throw new Error("arx: counter overflow");const f=Math.min(Va,l-g);if(u&&f===Va){const y=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,m;w<N4;w++)m=y+w,p[m]=d[m]^h[w];g+=Va;continue}for(let y=0,w;y<f;y++)w=g+y,n[w]=r[w]^c[y];g+=f}}function C4(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=m4({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return Bl(r),Bl(o),Hg(n),Hg(t),(a,l,c,h,u=0)=>{ps(a),ps(l),ps(c);const d=c.length;if(h===void 0&&(h=new Uint8Array(d)),ps(h),Bl(u),u<0||u>=rb)throw new Error("arx: counter overflow");if(h.length<d)throw new Error(`arx: output (${h.length}) is shorter than data (${d})`);const p=[];let g=a.length,f,y;if(g===32)p.push(f=Qh(a)),y=A4;else if(g===16&&t)f=new Uint8Array(32),f.set(a),f.set(a,16),y=E4,p.push(f);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Zh(l)||p.push(l=Qh(l));const w=Fi(f);if(i){if(l.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(y,w,Fi(l.subarray(0,16)),w),l=l.subarray(16)}const m=16-r;if(m!==l.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const I=new Uint8Array(12);I.set(l,n?0:12-l.length),l=I,p.push(l)}const b=Fi(l);return _4(s,y,w,b,c,h,u,o),qn(...p),h}}const $t=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let S4=class{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=Yh(e),ps(e,32);const t=$t(e,0),i=$t(e,2),r=$t(e,4),n=$t(e,6),o=$t(e,8),a=$t(e,10),l=$t(e,12),c=$t(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|r<<6)&7939,this.r[3]=(r>>>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|l<<5)&8065,this.r[8]=(l>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let h=0;h<8;h++)this.pad[h]=$t(e,16+2*h)}process(e,t,i=!1){const r=i?0:2048,{h:n,r:o}=this,a=o[0],l=o[1],c=o[2],h=o[3],u=o[4],d=o[5],p=o[6],g=o[7],f=o[8],y=o[9],w=$t(e,t+0),m=$t(e,t+2),b=$t(e,t+4),I=$t(e,t+6),N=$t(e,t+8),$=$t(e,t+10),P=$t(e,t+12),O=$t(e,t+14);let C=n[0]+(w&8191),T=n[1]+((w>>>13|m<<3)&8191),S=n[2]+((m>>>10|b<<6)&8191),R=n[3]+((b>>>7|I<<9)&8191),L=n[4]+((I>>>4|N<<12)&8191),q=n[5]+(N>>>1&8191),B=n[6]+((N>>>14|$<<2)&8191),U=n[7]+(($>>>11|P<<5)&8191),H=n[8]+((P>>>8|O<<8)&8191),W=n[9]+(O>>>5|r),A=0,z=A+C*a+T*(5*y)+S*(5*f)+R*(5*g)+L*(5*p);A=z>>>13,z&=8191,z+=q*(5*d)+B*(5*u)+U*(5*h)+H*(5*c)+W*(5*l),A+=z>>>13,z&=8191;let Y=A+C*l+T*a+S*(5*y)+R*(5*f)+L*(5*g);A=Y>>>13,Y&=8191,Y+=q*(5*p)+B*(5*d)+U*(5*u)+H*(5*h)+W*(5*c),A+=Y>>>13,Y&=8191;let K=A+C*c+T*l+S*a+R*(5*y)+L*(5*f);A=K>>>13,K&=8191,K+=q*(5*g)+B*(5*p)+U*(5*d)+H*(5*u)+W*(5*h),A+=K>>>13,K&=8191;let be=A+C*h+T*c+S*l+R*a+L*(5*y);A=be>>>13,be&=8191,be+=q*(5*f)+B*(5*g)+U*(5*p)+H*(5*d)+W*(5*u),A+=be>>>13,be&=8191;let oe=A+C*u+T*h+S*c+R*l+L*a;A=oe>>>13,oe&=8191,oe+=q*(5*y)+B*(5*f)+U*(5*g)+H*(5*p)+W*(5*d),A+=oe>>>13,oe&=8191;let Oe=A+C*d+T*u+S*h+R*c+L*l;A=Oe>>>13,Oe&=8191,Oe+=q*a+B*(5*y)+U*(5*f)+H*(5*g)+W*(5*p),A+=Oe>>>13,Oe&=8191;let lt=A+C*p+T*d+S*u+R*h+L*c;A=lt>>>13,lt&=8191,lt+=q*l+B*a+U*(5*y)+H*(5*f)+W*(5*g),A+=lt>>>13,lt&=8191;let Be=A+C*g+T*p+S*d+R*u+L*h;A=Be>>>13,Be&=8191,Be+=q*c+B*l+U*a+H*(5*y)+W*(5*f),A+=Be>>>13,Be&=8191;let Qe=A+C*f+T*g+S*p+R*d+L*u;A=Qe>>>13,Qe&=8191,Qe+=q*h+B*c+U*l+H*a+W*(5*y),A+=Qe>>>13,Qe&=8191;let He=A+C*y+T*f+S*g+R*p+L*d;A=He>>>13,He&=8191,He+=q*u+B*h+U*c+H*l+W*a,A+=He>>>13,He&=8191,A=(A<<2)+A|0,A=A+z|0,z=A&8191,A=A>>>13,Y+=A,n[0]=z,n[1]=Y,n[2]=K,n[3]=be,n[4]=oe,n[5]=Oe,n[6]=lt,n[7]=Be,n[8]=Qe,n[9]=He}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,i[0]=e[0]+5,r=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+r,r=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;qn(i)}update(e){Bg(this);const{buffer:t,blockLen:i}=this;e=Yh(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){for(;i<=r-n;n+=i)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){qn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Bg(this),d4(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}};function $4(s){const e=(i,r)=>s(r).update(Yh(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const P4=$4(s=>new S4(s));function T4(s,e,t,i,r,n=20){let o=s[0],a=s[1],l=s[2],c=s[3],h=e[0],u=e[1],d=e[2],p=e[3],g=e[4],f=e[5],y=e[6],w=e[7],m=r,b=t[0],I=t[1],N=t[2],$=o,P=a,O=l,C=c,T=h,S=u,R=d,L=p,q=g,B=f,U=y,H=w,W=m,A=b,z=I,Y=N;for(let be=0;be<n;be+=2)$=$+T|0,W=ge(W^$,16),q=q+W|0,T=ge(T^q,12),$=$+T|0,W=ge(W^$,8),q=q+W|0,T=ge(T^q,7),P=P+S|0,A=ge(A^P,16),B=B+A|0,S=ge(S^B,12),P=P+S|0,A=ge(A^P,8),B=B+A|0,S=ge(S^B,7),O=O+R|0,z=ge(z^O,16),U=U+z|0,R=ge(R^U,12),O=O+R|0,z=ge(z^O,8),U=U+z|0,R=ge(R^U,7),C=C+L|0,Y=ge(Y^C,16),H=H+Y|0,L=ge(L^H,12),C=C+L|0,Y=ge(Y^C,8),H=H+Y|0,L=ge(L^H,7),$=$+S|0,Y=ge(Y^$,16),U=U+Y|0,S=ge(S^U,12),$=$+S|0,Y=ge(Y^$,8),U=U+Y|0,S=ge(S^U,7),P=P+R|0,W=ge(W^P,16),H=H+W|0,R=ge(R^H,12),P=P+R|0,W=ge(W^P,8),H=H+W|0,R=ge(R^H,7),O=O+L|0,A=ge(A^O,16),q=q+A|0,L=ge(L^q,12),O=O+L|0,A=ge(A^O,8),q=q+A|0,L=ge(L^q,7),C=C+T|0,z=ge(z^C,16),B=B+z|0,T=ge(T^B,12),C=C+T|0,z=ge(z^C,8),B=B+z|0,T=ge(T^B,7);let K=0;i[K++]=o+$|0,i[K++]=a+P|0,i[K++]=l+O|0,i[K++]=c+C|0,i[K++]=h+T|0,i[K++]=u+S|0,i[K++]=d+R|0,i[K++]=p+L|0,i[K++]=g+q|0,i[K++]=f+B|0,i[K++]=y+U|0,i[K++]=w+H|0,i[K++]=m+W|0,i[K++]=b+A|0,i[K++]=I+z|0,i[K++]=N+Y|0}const M4=C4(T4,{counterRight:!1,counterLength:4,allowShortKeys:!1}),O4=new Uint8Array(16),Gg=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(O4.subarray(t))},x4=new Uint8Array(32);function Yg(s,e,t,i,r){const n=s(e,t,x4),o=P4.create(n);r&&Gg(o,r),Gg(o,i);const a=new Uint8Array(16),l=p4(a);Vg(l,0,BigInt(r?r.length:0),!0),Vg(l,8,BigInt(i.length),!0),o.update(a);const c=o.digest();return qn(n,a),c}const D4=s=>(e,t,i)=>({encrypt(r,n){const o=r.length;n=Wg(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);s(e,t,a,a,1);const l=Yg(s,e,t,a,i);return n.set(l,o),qn(l),n},decrypt(r,n){n=Wg(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),l=Yg(s,e,t,o,i);if(!w4(a,l))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),qn(l),n}}),nb=y4({blockSize:64,nonceLength:12,tagLength:16},D4(M4));let ob=class extends Bu{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,qu(e);const i=Fn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return zn(this),this.iHash.update(e),this}digestInto(e){zn(this),il(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:i,finished:r,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Wu=(s,e,t)=>new ob(s,e).update(t).digest();Wu.create=(s,e)=>new ob(s,e);function k4(s,e,t){return qu(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Wu(s,Fn(t),Fn(e))}const Hl=new Uint8Array([0]),Qg=new Uint8Array;function j4(s,e,t,i=32){if(qu(s),ta(i),i>255*s.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/s.outputLen);t===void 0&&(t=Qg);const n=new Uint8Array(r*s.outputLen),o=Wu.create(s,e),a=o._cloneInto(),l=new Uint8Array(o.outputLen);for(let c=0;c<r;c++)Hl[0]=c+1,a.update(c===0?Qg:l).update(t).update(Hl).digestInto(l),n.set(l,s.outputLen*c),o._cloneInto(a);return o.destroy(),a.destroy(),l.fill(0),Hl.fill(0),n.slice(0,i)}const R4=(s,e,t,i,r)=>j4(s,k4(s,e,t),i,r);function L4(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),l=i?4:0,c=i?0:4;s.setUint32(e+l,o,i),s.setUint32(e+c,a,i)}function U4(s,e,t){return s&e^~s&t}function z4(s,e,t){return s&e^s&t^e&t}class F4 extends Bu{constructor(e,t,i,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ql(this.buffer)}update(e){zn(this);const{view:t,buffer:i,blockLen:r}=this;e=Fn(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const l=ql(e);for(;r<=n-o;o+=r)this.process(l,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){zn(this),Ky(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(i,0),o=0);for(let u=o;u<r;u++)t[u]=0;L4(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=ql(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=l/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)a.setUint32(4*u,h[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:r,finished:n,destroyed:o,pos:a}=this;return e.length=r,e.pos=a,e.finished=n,e.destroyed=o,r%t&&e.buffer.set(i),e}}const q4=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]),Ai=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ni=new Uint32Array(64);let B4=class extends F4{constructor(){super(64,32,8,!1),this.A=Ai[0]|0,this.B=Ai[1]|0,this.C=Ai[2]|0,this.D=Ai[3]|0,this.E=Ai[4]|0,this.F=Ai[5]|0,this.G=Ai[6]|0,this.H=Ai[7]|0}get(){const{A:e,B:t,C:i,D:r,E:n,F:o,G:a,H:l}=this;return[e,t,i,r,n,o,a,l]}set(e,t,i,r,n,o,a,l){this.A=e|0,this.B=t|0,this.C=i|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=l|0}process(e,t){for(let u=0;u<16;u++,t+=4)Ni[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const d=Ni[u-15],p=Ni[u-2],g=Gs(d,7)^Gs(d,18)^d>>>3,f=Gs(p,17)^Gs(p,19)^p>>>10;Ni[u]=f+Ni[u-7]+g+Ni[u-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:l,G:c,H:h}=this;for(let u=0;u<64;u++){const d=Gs(a,6)^Gs(a,11)^Gs(a,25),p=h+d+U4(a,l,c)+q4[u]+Ni[u]|0,g=(Gs(i,2)^Gs(i,13)^Gs(i,22))+z4(i,r,n)|0;h=c,c=l,l=a,a=o+p|0,o=n,n=r,r=i,i=p+g|0}i=i+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,l=l+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(i,r,n,o,a,l,c,h)}roundClean(){Ni.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const rl=Gy(()=>new B4);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ab=BigInt(0);function Vu(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function cb(s){if(!Vu(s))throw new Error("Uint8Array expected")}const H4=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function W4(s){cb(s);let e="";for(let t=0;t<s.length;t++)e+=H4[s[t]];return e}function V4(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?ab:BigInt("0x"+s)}const li={_0:48,_9:57,A:65,F:70,a:97,f:102};function Zg(s){if(s>=li._0&&s<=li._9)return s-li._0;if(s>=li.A&&s<=li.F)return s-(li.A-10);if(s>=li.a&&s<=li.f)return s-(li.a-10)}function lb(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=Zg(s.charCodeAt(n)),a=Zg(s.charCodeAt(n+1));if(o===void 0||a===void 0){const l=s[n]+s[n+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+n)}i[r]=o*16+a}return i}function Jg(s){return cb(s),V4(W4(Uint8Array.from(s).reverse()))}function K4(s,e){return lb(s.toString(16).padStart(e*2,"0"))}function G4(s,e){return K4(s,e).reverse()}function Xg(s,e,t){let i;if(typeof e=="string")try{i=lb(e)}catch(n){throw new Error(s+" must be hex string or Uint8Array, cause: "+n)}else if(Vu(e))i=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");const r=i.length;if(typeof t=="number"&&r!==t)throw new Error(s+" of length "+t+" expected, got "+r);return i}const Wl=s=>typeof s=="bigint"&&ab<=s;function Y4(s,e,t){return Wl(s)&&Wl(e)&&Wl(t)&&e<=s&&s<t}function ef(s,e,t,i){if(!Y4(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const Q4={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||Vu(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function Z4(s,e,t={}){const i=(r,n,o)=>{const a=Q4[n];if(typeof a!="function")throw new Error("invalid validator function");const l=s[r];if(!(o&&l===void 0)&&!a(l,s))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+l)};for(const[r,n]of Object.entries(e))i(r,n,!1);for(const[r,n]of Object.entries(t))i(r,n,!0);return s}const $n=BigInt(0),Ka=BigInt(1);function hb(s,e){const t=s%e;return t>=$n?t:e+t}function J4(s,e,t){if(e<$n)throw new Error("invalid exponent, negatives unsupported");if(t<=$n)throw new Error("invalid modulus");if(t===Ka)return $n;let i=Ka;for(;e>$n;)e&Ka&&(i=i*s%t),s=s*s%t,e>>=Ka;return i}function zs(s,e,t){let i=s;for(;e-- >$n;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const rn=BigInt(0),Vl=BigInt(1);function X4(s){return Z4(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function ej(s){const e=X4(s),{P:t}=e,i=m=>hb(m,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),l=e.powPminus2||(m=>J4(m,t-BigInt(2),t));function c(m,b,I){const N=i(m*(b-I));return b=i(b-N),I=i(I+N),[b,I]}const h=(e.a-BigInt(2))/BigInt(4);function u(m,b){ef("u",m,rn,t),ef("scalar",b,rn,t);const I=b,N=m;let $=Vl,P=rn,O=m,C=Vl,T=rn,S;for(let L=BigInt(r-1);L>=rn;L--){const q=I>>L&Vl;T^=q,S=c(T,$,O),$=S[0],O=S[1],S=c(T,P,C),P=S[0],C=S[1],T=q;const B=$+P,U=i(B*B),H=$-P,W=i(H*H),A=U-W,z=O+C,Y=O-C,K=i(Y*B),be=i(z*H),oe=K+be,Oe=K-be;O=i(oe*oe),C=i(N*i(Oe*Oe)),$=i(U*W),P=i(A*(U+i(h*A)))}S=c(T,$,O),$=S[0],O=S[1],S=c(T,P,C),P=S[0],C=S[1];const R=l(P);return i($*R)}function d(m){return G4(i(m),n)}function p(m){const b=Xg("u coordinate",m,n);return o===32&&(b[31]&=127),Jg(b)}function g(m){const b=Xg("scalar",m),I=b.length;if(I!==n&&I!==o){let N=""+n+" or "+o;throw new Error("invalid scalar, expected "+N+" bytes, got "+I)}return Jg(a(b))}function f(m,b){const I=p(b),N=g(m),$=u(I,N);if($===rn)throw new Error("invalid private or public key received");return d($)}const y=d(e.Gu);function w(m){return f(m,y)}return{scalarMult:f,scalarMultBase:w,getSharedSecret:(m,b)=>f(m,b),getPublicKey:m=>w(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:y}}const Jh=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const tj=BigInt(1),tf=BigInt(2),sj=BigInt(3),ij=BigInt(5);BigInt(8);function rj(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=Jh,o=s*s%n*s%n,a=zs(o,tf,n)*o%n,l=zs(a,tj,n)*s%n,c=zs(l,ij,n)*l%n,h=zs(c,e,n)*c%n,u=zs(h,t,n)*h%n,d=zs(u,i,n)*u%n,p=zs(d,r,n)*d%n,g=zs(p,r,n)*d%n,f=zs(g,e,n)*c%n;return{pow_p_5_8:zs(f,tf,n)*s%n,b2:o}}function nj(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const Xh=ej({P:Jh,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=Jh,{pow_p_5_8:t,b2:i}=rj(s);return hb(zs(t,sj,e)*i,e)},adjustScalarBytes:nj,randomBytes:Aa}),ub="base10",Ht="base16",Ui="base64pad",Io="base64url",Na="utf8",db=0,mi=1,_a=2,oj=0,sf=1,Uo=12,Ku=32;function aj(){const s=Xh.utils.randomPrivateKey(),e=Xh.getPublicKey(s);return{privateKey:Ae(s,Ht),publicKey:Ae(e,Ht)}}function eu(){const s=Aa(Ku);return Ae(s,Ht)}function cj(s,e){const t=Xh.getSharedSecret(Ge(s,Ht),Ge(e,Ht)),i=R4(rl,t,void 0,void 0,Ku);return Ae(i,Ht)}function dc(s){const e=rl(Ge(s,Ht));return Ae(e,Ht)}function Xs(s){const e=rl(Ge(s,Na));return Ae(e,Ht)}function pb(s){return Ge(`${s}`,ub)}function Nr(s){return Number(Ae(s,ub))}function lj(s){const e=pb(typeof s.type<"u"?s.type:db);if(Nr(e)===mi&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?Ge(s.senderPublicKey,Ht):void 0,i=typeof s.iv<"u"?Ge(s.iv,Ht):Aa(Uo),r=Ge(s.symKey,Ht),n=nb(r,i).encrypt(Ge(s.message,Na));return gb({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function hj(s){const e=Ge(s.symKey,Ht),{sealed:t,iv:i}=ia(s),r=nb(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return Ae(r,Na)}function uj(s,e){const t=pb(_a),i=Aa(Uo),r=Ge(s,Na);return gb({type:t,sealed:r,iv:i,encoding:e})}function dj(s,e){const{sealed:t}=ia({encoded:s,encoding:e});return Ae(t,Na)}function gb(s){const{encoding:e=Ui}=s;if(Nr(s.type)===_a)return Ae(Mn([s.type,s.sealed]),e);if(Nr(s.type)===mi){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ae(Mn([s.type,s.senderPublicKey,s.iv,s.sealed]),e)}return Ae(Mn([s.type,s.iv,s.sealed]),e)}function ia(s){const{encoded:e,encoding:t=Ui}=s,i=Ge(e,t),r=i.slice(oj,sf),n=sf;if(Nr(r)===mi){const c=n+Ku,h=c+Uo,u=i.slice(n,c),d=i.slice(c,h),p=i.slice(h);return{type:r,sealed:p,iv:d,senderPublicKey:u}}if(Nr(r)===_a){const c=i.slice(n),h=Aa(Uo);return{type:r,sealed:c,iv:h}}const o=n+Uo,a=i.slice(n,o),l=i.slice(o);return{type:r,sealed:l,iv:a}}function pj(s,e){const t=ia({encoded:s,encoding:e==null?void 0:e.encoding});return fb({type:Nr(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Ae(t.senderPublicKey,Ht):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function fb(s){const e=(s==null?void 0:s.type)||db;if(e===mi){if(typeof(s==null?void 0:s.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(s==null?void 0:s.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:s==null?void 0:s.senderPublicKey,receiverPublicKey:s==null?void 0:s.receiverPublicKey}}function rf(s){return s.type===mi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function nf(s){return s.type===_a}function gj(s){return new Zm.ec("p256").keyFromPublic({x:_.Buffer.from(s.x,"base64").toString("hex"),y:_.Buffer.from(s.y,"base64").toString("hex")},"hex")}function fj(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function mj(s){return _.Buffer.from(fj(s),"base64")}function wj(s,e){const[t,i,r]=s.split("."),n=mj(r);if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32).toString("hex"),a=n.slice(32,64).toString("hex"),l=`${t}.${i}`,c=rl(l),h=gj(e),u=Ae(c,Ht);if(!h.verify(u,{r:o,s:a}))throw new Error("Invalid signature");return jn(s).payload}const yj="irn";function Oc(s){return(s==null?void 0:s.relay)||{protocol:yj}}function Oo(s){const e=$m[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function bj(s,e="-"){const t={},i="relay"+e;return Object.keys(s).forEach(r=>{if(r.startsWith(i)){const n=r.replace(i,""),o=s[r];t[n]=o}}),t}function of(s){if(!s.includes("wc:")){const c=Vy(s);c!=null&&c.includes("wc:")&&(s=c)}s=s.includes("wc://")?s.replace("wc://",""):s,s=s.includes("wc:")?s.replace("wc:",""):s;const e=s.indexOf(":"),t=s.indexOf("?")!==-1?s.indexOf("?"):void 0,i=s.substring(0,e),r=s.substring(e+1,t).split("@"),n=typeof t<"u"?s.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((c,h)=>{a[h]=c});const l=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:vj(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:bj(a),methods:l,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function vj(s){return s.startsWith("//")?s.substring(2):s}function Ij(s,e="-"){const t="relay",i={};return Object.keys(s).forEach(r=>{const n=r,o=t+e+n;s[n]&&(i[o]=s[n])}),i}function af(s){const e=new URLSearchParams,t=Ij(s.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",s.symKey),s.expiryTimestamp&&e.set("expiryTimestamp",s.expiryTimestamp.toString()),s.methods&&e.set("methods",s.methods.join(","));const i=e.toString();return`${s.protocol}:${s.topic}@${s.version}?${i}`}function Ga(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function to(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function Ej(s){const e=[];return Object.values(s).forEach(t=>{e.push(...to(t.accounts))}),e}function Aj(s,e){const t=[];return Object.values(s).forEach(i=>{to(i.accounts).includes(e)&&t.push(...i.methods)}),t}function Nj(s,e){const t=[];return Object.values(s).forEach(i=>{to(i.accounts).includes(e)&&t.push(...i.events)}),t}function Gu(s){return s.includes(":")}function xo(s){return Gu(s)?s.split(":")[0]:s}function _j(s){const e={};return s==null||s.forEach(t=>{var i;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(i=e[r].chains)==null||i.push(`${r}:${n}`)}),e}function cf(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=_j(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=hc(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const Cj={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}},Sj={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 j(s,e){const{message:t,code:i}=Sj[s];return{message:e?`${t} ${e}`:t,code:i}}function Me(s,e){const{message:t,code:i}=Cj[s];return{message:e?`${t} ${e}`:t,code:i}}function _r(s,e){return!!Array.isArray(s)}function ra(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function Dt(s){return typeof s>"u"}function at(s,e){return e&&Dt(s)?!0:typeof s=="string"&&!!s.trim().length}function Yu(s,e){return e&&Dt(s)?!0:typeof s=="number"&&!isNaN(s)}function $j(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return pr(r,i)?(i.forEach(o=>{const{accounts:a,methods:l,events:c}=s.namespaces[o],h=to(a),u=t[o];(!pr(Fy(o,u),h)||!pr(u.methods,l)||!pr(u.events,c))&&(n=!1)}),n):!1}function xc(s){return at(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function Pj(s){if(at(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&xc(t)}}return!1}function Tj(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(at(s,!1)){if(e(s))return!0;const t=Vy(s);return e(t)}}catch{}return!1}function Mj(s){var e;return(e=s==null?void 0:s.proposer)==null?void 0:e.publicKey}function Oj(s){return s==null?void 0:s.topic}function xj(s,e){let t=null;return at(s==null?void 0:s.publicKey,!1)||(t=j("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function lf(s){let e=!0;return _r(s)?s.length&&(e=s.every(t=>at(t,!1))):e=!1,e}function Dj(s,e,t){let i=null;return _r(e)&&e.length?e.forEach(r=>{i||xc(r)||(i=Me("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):xc(s)||(i=Me("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function kj(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=Dj(r,Fy(r,n),`${e} ${t}`);o&&(i=o)}),i}function jj(s,e){let t=null;return _r(s)?s.forEach(i=>{t||Pj(i)||(t=Me("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Me("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function Rj(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=jj(i==null?void 0:i.accounts,`${e} namespace`);r&&(t=r)}),t}function Lj(s,e){let t=null;return lf(s==null?void 0:s.methods)?lf(s==null?void 0:s.events)||(t=Me("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Me("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function mb(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=Lj(i,`${e}, namespace`);r&&(t=r)}),t}function Uj(s,e,t){let i=null;if(s&&ra(s)){const r=mb(s,e);r&&(i=r);const n=kj(s,e,t);n&&(i=n)}else i=j("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function Kl(s,e){let t=null;if(s&&ra(s)){const i=mb(s,e);i&&(t=i);const r=Rj(s,e);r&&(t=r)}else t=j("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function wb(s){return at(s.protocol,!0)}function zj(s,e){let t=!1;return s?s&&_r(s)&&s.length&&s.forEach(i=>{t=wb(i)}):t=!0,t}function Fj(s){return typeof s=="number"}function rs(s){return typeof s<"u"&&typeof s!==null}function qj(s){return!(!s||typeof s!="object"||!s.code||!Yu(s.code,!1)||!s.message||!at(s.message,!1))}function Bj(s){return!(Dt(s)||!at(s.method,!1))}function Hj(s){return!(Dt(s)||Dt(s.result)&&Dt(s.error)||!Yu(s.id,!1)||!at(s.jsonrpc,!1))}function Wj(s){return!(Dt(s)||!at(s.name,!1))}function hf(s,e){return!(!xc(e)||!Ej(s).includes(e))}function Vj(s,e,t){return at(t,!1)?Aj(s,e).includes(t):!1}function Kj(s,e,t){return at(t,!1)?Nj(s,e).includes(t):!1}function uf(s,e,t){let i=null;const r=Gj(s),n=Yj(e),o=Object.keys(r),a=Object.keys(n),l=df(Object.keys(s)),c=df(Object.keys(e)),h=l.filter(u=>!c.includes(u));return h.length&&(i=j("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
16
+ `)};function i4(s){return _.Buffer.from(JSON.stringify(s)).toString("base64")}function r4(s){return JSON.parse(_.Buffer.from(s,"base64").toString("utf-8"))}function Ar(s){if(!s)throw new Error("No recap provided, value is undefined");if(!s.att)throw new Error("No `att` property found");const e=Object.keys(s.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=s.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(r=>{const n=i[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function n4(s,e,t,i={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[s]:o4(e,t,i)}}}function o4(s,e,t={}){e=e==null?void 0:e.sort((r,n)=>r.localeCompare(n));const i=e.map(r=>({[`${s}/${r}`]:[t]}));return Object.assign({},...i)}function tb(s){return Ar(s),`urn:recap:${i4(s).replace(/=/g,"")}`}function sa(s){const e=r4(s.replace("urn:recap:",""));return Ar(e),e}function a4(s,e,t){const i=n4(s,e,t);return tb(i)}function c4(s){return s&&s.includes("urn:recap:")}function l4(s,e){const t=sa(s),i=sa(e),r=h4(t,i);return tb(r)}function h4(s,e){Ar(s),Ar(e);const t=Object.keys(s.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),i={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=s.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,l)=>a.localeCompare(l)).forEach(a=>{var l,c;i.att[r]=e4(X3({},i.att[r]),{[a]:((l=s.att[r])==null?void 0:l[a])||((c=e.att[r])==null?void 0:c[a])})})}),i}function u4(s="",e){Ar(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(s.includes(t))return s;const i=[];let r=0;Object.keys(e.att).forEach(a=>{const l=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));l.sort((u,d)=>u.action.localeCompare(d.action));const c={};l.forEach(u=>{c[u.ability]||(c[u.ability]=[]),c[u.ability].push(u.action)});const h=Object.keys(c).map(u=>(r++,`(${r}) '${u}': '${c[u].join("', '")}' for '${a}'.`));i.push(h.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${s?s+" ":""}${o}`}function Fg(s){var e;const t=sa(s);Ar(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function qg(s){const e=sa(s);Ar(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(r=>{var n;(n=r==null?void 0:r[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function uc(s){if(!s)return;const e=s==null?void 0:s[s.length-1];return c4(e)?e:void 0}function Bl(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function sb(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ps(s,...e){if(!sb(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Bg(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function d4(s,e){ps(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Hg(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}const Fi=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),p4=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),g4=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!g4)throw new Error("Non little-endian hardware is not supported");function f4(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Yh(s){if(typeof s=="string")s=f4(s);else if(sb(s))s=Qh(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function m4(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function w4(s,e){if(s.length!==e.length)return!1;let t=0;for(let i=0;i<s.length;i++)t|=s[i]^e[i];return t===0}const y4=(s,e)=>{function t(i,...r){if(ps(i),s.nonceLength!==void 0){const c=r[0];if(!c)throw new Error("nonce / iv required");s.varSizeNonce?ps(c):ps(c,s.nonceLength)}const n=s.tagLength;n&&r[1]!==void 0&&ps(r[1]);const o=e(i,...r),a=(c,h)=>{if(h!==void 0){if(c!==2)throw new Error("cipher output not supported");ps(h)}};let l=!1;return{encrypt(c,h){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ps(c),a(o.encrypt.length,h),o.encrypt(c,h)},decrypt(c,h){if(ps(c),n&&c.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,h),o.decrypt(c,h)}}}return Object.assign(t,s),t};function Wg(s,e,t=!0){if(e===void 0)return new Uint8Array(s);if(e.length!==s)throw new Error("invalid output length, expected "+s+", got: "+e.length);if(t&&!b4(e))throw new Error("invalid output, must be aligned");return e}function Vg(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);s.setUint32(e+4,o,i),s.setUint32(e+0,a,i)}function b4(s){return s.byteOffset%4===0}function Qh(s){return Uint8Array.from(s)}function qn(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}const ib=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),v4=ib("expand 16-byte k"),I4=ib("expand 32-byte k"),E4=Fi(v4),A4=Fi(I4);function ge(s,e){return s<<e|s>>>32-e}function Zh(s){return s.byteOffset%4===0}const Va=64,N4=16,rb=2**32-1,Kg=new Uint32Array;function _4(s,e,t,i,r,n,o,a){const l=r.length,c=new Uint8Array(Va),h=Fi(c),u=Zh(r)&&Zh(n),d=u?Fi(r):Kg,p=u?Fi(n):Kg;for(let g=0;g<l;o++){if(s(e,t,i,h,o,a),o>=rb)throw new Error("arx: counter overflow");const f=Math.min(Va,l-g);if(u&&f===Va){const y=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,m;w<N4;w++)m=y+w,p[m]=d[m]^h[w];g+=Va;continue}for(let y=0,w;y<f;y++)w=g+y,n[w]=r[w]^c[y];g+=f}}function C4(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=m4({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return Bl(r),Bl(o),Hg(n),Hg(t),(a,l,c,h,u=0)=>{ps(a),ps(l),ps(c);const d=c.length;if(h===void 0&&(h=new Uint8Array(d)),ps(h),Bl(u),u<0||u>=rb)throw new Error("arx: counter overflow");if(h.length<d)throw new Error(`arx: output (${h.length}) is shorter than data (${d})`);const p=[];let g=a.length,f,y;if(g===32)p.push(f=Qh(a)),y=A4;else if(g===16&&t)f=new Uint8Array(32),f.set(a),f.set(a,16),y=E4,p.push(f);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Zh(l)||p.push(l=Qh(l));const w=Fi(f);if(i){if(l.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(y,w,Fi(l.subarray(0,16)),w),l=l.subarray(16)}const m=16-r;if(m!==l.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const I=new Uint8Array(12);I.set(l,n?0:12-l.length),l=I,p.push(l)}const b=Fi(l);return _4(s,y,w,b,c,h,u,o),qn(...p),h}}const $t=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let S4=class{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=Yh(e),ps(e,32);const t=$t(e,0),i=$t(e,2),r=$t(e,4),n=$t(e,6),o=$t(e,8),a=$t(e,10),l=$t(e,12),c=$t(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|r<<6)&7939,this.r[3]=(r>>>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|l<<5)&8065,this.r[8]=(l>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let h=0;h<8;h++)this.pad[h]=$t(e,16+2*h)}process(e,t,i=!1){const r=i?0:2048,{h:n,r:o}=this,a=o[0],l=o[1],c=o[2],h=o[3],u=o[4],d=o[5],p=o[6],g=o[7],f=o[8],y=o[9],w=$t(e,t+0),m=$t(e,t+2),b=$t(e,t+4),I=$t(e,t+6),N=$t(e,t+8),$=$t(e,t+10),P=$t(e,t+12),O=$t(e,t+14);let C=n[0]+(w&8191),T=n[1]+((w>>>13|m<<3)&8191),S=n[2]+((m>>>10|b<<6)&8191),R=n[3]+((b>>>7|I<<9)&8191),L=n[4]+((I>>>4|N<<12)&8191),q=n[5]+(N>>>1&8191),B=n[6]+((N>>>14|$<<2)&8191),U=n[7]+(($>>>11|P<<5)&8191),H=n[8]+((P>>>8|O<<8)&8191),W=n[9]+(O>>>5|r),A=0,z=A+C*a+T*(5*y)+S*(5*f)+R*(5*g)+L*(5*p);A=z>>>13,z&=8191,z+=q*(5*d)+B*(5*u)+U*(5*h)+H*(5*c)+W*(5*l),A+=z>>>13,z&=8191;let Y=A+C*l+T*a+S*(5*y)+R*(5*f)+L*(5*g);A=Y>>>13,Y&=8191,Y+=q*(5*p)+B*(5*d)+U*(5*u)+H*(5*h)+W*(5*c),A+=Y>>>13,Y&=8191;let K=A+C*c+T*l+S*a+R*(5*y)+L*(5*f);A=K>>>13,K&=8191,K+=q*(5*g)+B*(5*p)+U*(5*d)+H*(5*u)+W*(5*h),A+=K>>>13,K&=8191;let be=A+C*h+T*c+S*l+R*a+L*(5*y);A=be>>>13,be&=8191,be+=q*(5*f)+B*(5*g)+U*(5*p)+H*(5*d)+W*(5*u),A+=be>>>13,be&=8191;let oe=A+C*u+T*h+S*c+R*l+L*a;A=oe>>>13,oe&=8191,oe+=q*(5*y)+B*(5*f)+U*(5*g)+H*(5*p)+W*(5*d),A+=oe>>>13,oe&=8191;let Oe=A+C*d+T*u+S*h+R*c+L*l;A=Oe>>>13,Oe&=8191,Oe+=q*a+B*(5*y)+U*(5*f)+H*(5*g)+W*(5*p),A+=Oe>>>13,Oe&=8191;let lt=A+C*p+T*d+S*u+R*h+L*c;A=lt>>>13,lt&=8191,lt+=q*l+B*a+U*(5*y)+H*(5*f)+W*(5*g),A+=lt>>>13,lt&=8191;let Be=A+C*g+T*p+S*d+R*u+L*h;A=Be>>>13,Be&=8191,Be+=q*c+B*l+U*a+H*(5*y)+W*(5*f),A+=Be>>>13,Be&=8191;let Qe=A+C*f+T*g+S*p+R*d+L*u;A=Qe>>>13,Qe&=8191,Qe+=q*h+B*c+U*l+H*a+W*(5*y),A+=Qe>>>13,Qe&=8191;let He=A+C*y+T*f+S*g+R*p+L*d;A=He>>>13,He&=8191,He+=q*u+B*h+U*c+H*l+W*a,A+=He>>>13,He&=8191,A=(A<<2)+A|0,A=A+z|0,z=A&8191,A=A>>>13,Y+=A,n[0]=z,n[1]=Y,n[2]=K,n[3]=be,n[4]=oe,n[5]=Oe,n[6]=lt,n[7]=Be,n[8]=Qe,n[9]=He}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,i[0]=e[0]+5,r=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+r,r=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;qn(i)}update(e){Bg(this);const{buffer:t,blockLen:i}=this;e=Yh(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){for(;i<=r-n;n+=i)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){qn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Bg(this),d4(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}};function $4(s){const e=(i,r)=>s(r).update(Yh(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const P4=$4(s=>new S4(s));function T4(s,e,t,i,r,n=20){let o=s[0],a=s[1],l=s[2],c=s[3],h=e[0],u=e[1],d=e[2],p=e[3],g=e[4],f=e[5],y=e[6],w=e[7],m=r,b=t[0],I=t[1],N=t[2],$=o,P=a,O=l,C=c,T=h,S=u,R=d,L=p,q=g,B=f,U=y,H=w,W=m,A=b,z=I,Y=N;for(let be=0;be<n;be+=2)$=$+T|0,W=ge(W^$,16),q=q+W|0,T=ge(T^q,12),$=$+T|0,W=ge(W^$,8),q=q+W|0,T=ge(T^q,7),P=P+S|0,A=ge(A^P,16),B=B+A|0,S=ge(S^B,12),P=P+S|0,A=ge(A^P,8),B=B+A|0,S=ge(S^B,7),O=O+R|0,z=ge(z^O,16),U=U+z|0,R=ge(R^U,12),O=O+R|0,z=ge(z^O,8),U=U+z|0,R=ge(R^U,7),C=C+L|0,Y=ge(Y^C,16),H=H+Y|0,L=ge(L^H,12),C=C+L|0,Y=ge(Y^C,8),H=H+Y|0,L=ge(L^H,7),$=$+S|0,Y=ge(Y^$,16),U=U+Y|0,S=ge(S^U,12),$=$+S|0,Y=ge(Y^$,8),U=U+Y|0,S=ge(S^U,7),P=P+R|0,W=ge(W^P,16),H=H+W|0,R=ge(R^H,12),P=P+R|0,W=ge(W^P,8),H=H+W|0,R=ge(R^H,7),O=O+L|0,A=ge(A^O,16),q=q+A|0,L=ge(L^q,12),O=O+L|0,A=ge(A^O,8),q=q+A|0,L=ge(L^q,7),C=C+T|0,z=ge(z^C,16),B=B+z|0,T=ge(T^B,12),C=C+T|0,z=ge(z^C,8),B=B+z|0,T=ge(T^B,7);let K=0;i[K++]=o+$|0,i[K++]=a+P|0,i[K++]=l+O|0,i[K++]=c+C|0,i[K++]=h+T|0,i[K++]=u+S|0,i[K++]=d+R|0,i[K++]=p+L|0,i[K++]=g+q|0,i[K++]=f+B|0,i[K++]=y+U|0,i[K++]=w+H|0,i[K++]=m+W|0,i[K++]=b+A|0,i[K++]=I+z|0,i[K++]=N+Y|0}const M4=C4(T4,{counterRight:!1,counterLength:4,allowShortKeys:!1}),O4=new Uint8Array(16),Gg=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(O4.subarray(t))},x4=new Uint8Array(32);function Yg(s,e,t,i,r){const n=s(e,t,x4),o=P4.create(n);r&&Gg(o,r),Gg(o,i);const a=new Uint8Array(16),l=p4(a);Vg(l,0,BigInt(r?r.length:0),!0),Vg(l,8,BigInt(i.length),!0),o.update(a);const c=o.digest();return qn(n,a),c}const D4=s=>(e,t,i)=>({encrypt(r,n){const o=r.length;n=Wg(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);s(e,t,a,a,1);const l=Yg(s,e,t,a,i);return n.set(l,o),qn(l),n},decrypt(r,n){n=Wg(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),l=Yg(s,e,t,o,i);if(!w4(a,l))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),qn(l),n}}),nb=y4({blockSize:64,nonceLength:12,tagLength:16},D4(M4));let ob=class extends Bu{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,qu(e);const i=Fn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return zn(this),this.iHash.update(e),this}digestInto(e){zn(this),il(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:i,finished:r,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Wu=(s,e,t)=>new ob(s,e).update(t).digest();Wu.create=(s,e)=>new ob(s,e);function k4(s,e,t){return qu(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Wu(s,Fn(t),Fn(e))}const Hl=new Uint8Array([0]),Qg=new Uint8Array;function j4(s,e,t,i=32){if(qu(s),ta(i),i>255*s.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/s.outputLen);t===void 0&&(t=Qg);const n=new Uint8Array(r*s.outputLen),o=Wu.create(s,e),a=o._cloneInto(),l=new Uint8Array(o.outputLen);for(let c=0;c<r;c++)Hl[0]=c+1,a.update(c===0?Qg:l).update(t).update(Hl).digestInto(l),n.set(l,s.outputLen*c),o._cloneInto(a);return o.destroy(),a.destroy(),l.fill(0),Hl.fill(0),n.slice(0,i)}const R4=(s,e,t,i,r)=>j4(s,k4(s,e,t),i,r);function L4(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),l=i?4:0,c=i?0:4;s.setUint32(e+l,o,i),s.setUint32(e+c,a,i)}function U4(s,e,t){return s&e^~s&t}function z4(s,e,t){return s&e^s&t^e&t}class F4 extends Bu{constructor(e,t,i,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ql(this.buffer)}update(e){zn(this);const{view:t,buffer:i,blockLen:r}=this;e=Fn(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const l=ql(e);for(;r<=n-o;o+=r)this.process(l,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){zn(this),Ky(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(i,0),o=0);for(let u=o;u<r;u++)t[u]=0;L4(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=ql(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=l/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)a.setUint32(4*u,h[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:r,finished:n,destroyed:o,pos:a}=this;return e.length=r,e.pos=a,e.finished=n,e.destroyed=o,r%t&&e.buffer.set(i),e}}const q4=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]),Ai=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ni=new Uint32Array(64);let B4=class extends F4{constructor(){super(64,32,8,!1),this.A=Ai[0]|0,this.B=Ai[1]|0,this.C=Ai[2]|0,this.D=Ai[3]|0,this.E=Ai[4]|0,this.F=Ai[5]|0,this.G=Ai[6]|0,this.H=Ai[7]|0}get(){const{A:e,B:t,C:i,D:r,E:n,F:o,G:a,H:l}=this;return[e,t,i,r,n,o,a,l]}set(e,t,i,r,n,o,a,l){this.A=e|0,this.B=t|0,this.C=i|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=l|0}process(e,t){for(let u=0;u<16;u++,t+=4)Ni[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const d=Ni[u-15],p=Ni[u-2],g=Gs(d,7)^Gs(d,18)^d>>>3,f=Gs(p,17)^Gs(p,19)^p>>>10;Ni[u]=f+Ni[u-7]+g+Ni[u-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:l,G:c,H:h}=this;for(let u=0;u<64;u++){const d=Gs(a,6)^Gs(a,11)^Gs(a,25),p=h+d+U4(a,l,c)+q4[u]+Ni[u]|0,g=(Gs(i,2)^Gs(i,13)^Gs(i,22))+z4(i,r,n)|0;h=c,c=l,l=a,a=o+p|0,o=n,n=r,r=i,i=p+g|0}i=i+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,l=l+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(i,r,n,o,a,l,c,h)}roundClean(){Ni.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const rl=Gy(()=>new B4);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ab=BigInt(0);function Vu(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function cb(s){if(!Vu(s))throw new Error("Uint8Array expected")}const H4=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function W4(s){cb(s);let e="";for(let t=0;t<s.length;t++)e+=H4[s[t]];return e}function V4(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?ab:BigInt("0x"+s)}const li={_0:48,_9:57,A:65,F:70,a:97,f:102};function Zg(s){if(s>=li._0&&s<=li._9)return s-li._0;if(s>=li.A&&s<=li.F)return s-(li.A-10);if(s>=li.a&&s<=li.f)return s-(li.a-10)}function lb(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=Zg(s.charCodeAt(n)),a=Zg(s.charCodeAt(n+1));if(o===void 0||a===void 0){const l=s[n]+s[n+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+n)}i[r]=o*16+a}return i}function Jg(s){return cb(s),V4(W4(Uint8Array.from(s).reverse()))}function K4(s,e){return lb(s.toString(16).padStart(e*2,"0"))}function G4(s,e){return K4(s,e).reverse()}function Xg(s,e,t){let i;if(typeof e=="string")try{i=lb(e)}catch(n){throw new Error(s+" must be hex string or Uint8Array, cause: "+n)}else if(Vu(e))i=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");const r=i.length;if(typeof t=="number"&&r!==t)throw new Error(s+" of length "+t+" expected, got "+r);return i}const Wl=s=>typeof s=="bigint"&&ab<=s;function Y4(s,e,t){return Wl(s)&&Wl(e)&&Wl(t)&&e<=s&&s<t}function ef(s,e,t,i){if(!Y4(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const Q4={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||Vu(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function Z4(s,e,t={}){const i=(r,n,o)=>{const a=Q4[n];if(typeof a!="function")throw new Error("invalid validator function");const l=s[r];if(!(o&&l===void 0)&&!a(l,s))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+l)};for(const[r,n]of Object.entries(e))i(r,n,!1);for(const[r,n]of Object.entries(t))i(r,n,!0);return s}const $n=BigInt(0),Ka=BigInt(1);function hb(s,e){const t=s%e;return t>=$n?t:e+t}function J4(s,e,t){if(e<$n)throw new Error("invalid exponent, negatives unsupported");if(t<=$n)throw new Error("invalid modulus");if(t===Ka)return $n;let i=Ka;for(;e>$n;)e&Ka&&(i=i*s%t),s=s*s%t,e>>=Ka;return i}function zs(s,e,t){let i=s;for(;e-- >$n;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const rn=BigInt(0),Vl=BigInt(1);function X4(s){return Z4(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function ej(s){const e=X4(s),{P:t}=e,i=m=>hb(m,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),l=e.powPminus2||(m=>J4(m,t-BigInt(2),t));function c(m,b,I){const N=i(m*(b-I));return b=i(b-N),I=i(I+N),[b,I]}const h=(e.a-BigInt(2))/BigInt(4);function u(m,b){ef("u",m,rn,t),ef("scalar",b,rn,t);const I=b,N=m;let $=Vl,P=rn,O=m,C=Vl,T=rn,S;for(let L=BigInt(r-1);L>=rn;L--){const q=I>>L&Vl;T^=q,S=c(T,$,O),$=S[0],O=S[1],S=c(T,P,C),P=S[0],C=S[1],T=q;const B=$+P,U=i(B*B),H=$-P,W=i(H*H),A=U-W,z=O+C,Y=O-C,K=i(Y*B),be=i(z*H),oe=K+be,Oe=K-be;O=i(oe*oe),C=i(N*i(Oe*Oe)),$=i(U*W),P=i(A*(U+i(h*A)))}S=c(T,$,O),$=S[0],O=S[1],S=c(T,P,C),P=S[0],C=S[1];const R=l(P);return i($*R)}function d(m){return G4(i(m),n)}function p(m){const b=Xg("u coordinate",m,n);return o===32&&(b[31]&=127),Jg(b)}function g(m){const b=Xg("scalar",m),I=b.length;if(I!==n&&I!==o){let N=""+n+" or "+o;throw new Error("invalid scalar, expected "+N+" bytes, got "+I)}return Jg(a(b))}function f(m,b){const I=p(b),N=g(m),$=u(I,N);if($===rn)throw new Error("invalid private or public key received");return d($)}const y=d(e.Gu);function w(m){return f(m,y)}return{scalarMult:f,scalarMultBase:w,getSharedSecret:(m,b)=>f(m,b),getPublicKey:m=>w(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:y}}const Jh=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const tj=BigInt(1),tf=BigInt(2),sj=BigInt(3),ij=BigInt(5);BigInt(8);function rj(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=Jh,o=s*s%n*s%n,a=zs(o,tf,n)*o%n,l=zs(a,tj,n)*s%n,c=zs(l,ij,n)*l%n,h=zs(c,e,n)*c%n,u=zs(h,t,n)*h%n,d=zs(u,i,n)*u%n,p=zs(d,r,n)*d%n,g=zs(p,r,n)*d%n,f=zs(g,e,n)*c%n;return{pow_p_5_8:zs(f,tf,n)*s%n,b2:o}}function nj(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const Xh=ej({P:Jh,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=Jh,{pow_p_5_8:t,b2:i}=rj(s);return hb(zs(t,sj,e)*i,e)},adjustScalarBytes:nj,randomBytes:Aa}),ub="base10",Ht="base16",Ui="base64pad",Io="base64url",Na="utf8",db=0,mi=1,_a=2,oj=0,sf=1,Uo=12,Ku=32;function aj(){const s=Xh.utils.randomPrivateKey(),e=Xh.getPublicKey(s);return{privateKey:Ae(s,Ht),publicKey:Ae(e,Ht)}}function eu(){const s=Aa(Ku);return Ae(s,Ht)}function cj(s,e){const t=Xh.getSharedSecret(Ge(s,Ht),Ge(e,Ht)),i=R4(rl,t,void 0,void 0,Ku);return Ae(i,Ht)}function dc(s){const e=rl(Ge(s,Ht));return Ae(e,Ht)}function Xs(s){const e=rl(Ge(s,Na));return Ae(e,Ht)}function pb(s){return Ge(`${s}`,ub)}function Nr(s){return Number(Ae(s,ub))}function lj(s){const e=pb(typeof s.type<"u"?s.type:db);if(Nr(e)===mi&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?Ge(s.senderPublicKey,Ht):void 0,i=typeof s.iv<"u"?Ge(s.iv,Ht):Aa(Uo),r=Ge(s.symKey,Ht),n=nb(r,i).encrypt(Ge(s.message,Na));return gb({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function hj(s){const e=Ge(s.symKey,Ht),{sealed:t,iv:i}=ia(s),r=nb(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return Ae(r,Na)}function uj(s,e){const t=pb(_a),i=Aa(Uo),r=Ge(s,Na);return gb({type:t,sealed:r,iv:i,encoding:e})}function dj(s,e){const{sealed:t}=ia({encoded:s,encoding:e});return Ae(t,Na)}function gb(s){const{encoding:e=Ui}=s;if(Nr(s.type)===_a)return Ae(Mn([s.type,s.sealed]),e);if(Nr(s.type)===mi){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ae(Mn([s.type,s.senderPublicKey,s.iv,s.sealed]),e)}return Ae(Mn([s.type,s.iv,s.sealed]),e)}function ia(s){const{encoded:e,encoding:t=Ui}=s,i=Ge(e,t),r=i.slice(oj,sf),n=sf;if(Nr(r)===mi){const c=n+Ku,h=c+Uo,u=i.slice(n,c),d=i.slice(c,h),p=i.slice(h);return{type:r,sealed:p,iv:d,senderPublicKey:u}}if(Nr(r)===_a){const c=i.slice(n),h=Aa(Uo);return{type:r,sealed:c,iv:h}}const o=n+Uo,a=i.slice(n,o),l=i.slice(o);return{type:r,sealed:l,iv:a}}function pj(s,e){const t=ia({encoded:s,encoding:e==null?void 0:e.encoding});return fb({type:Nr(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Ae(t.senderPublicKey,Ht):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function fb(s){const e=(s==null?void 0:s.type)||db;if(e===mi){if(typeof(s==null?void 0:s.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(s==null?void 0:s.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:s==null?void 0:s.senderPublicKey,receiverPublicKey:s==null?void 0:s.receiverPublicKey}}function rf(s){return s.type===mi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function nf(s){return s.type===_a}function gj(s){return new Zm.ec("p256").keyFromPublic({x:_.Buffer.from(s.x,"base64").toString("hex"),y:_.Buffer.from(s.y,"base64").toString("hex")},"hex")}function fj(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function mj(s){return _.Buffer.from(fj(s),"base64")}function wj(s,e){const[t,i,r]=s.split("."),n=mj(r);if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32).toString("hex"),a=n.slice(32,64).toString("hex"),l=`${t}.${i}`,c=rl(l),h=gj(e),u=Ae(c,Ht);if(!h.verify(u,{r:o,s:a}))throw new Error("Invalid signature");return jn(s).payload}const yj="irn";function Oc(s){return(s==null?void 0:s.relay)||{protocol:yj}}function Oo(s){const e=Cm[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function bj(s,e="-"){const t={},i="relay"+e;return Object.keys(s).forEach(r=>{if(r.startsWith(i)){const n=r.replace(i,""),o=s[r];t[n]=o}}),t}function of(s){if(!s.includes("wc:")){const c=Vy(s);c!=null&&c.includes("wc:")&&(s=c)}s=s.includes("wc://")?s.replace("wc://",""):s,s=s.includes("wc:")?s.replace("wc:",""):s;const e=s.indexOf(":"),t=s.indexOf("?")!==-1?s.indexOf("?"):void 0,i=s.substring(0,e),r=s.substring(e+1,t).split("@"),n=typeof t<"u"?s.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((c,h)=>{a[h]=c});const l=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:vj(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:bj(a),methods:l,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function vj(s){return s.startsWith("//")?s.substring(2):s}function Ij(s,e="-"){const t="relay",i={};return Object.keys(s).forEach(r=>{const n=r,o=t+e+n;s[n]&&(i[o]=s[n])}),i}function af(s){const e=new URLSearchParams,t=Ij(s.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",s.symKey),s.expiryTimestamp&&e.set("expiryTimestamp",s.expiryTimestamp.toString()),s.methods&&e.set("methods",s.methods.join(","));const i=e.toString();return`${s.protocol}:${s.topic}@${s.version}?${i}`}function Ga(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function to(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function Ej(s){const e=[];return Object.values(s).forEach(t=>{e.push(...to(t.accounts))}),e}function Aj(s,e){const t=[];return Object.values(s).forEach(i=>{to(i.accounts).includes(e)&&t.push(...i.methods)}),t}function Nj(s,e){const t=[];return Object.values(s).forEach(i=>{to(i.accounts).includes(e)&&t.push(...i.events)}),t}function Gu(s){return s.includes(":")}function xo(s){return Gu(s)?s.split(":")[0]:s}function _j(s){const e={};return s==null||s.forEach(t=>{var i;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(i=e[r].chains)==null||i.push(`${r}:${n}`)}),e}function cf(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=_j(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=hc(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const Cj={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}},Sj={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 j(s,e){const{message:t,code:i}=Sj[s];return{message:e?`${t} ${e}`:t,code:i}}function Me(s,e){const{message:t,code:i}=Cj[s];return{message:e?`${t} ${e}`:t,code:i}}function _r(s,e){return!!Array.isArray(s)}function ra(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function Dt(s){return typeof s>"u"}function at(s,e){return e&&Dt(s)?!0:typeof s=="string"&&!!s.trim().length}function Yu(s,e){return e&&Dt(s)?!0:typeof s=="number"&&!isNaN(s)}function $j(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return pr(r,i)?(i.forEach(o=>{const{accounts:a,methods:l,events:c}=s.namespaces[o],h=to(a),u=t[o];(!pr(Fy(o,u),h)||!pr(u.methods,l)||!pr(u.events,c))&&(n=!1)}),n):!1}function xc(s){return at(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function Pj(s){if(at(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&xc(t)}}return!1}function Tj(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(at(s,!1)){if(e(s))return!0;const t=Vy(s);return e(t)}}catch{}return!1}function Mj(s){var e;return(e=s==null?void 0:s.proposer)==null?void 0:e.publicKey}function Oj(s){return s==null?void 0:s.topic}function xj(s,e){let t=null;return at(s==null?void 0:s.publicKey,!1)||(t=j("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function lf(s){let e=!0;return _r(s)?s.length&&(e=s.every(t=>at(t,!1))):e=!1,e}function Dj(s,e,t){let i=null;return _r(e)&&e.length?e.forEach(r=>{i||xc(r)||(i=Me("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):xc(s)||(i=Me("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function kj(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=Dj(r,Fy(r,n),`${e} ${t}`);o&&(i=o)}),i}function jj(s,e){let t=null;return _r(s)?s.forEach(i=>{t||Pj(i)||(t=Me("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Me("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function Rj(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=jj(i==null?void 0:i.accounts,`${e} namespace`);r&&(t=r)}),t}function Lj(s,e){let t=null;return lf(s==null?void 0:s.methods)?lf(s==null?void 0:s.events)||(t=Me("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Me("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function mb(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=Lj(i,`${e}, namespace`);r&&(t=r)}),t}function Uj(s,e,t){let i=null;if(s&&ra(s)){const r=mb(s,e);r&&(i=r);const n=kj(s,e,t);n&&(i=n)}else i=j("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function Kl(s,e){let t=null;if(s&&ra(s)){const i=mb(s,e);i&&(t=i);const r=Rj(s,e);r&&(t=r)}else t=j("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function wb(s){return at(s.protocol,!0)}function zj(s,e){let t=!1;return s?s&&_r(s)&&s.length&&s.forEach(i=>{t=wb(i)}):t=!0,t}function Fj(s){return typeof s=="number"}function rs(s){return typeof s<"u"&&typeof s!==null}function qj(s){return!(!s||typeof s!="object"||!s.code||!Yu(s.code,!1)||!s.message||!at(s.message,!1))}function Bj(s){return!(Dt(s)||!at(s.method,!1))}function Hj(s){return!(Dt(s)||Dt(s.result)&&Dt(s.error)||!Yu(s.id,!1)||!at(s.jsonrpc,!1))}function Wj(s){return!(Dt(s)||!at(s.name,!1))}function hf(s,e){return!(!xc(e)||!Ej(s).includes(e))}function Vj(s,e,t){return at(t,!1)?Aj(s,e).includes(t):!1}function Kj(s,e,t){return at(t,!1)?Nj(s,e).includes(t):!1}function uf(s,e,t){let i=null;const r=Gj(s),n=Yj(e),o=Object.keys(r),a=Object.keys(n),l=df(Object.keys(s)),c=df(Object.keys(e)),h=l.filter(u=>!c.includes(u));return h.length&&(i=j("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
17
17
  Required: ${h.toString()}
18
18
  Received: ${Object.keys(e).toString()}`)),pr(o,a)||(i=j("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces.
19
19
  Required: ${o.toString()}
20
20
  Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||i)return;const d=to(e[u].accounts);d.includes(u)||(i=j("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${u}
21
21
  Required: ${u}
22
- Approved: ${d.toString()}`))}),o.forEach(u=>{i||(pr(r[u].methods,n[u].methods)?pr(r[u].events,n[u].events)||(i=j("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):i=j("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),i}function Gj(s){const e={};return Object.keys(s).forEach(t=>{var i;t.includes(":")?e[t]=s[t]:(i=s[t].chains)==null||i.forEach(r=>{e[r]={methods:s[t].methods,events:s[t].events}})}),e}function df(s){return[...new Set(s.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Yj(s){const e={};return Object.keys(s).forEach(t=>{if(t.includes(":"))e[t]=s[t];else{const i=to(s[t].accounts);i==null||i.forEach(r=>{e[r]={accounts:s[t].accounts.filter(n=>n.includes(`${r}:`)),methods:s[t].methods,events:s[t].events}})}}),e}function Qj(s,e){return Yu(s,!1)&&s<=e.max&&s>=e.min}function pf(){const s=Ea();return new Promise(e=>{switch(s){case ms.browser:e(Zj());break;case ms.reactNative:e(Jj());break;case ms.node:e(Xj());break;default:e(!0)}})}function Zj(){return Ia()&&(navigator==null?void 0:navigator.onLine)}async function Jj(){if(Yi()&&typeof _.global<"u"&&_.global!=null&&_.global.NetInfo){const s=await(_.global==null?void 0:_.global.NetInfo.fetch());return s==null?void 0:s.isConnected}return!0}function Xj(){return!0}function eR(s){switch(Ea()){case ms.browser:tR(s);break;case ms.reactNative:sR(s);break}}function tR(s){!Yi()&&Ia()&&(window.addEventListener("online",()=>s(!0)),window.addEventListener("offline",()=>s(!1)))}function sR(s){var e;Yi()&&typeof _.global<"u"&&_.global!=null&&_.global.NetInfo&&((e=_.global)==null||e.NetInfo.addEventListener(t=>s(t==null?void 0:t.isConnected)))}const Gl={};class Eo{static get(e){return Gl[e]}static set(e,t){Gl[e]=t}static delete(e){delete Gl[e]}}const yb="wc",bb=2,tu="core",ii=`${yb}@2:${tu}:`,iR={logger:"error"},rR={database:":memory:"},nR="crypto",gf="client_ed25519_seed",oR=E.ONE_DAY,aR="keychain",cR="0.3",lR="messages",hR="0.3",ff=E.SIX_HOURS,uR="publisher",vb="irn",dR="error",Ib="wss://relay.walletconnect.org",pR="relayer",Et={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"},gR="_subscription",As={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},fR=.1,su="2.19.1",Ke={link_mode:"link_mode",relay:"relay"},pc={inbound:"inbound",outbound:"outbound"},mR="0.3",wR="WALLETCONNECT_CLIENT_ID",mf="WALLETCONNECT_LINK_MODE_APPS",us={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},yR="subscription",bR="0.3",vR="pairing",IR="0.3",Ao={wc_pairingDelete:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:E.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:E.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:E.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:E.ONE_DAY,prompt:!1,tag:0},res:{ttl:E.ONE_DAY,prompt:!1,tag:0}}},lr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},js={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},ER="history",AR="0.3",NR="expirer",Ss={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},_R="0.3",CR="verify-api",SR="https://verify.walletconnect.com",Eb="https://verify.walletconnect.org",zo=Eb,$R=`${zo}/v3`,PR=[SR,Eb],TR="echo",MR="https://echo.walletconnect.com",Js={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"},ui={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Rs={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},tr={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"},sr={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},No={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},OR=.1,xR="event-client",DR=86400,kR="https://pulse.walletconnect.org/batch";function jR(s,e){if(s.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var r=0;r<s.length;r++){var n=s.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=s.length,l=s.charAt(0),c=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var f=0,y=0,w=0,m=g.length;w!==m&&g[w]===0;)w++,f++;for(var b=(m-w)*h+1>>>0,I=new Uint8Array(b);w!==m;){for(var N=g[w],$=0,P=b-1;(N!==0||$<y)&&P!==-1;P--,$++)N+=256*I[P]>>>0,I[P]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");y=$,w++}for(var O=b-y;O!==b&&I[O]===0;)O++;for(var C=l.repeat(f);O<b;++O)C+=s.charAt(I[O]);return C}function d(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var f=0;if(g[f]!==" "){for(var y=0,w=0;g[f]===l;)y++,f++;for(var m=(g.length-f)*c+1>>>0,b=new Uint8Array(m);g[f];){var I=t[g.charCodeAt(f)];if(I===255)return;for(var N=0,$=m-1;(I!==0||N<w)&&$!==-1;$--,N++)I+=a*b[$]>>>0,b[$]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");w=N,f++}if(g[f]!==" "){for(var P=m-w;P!==m&&b[P]===0;)P++;for(var O=new Uint8Array(y+(m-P)),C=y;P!==m;)O[C++]=b[P++];return O}}}function p(g){var f=d(g);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:p}}var RR=jR,LR=RR;const Ab=s=>{if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);throw new Error("Unknown type, must be binary type")},UR=s=>new TextEncoder().encode(s),zR=s=>new TextDecoder().decode(s);class FR{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class qR{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Nb(this,e)}}class BR{constructor(e){this.decoders=e}or(e){return Nb(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Nb=(s,e)=>new BR({...s.decoders||{[s.prefix]:s},...e.decoders||{[e.prefix]:e}});class HR{constructor(e,t,i,r){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=r,this.encoder=new FR(e,t,i),this.decoder=new qR(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const nl=({name:s,prefix:e,encode:t,decode:i})=>new HR(s,e,t,i),Ca=({prefix:s,name:e,alphabet:t})=>{const{encode:i,decode:r}=LR(t,e);return nl({prefix:s,name:e,encode:i,decode:n=>Ab(r(n))})},WR=(s,e,t,i)=>{const r={};for(let h=0;h<e.length;++h)r[e[h]]=h;let n=s.length;for(;s[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,l=0,c=0;for(let h=0;h<n;++h){const u=r[s[h]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);l=l<<t|u,a+=t,a>=8&&(a-=8,o[c++]=255&l>>a)}if(a>=t||255&l<<8-a)throw new SyntaxError("Unexpected end of data");return o},VR=(s,e,t)=>{const i=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Lt=({name:s,prefix:e,bitsPerChar:t,alphabet:i})=>nl({prefix:e,name:s,encode(r){return VR(r,i,t)},decode(r){return WR(r,i,t,s)}}),KR=nl({prefix:"\0",name:"identity",encode:s=>zR(s),decode:s=>UR(s)});var GR=Object.freeze({__proto__:null,identity:KR});const YR=Lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var QR=Object.freeze({__proto__:null,base2:YR});const ZR=Lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var JR=Object.freeze({__proto__:null,base8:ZR});const XR=Ca({prefix:"9",name:"base10",alphabet:"0123456789"});var e5=Object.freeze({__proto__:null,base10:XR});const t5=Lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),s5=Lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var i5=Object.freeze({__proto__:null,base16:t5,base16upper:s5});const r5=Lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),n5=Lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),o5=Lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),a5=Lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),c5=Lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),l5=Lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),h5=Lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),u5=Lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),d5=Lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var p5=Object.freeze({__proto__:null,base32:r5,base32upper:n5,base32pad:o5,base32padupper:a5,base32hex:c5,base32hexupper:l5,base32hexpad:h5,base32hexpadupper:u5,base32z:d5});const g5=Ca({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),f5=Ca({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var m5=Object.freeze({__proto__:null,base36:g5,base36upper:f5});const w5=Ca({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),y5=Ca({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var b5=Object.freeze({__proto__:null,base58btc:w5,base58flickr:y5});const v5=Lt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),I5=Lt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),E5=Lt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),A5=Lt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var N5=Object.freeze({__proto__:null,base64:v5,base64pad:I5,base64url:E5,base64urlpad:A5});const _b=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),_5=_b.reduce((s,e,t)=>(s[t]=e,s),[]),C5=_b.reduce((s,e,t)=>(s[e.codePointAt(0)]=t,s),[]);function S5(s){return s.reduce((e,t)=>(e+=_5[t],e),"")}function $5(s){const e=[];for(const t of s){const i=C5[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const P5=nl({prefix:"🚀",name:"base256emoji",encode:S5,decode:$5});var T5=Object.freeze({__proto__:null,base256emoji:P5}),M5=Cb,wf=128,O5=-128,x5=Math.pow(2,31);function Cb(s,e,t){e=e||[],t=t||0;for(var i=t;s>=x5;)e[t++]=s&255|wf,s/=128;for(;s&O5;)e[t++]=s&255|wf,s>>>=7;return e[t]=s|0,Cb.bytes=t-i+1,e}var D5=iu,k5=128,yf=127;function iu(s,i){var t=0,i=i||0,r=0,n=i,o,a=s.length;do{if(n>=a)throw iu.bytes=0,new RangeError("Could not decode varint");o=s[n++],t+=r<28?(o&yf)<<r:(o&yf)*Math.pow(2,r),r+=7}while(o>=k5);return iu.bytes=n-i,t}var j5=Math.pow(2,7),R5=Math.pow(2,14),L5=Math.pow(2,21),U5=Math.pow(2,28),z5=Math.pow(2,35),F5=Math.pow(2,42),q5=Math.pow(2,49),B5=Math.pow(2,56),H5=Math.pow(2,63),W5=function(s){return s<j5?1:s<R5?2:s<L5?3:s<U5?4:s<z5?5:s<F5?6:s<q5?7:s<B5?8:s<H5?9:10},V5={encode:M5,decode:D5,encodingLength:W5},Sb=V5;const bf=(s,e,t=0)=>(Sb.encode(s,e,t),e),vf=s=>Sb.encodingLength(s),ru=(s,e)=>{const t=e.byteLength,i=vf(s),r=i+vf(t),n=new Uint8Array(r+t);return bf(s,n,0),bf(t,n,i),n.set(e,r),new K5(s,t,e,n)};class K5{constructor(e,t,i,r){this.code=e,this.size=t,this.digest=i,this.bytes=r}}const $b=({name:s,code:e,encode:t})=>new G5(s,e,t);class G5{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?ru(this.code,t):t.then(i=>ru(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Pb=s=>async e=>new Uint8Array(await crypto.subtle.digest(s,e)),Y5=$b({name:"sha2-256",code:18,encode:Pb("SHA-256")}),Q5=$b({name:"sha2-512",code:19,encode:Pb("SHA-512")});var Z5=Object.freeze({__proto__:null,sha256:Y5,sha512:Q5});const Tb=0,J5="identity",Mb=Ab,X5=s=>ru(Tb,Mb(s)),eL={code:Tb,name:J5,encode:Mb,digest:X5};var tL=Object.freeze({__proto__:null,identity:eL});new TextEncoder,new TextDecoder;const If={...GR,...QR,...JR,...e5,...i5,...p5,...m5,...b5,...N5,...T5};({...Z5,...tL});function sL(s=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(s):new Uint8Array(s)}function Ob(s,e,t,i){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:i}}}const Ef=Ob("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),Yl=Ob("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);const e=sL(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),iL={utf8:Ef,"utf-8":Ef,hex:If.base16,latin1:Yl,ascii:Yl,binary:Yl,...If};function rL(s,e="utf8"){const t=iL[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(s,"utf8"):t.decoder.decode(`${t.prefix}${s}`)}var nL=Object.defineProperty,oL=(s,e,t)=>e in s?nL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ys=(s,e,t)=>oL(s,typeof e!="symbol"?e+"":e,t);class aL{constructor(e,t){this.core=e,this.logger=t,Ys(this,"keychain",new Map),Ys(this,"name",aR),Ys(this,"version",cR),Ys(this,"initialized",!1),Ys(this,"storagePrefix",ii),Ys(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Ys(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Ys(this,"set",async(i,r)=>{this.isInitialized(),this.keychain.set(i,r),await this.persist()}),Ys(this,"get",i=>{this.isInitialized();const r=this.keychain.get(i);if(typeof r>"u"){const{message:n}=j("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return r}),Ys(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Ne(t,this.name)}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Vh(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Kh(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var cL=Object.defineProperty,lL=(s,e,t)=>e in s?cL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Pt=(s,e,t)=>lL(s,typeof e!="symbol"?e+"":e,t);class hL{constructor(e,t,i){this.core=e,this.logger=t,Pt(this,"name",nR),Pt(this,"keychain"),Pt(this,"randomSessionIdentifier",eu()),Pt(this,"initialized",!1),Pt(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Pt(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Pt(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=vc(r);return Tm(n.publicKey)}),Pt(this,"generateKeyPair",()=>{this.isInitialized();const r=aj();return this.setPrivateKey(r.publicKey,r.privateKey)}),Pt(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=vc(n),a=this.randomSessionIdentifier;return await Mm(a,r,oR,o)}),Pt(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),l=cj(a,n);return this.setSymKey(l,o)}),Pt(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||dc(r);return await this.keychain.set(o,r),o}),Pt(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Pt(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Pt(this,"encode",async(r,n,o)=>{this.isInitialized();const a=fb(o),l=Sr(n);if(nf(a))return uj(l,o==null?void 0:o.encoding);if(rf(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;r=await this.generateSharedKey(d,p)}const c=this.getSymKey(r),{type:h,senderPublicKey:u}=a;return lj({type:h,symKey:c,message:l,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Pt(this,"decode",async(r,n,o)=>{this.isInitialized();const a=pj(n,o);if(nf(a)){const l=dj(n,o==null?void 0:o.encoding);return wi(l)}if(rf(a)){const l=a.receiverPublicKey,c=a.senderPublicKey;r=await this.generateSharedKey(l,c)}try{const l=this.getSymKey(r),c=hj({symKey:l,encoded:n,encoding:o==null?void 0:o.encoding});return wi(c)}catch(l){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(l)}}),Pt(this,"getPayloadType",(r,n=Ui)=>{const o=ia({encoded:r,encoding:n});return Nr(o.type)}),Pt(this,"getPayloadSenderPublicKey",(r,n=Ui)=>{const o=ia({encoded:r,encoding:n});return o.senderPublicKey?Ae(o.senderPublicKey,Ht):void 0}),this.core=e,this.logger=Ne(t,this.name),this.keychain=i||new aL(this.core,this.logger)}get context(){return qe(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(gf)}catch{e=eu(),await this.keychain.set(gf,e)}return rL(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var uL=Object.defineProperty,dL=Object.defineProperties,pL=Object.getOwnPropertyDescriptors,Af=Object.getOwnPropertySymbols,gL=Object.prototype.hasOwnProperty,fL=Object.prototype.propertyIsEnumerable,nu=(s,e,t)=>e in s?uL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,mL=(s,e)=>{for(var t in e||(e={}))gL.call(e,t)&&nu(s,t,e[t]);if(Af)for(var t of Af(e))fL.call(e,t)&&nu(s,t,e[t]);return s},wL=(s,e)=>dL(s,pL(e)),ls=(s,e,t)=>nu(s,typeof e!="symbol"?e+"":e,t);class yL extends CD{constructor(e,t){super(e,t),this.logger=e,this.core=t,ls(this,"messages",new Map),ls(this,"messagesWithoutClientAck",new Map),ls(this,"name",lR),ls(this,"version",hR),ls(this,"initialized",!1),ls(this,"storagePrefix",ii),ls(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ls(this,"set",async(i,r,n)=>{this.isInitialized();const o=Xs(r);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(i,a),n===pc.inbound){const l=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,wL(mL({},l),{[o]:r}))}return await this.persist(),o}),ls(this,"get",i=>{this.isInitialized();let r=this.messages.get(i);return typeof r>"u"&&(r={}),r}),ls(this,"getWithoutAck",i=>{this.isInitialized();const r={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};r[n]=Object.values(o)}return r}),ls(this,"has",(i,r)=>{this.isInitialized();const n=this.get(i),o=Xs(r);return typeof n[o]<"u"}),ls(this,"ack",async(i,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=Xs(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),ls(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=Ne(e,this.name),this.core=t}get context(){return qe(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,Vh(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Vh(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Kh(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Kh(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var bL=Object.defineProperty,vL=Object.defineProperties,IL=Object.getOwnPropertyDescriptors,Nf=Object.getOwnPropertySymbols,EL=Object.prototype.hasOwnProperty,AL=Object.prototype.propertyIsEnumerable,ou=(s,e,t)=>e in s?bL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ya=(s,e)=>{for(var t in e||(e={}))EL.call(e,t)&&ou(s,t,e[t]);if(Nf)for(var t of Nf(e))AL.call(e,t)&&ou(s,t,e[t]);return s},Ql=(s,e)=>vL(s,IL(e)),Ls=(s,e,t)=>ou(s,typeof e!="symbol"?e+"":e,t);class NL extends SD{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Ls(this,"events",new kt.EventEmitter),Ls(this,"name",uR),Ls(this,"queue",new Map),Ls(this,"publishTimeout",E.toMiliseconds(E.ONE_MINUTE)),Ls(this,"initialPublishTimeout",E.toMiliseconds(E.ONE_SECOND*15)),Ls(this,"needsTransportRestart",!1),Ls(this,"publish",async(i,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:r,opts:n}});const a=(n==null?void 0:n.ttl)||ff,l=Oc(n),c=(n==null?void 0:n.prompt)||!1,h=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||gs().toString(),d={topic:i,message:r,opts:{ttl:a,relay:l,prompt:c,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},p=`Failed to publish payload, please try again. id:${u} tag:${h}`;try{const g=new Promise(async f=>{const y=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(Et.publish,y),f(d))};this.relayer.events.on(Et.publish,y);const w=Li(new Promise((m,b)=>{this.rpcPublish({topic:i,message:r,ttl:a,prompt:c,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(m).catch(I=>{this.logger.warn(I,I==null?void 0:I.message),b(I)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${h}`);try{await w,this.events.removeListener(Et.publish,y)}catch(m){this.queue.set(u,Ql(Ya({},d),{attempt:1})),this.logger.warn(m,m==null?void 0:m.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:i,message:r,opts:n}}),await Li(g,this.publishTimeout,p)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(u)}}),Ls(this,"on",(i,r)=>{this.events.on(i,r)}),Ls(this,"once",(i,r)=>{this.events.once(i,r)}),Ls(this,"off",(i,r)=>{this.events.off(i,r)}),Ls(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.relayer=e,this.logger=Ne(t,this.name),this.registerEventListeners()}get context(){return qe(this.logger)}async rpcPublish(e){var t,i,r,n;const{topic:o,message:a,ttl:l=ff,prompt:c,tag:h,id:u,attestation:d,tvf:p}=e,g={method:Oo(Oc().protocol).publish,params:Ya({topic:o,message:a,ttl:l,prompt:c,tag:h,attestation:d},p),id:u};Dt((t=g.params)==null?void 0:t.prompt)&&((i=g.params)==null||delete i.prompt),Dt((r=g.params)==null?void 0:r.tag)&&((n=g.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const f=await this.relayer.request(g);return this.relayer.events.emit(Et.publish,e),this.logger.debug("Successfully Published Payload"),f}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,Ql(Ya({},e),{attempt:i}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Ql(Ya({},e),{topic:r,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(qs.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Et.connection_stalled);return}this.checkQueue()}),this.relayer.on(Et.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var _L=Object.defineProperty,CL=(s,e,t)=>e in s?_L(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,nn=(s,e,t)=>CL(s,typeof e!="symbol"?e+"":e,t);class SL{constructor(){nn(this,"map",new Map),nn(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),nn(this,"get",e=>this.map.get(e)||[]),nn(this,"exists",(e,t)=>this.get(e).includes(t)),nn(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const r=i.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),nn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var $L=Object.defineProperty,PL=Object.defineProperties,TL=Object.getOwnPropertyDescriptors,_f=Object.getOwnPropertySymbols,ML=Object.prototype.hasOwnProperty,OL=Object.prototype.propertyIsEnumerable,au=(s,e,t)=>e in s?$L(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,_o=(s,e)=>{for(var t in e||(e={}))ML.call(e,t)&&au(s,t,e[t]);if(_f)for(var t of _f(e))OL.call(e,t)&&au(s,t,e[t]);return s},Zl=(s,e)=>PL(s,TL(e)),xe=(s,e,t)=>au(s,typeof e!="symbol"?e+"":e,t);class xL extends TD{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,xe(this,"subscriptions",new Map),xe(this,"topicMap",new SL),xe(this,"events",new kt.EventEmitter),xe(this,"name",yR),xe(this,"version",bR),xe(this,"pending",new Map),xe(this,"cached",[]),xe(this,"initialized",!1),xe(this,"storagePrefix",ii),xe(this,"subscribeTimeout",E.toMiliseconds(E.ONE_MINUTE)),xe(this,"initialSubscribeTimeout",E.toMiliseconds(E.ONE_SECOND*15)),xe(this,"clientId"),xe(this,"batchSubscribeTopicsLimit",500),xe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),xe(this,"subscribe",async(i,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}});try{const n=Oc(r),o={topic:i,relay:n,transportType:r==null?void 0:r.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,r);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),xe(this,"unsubscribe",async(i,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(i,r.id,r):await this.unsubscribeByTopic(i,r)}),xe(this,"isSubscribed",i=>new Promise(r=>{r(this.topicMap.topics.includes(i))})),xe(this,"isKnownTopic",i=>new Promise(r=>{r(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),xe(this,"on",(i,r)=>{this.events.on(i,r)}),xe(this,"once",(i,r)=>{this.events.once(i,r)}),xe(this,"off",(i,r)=>{this.events.off(i,r)}),xe(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),xe(this,"start",async()=>{await this.onConnect()}),xe(this,"stop",async()=>{await this.onDisconnect()}),xe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),xe(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(r=>{i.push(r)}),await this.batchSubscribe(i)}),xe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(qs.pulse,async()=>{await this.checkPending()}),this.events.on(us.created,async i=>{const r=us.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()}),this.events.on(us.deleted,async i=>{const r=us.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()})}),this.relayer=e,this.logger=Ne(t,this.name),this.clientId=""}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const r=Oc(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Me("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,i){var r;(!i||(i==null?void 0:i.transportType)===Ke.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Oo(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=i==null?void 0:i.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===Ke.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(h=>this.logger.warn(h))},E.toMiliseconds(E.ONE_SECOND)),a;const l=new Promise(async h=>{const u=d=>{d.topic===e&&(this.events.removeListener(us.created,u),h(d.id))};this.events.on(us.created,u);try{const d=await Li(new Promise((p,g)=>{this.relayer.request(n).catch(f=>{this.logger.warn(f,f==null?void 0:f.message),g(f)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(us.created,u),h(d)}catch{}}),c=await Li(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!c&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return c?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Et.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:Oo(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Li(new Promise(r=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Et.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:Oo(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let r;try{r=await await Li(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Et.connection_stalled)}return r}rpcUnsubscribe(e,t,i){const r={method:Oo(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,Zl(_o({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,_o({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,_o({},t)),this.topicMap.set(t.topic,e),this.events.emit(us.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(us.deleted,Zl(_o({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(us.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(us.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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 t=>Zl(_o({},t),{id:await this.getSubscriptionId(t.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await v3(E.toMiliseconds(E.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=j("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 Xs(e+await this.getClientId())}}var DL=Object.defineProperty,Cf=Object.getOwnPropertySymbols,kL=Object.prototype.hasOwnProperty,jL=Object.prototype.propertyIsEnumerable,cu=(s,e,t)=>e in s?DL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Sf=(s,e)=>{for(var t in e||(e={}))kL.call(e,t)&&cu(s,t,e[t]);if(Cf)for(var t of Cf(e))jL.call(e,t)&&cu(s,t,e[t]);return s},fe=(s,e,t)=>cu(s,typeof e!="symbol"?e+"":e,t);class RL extends $D{constructor(e){super(e),fe(this,"protocol","wc"),fe(this,"version",2),fe(this,"core"),fe(this,"logger"),fe(this,"events",new kt.EventEmitter),fe(this,"provider"),fe(this,"messages"),fe(this,"subscriber"),fe(this,"publisher"),fe(this,"name",pR),fe(this,"transportExplicitlyClosed",!1),fe(this,"initialized",!1),fe(this,"connectionAttemptInProgress",!1),fe(this,"relayUrl"),fe(this,"projectId"),fe(this,"packageName"),fe(this,"bundleId"),fe(this,"hasExperiencedNetworkDisruption",!1),fe(this,"pingTimeout"),fe(this,"heartBeatTimeout",E.toMiliseconds(E.THIRTY_SECONDS+E.FIVE_SECONDS)),fe(this,"reconnectTimeout"),fe(this,"connectPromise"),fe(this,"reconnectInProgress",!1),fe(this,"requestsInFlight",[]),fe(this,"connectTimeout",E.toMiliseconds(E.ONE_SECOND*15)),fe(this,"request",async t=>{var i,r;this.logger.debug("Publishing Request Payload");const n=t.id||gs().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((r=t.params)==null?void 0:r.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),fe(this,"resetPingTimeout",()=>{Tc()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),fe(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),fe(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Et.connect)}),fe(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),fe(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(Et.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),fe(this,"registerProviderListeners",()=>{this.provider.on(As.payload,this.onPayloadHandler),this.provider.on(As.connect,this.onConnectHandler),this.provider.on(As.disconnect,this.onDisconnectHandler),this.provider.on(As.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ne(e.logger,this.name):Vn(yi({level:e.logger||dR})),this.messages=new yL(this.logger,e.core),this.subscriber=new xL(this,this.logger),this.publisher=new NL(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Ib,this.projectId=e.projectId,n3()?this.packageName=Tg():o3()&&(this.bundleId=Tg()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return qe(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Ke.relay},pc.outbound)}async subscribe(e,t){var i,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=t==null?void 0:t.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(r=t==null?void 0:t.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",l;const c=h=>{h.topic===e&&(this.subscriber.off(us.created,c),l())};return await Promise.all([new Promise(h=>{l=h,this.subscriber.on(us.created,c)}),new Promise(async(h,u)=>{a=await this.subscriber.subscribe(e,Sf({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&u(d)})||a,h()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Li(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(t,i)=>{await this.connect(e).then(t).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await pf())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,r)=>i.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+(r==null?void 0:r.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const r=dt(E.FIVE_MINUTES),n={topic:i,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(Et.message,e),await this.recordMessageEvent(e,pc.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(As.disconnect,n),await Li(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off(As.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const l=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(As.disconnect,l),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(As.disconnect,l)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const r=i;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(i=>setTimeout(i,E.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,r,n;if(Tc())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(i=this.provider)==null?void 0:i.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ye(new Ow(h3({sdkVersion:su,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:i,message:r}=e;await this.messages.set(i,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,i);return r&&this.logger.warn(`Ignoring duplicate message: ${i}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Kn(e)){if(!e.method.endsWith(gR))return;const t=e.params,{topic:i,message:r,publishedAt:n,attestation:o}=t.data,a={topic:i,message:r,publishedAt:n,transportType:Ke.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Sf({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else $r(e)&&this.events.emit(Et.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,pc.inbound),this.events.emit(Et.message,e))}async acknowledgePayload(e){const t=Vi(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(As.payload,this.onPayloadHandler),this.provider.off(As.connect,this.onConnectHandler),this.provider.off(As.disconnect,this.onDisconnectHandler),this.provider.off(As.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await pf();eR(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Et.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},E.toMiliseconds(fR)))))}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}}function LL(){}function $f(s){if(!s||typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(s)==="[object Object]":!1}function Pf(s){return Object.getOwnPropertySymbols(s).filter(e=>Object.prototype.propertyIsEnumerable.call(s,e))}function Tf(s){return s==null?s===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(s)}const UL="[object RegExp]",zL="[object String]",FL="[object Number]",qL="[object Boolean]",Mf="[object Arguments]",BL="[object Symbol]",HL="[object Date]",WL="[object Map]",VL="[object Set]",KL="[object Array]",GL="[object Function]",YL="[object ArrayBuffer]",Jl="[object Object]",QL="[object Error]",ZL="[object DataView]",JL="[object Uint8Array]",XL="[object Uint8ClampedArray]",eU="[object Uint16Array]",tU="[object Uint32Array]",sU="[object BigUint64Array]",iU="[object Int8Array]",rU="[object Int16Array]",nU="[object Int32Array]",oU="[object BigInt64Array]",aU="[object Float32Array]",cU="[object Float64Array]";function lU(s,e){return s===e||Number.isNaN(s)&&Number.isNaN(e)}function hU(s,e,t){return Do(s,e,void 0,void 0,void 0,void 0,t)}function Do(s,e,t,i,r,n,o){const a=o(s,e,t,i,r,n);if(a!==void 0)return a;if(typeof s==typeof e)switch(typeof s){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return s===e;case"number":return s===e||Object.is(s,e);case"function":return s===e;case"object":return Fo(s,e,n,o)}return Fo(s,e,n,o)}function Fo(s,e,t,i){if(Object.is(s,e))return!0;let r=Tf(s),n=Tf(e);if(r===Mf&&(r=Jl),n===Mf&&(n=Jl),r!==n)return!1;switch(r){case zL:return s.toString()===e.toString();case FL:{const l=s.valueOf(),c=e.valueOf();return lU(l,c)}case qL:case HL:case BL:return Object.is(s.valueOf(),e.valueOf());case UL:return s.source===e.source&&s.flags===e.flags;case GL:return s===e}t=t??new Map;const o=t.get(s),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(s,e),t.set(e,s);try{switch(r){case WL:{if(s.size!==e.size)return!1;for(const[l,c]of s.entries())if(!e.has(l)||!Do(c,e.get(l),l,s,e,t,i))return!1;return!0}case VL:{if(s.size!==e.size)return!1;const l=Array.from(s.values()),c=Array.from(e.values());for(let h=0;h<l.length;h++){const u=l[h],d=c.findIndex(p=>Do(u,p,void 0,s,e,t,i));if(d===-1)return!1;c.splice(d,1)}return!0}case KL:case JL:case XL:case eU:case tU:case sU:case iU:case rU:case nU:case oU:case aU:case cU:{if(typeof _.Buffer<"u"&&_.Buffer.isBuffer(s)!==_.Buffer.isBuffer(e)||s.length!==e.length)return!1;for(let l=0;l<s.length;l++)if(!Do(s[l],e[l],l,s,e,t,i))return!1;return!0}case YL:return s.byteLength!==e.byteLength?!1:Fo(new Uint8Array(s),new Uint8Array(e),t,i);case ZL:return s.byteLength!==e.byteLength||s.byteOffset!==e.byteOffset?!1:Fo(new Uint8Array(s),new Uint8Array(e),t,i);case QL:return s.name===e.name&&s.message===e.message;case Jl:{if(!(Fo(s.constructor,e.constructor,t,i)||$f(s)&&$f(e)))return!1;const l=[...Object.keys(s),...Pf(s)],c=[...Object.keys(e),...Pf(e)];if(l.length!==c.length)return!1;for(let h=0;h<l.length;h++){const u=l[h],d=s[u];if(!Object.hasOwn(e,u))return!1;const p=e[u];if(!Do(d,p,u,s,e,t,i))return!1}return!0}default:return!1}}finally{t.delete(s),t.delete(e)}}function uU(s,e){return hU(s,e,LL)}var dU=Object.defineProperty,Of=Object.getOwnPropertySymbols,pU=Object.prototype.hasOwnProperty,gU=Object.prototype.propertyIsEnumerable,lu=(s,e,t)=>e in s?dU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,xf=(s,e)=>{for(var t in e||(e={}))pU.call(e,t)&&lu(s,t,e[t]);if(Of)for(var t of Of(e))gU.call(e,t)&&lu(s,t,e[t]);return s},Xt=(s,e,t)=>lu(s,typeof e!="symbol"?e+"":e,t);class jr extends PD{constructor(e,t,i,r=ii,n=void 0){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,Xt(this,"map",new Map),Xt(this,"version",mR),Xt(this,"cached",[]),Xt(this,"initialized",!1),Xt(this,"getKey"),Xt(this,"storagePrefix",ii),Xt(this,"recentlyDeleted",[]),Xt(this,"recentlyDeletedLimit",200),Xt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Dt(o)?this.map.set(this.getKey(o),o):Mj(o)?this.map.set(o.id,o):Oj(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Xt(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())}),Xt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Xt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(l=>uU(a[l],o[l]))):this.values)),Xt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const l=xf(xf({},this.getData(o)),a);this.map.set(o,l),await this.persist()}),Xt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Ne(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=j("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:i}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var fU=Object.defineProperty,mU=(s,e,t)=>e in s?fU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,le=(s,e,t)=>mU(s,typeof e!="symbol"?e+"":e,t);class wU{constructor(e,t){this.core=e,this.logger=t,le(this,"name",vR),le(this,"version",IR),le(this,"events",new Wn),le(this,"pairings"),le(this,"initialized",!1),le(this,"storagePrefix",ii),le(this,"ignoredPayloadTypes",[mi]),le(this,"registeredMethods",[]),le(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),le(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),le(this,"create",async i=>{this.isInitialized();const r=eu(),n=await this.core.crypto.setSymKey(r),o=dt(E.FIVE_MINUTES),a={protocol:vb},l={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},c=af({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(lr.create,l),this.core.expirer.set(n,o),await this.pairings.set(n,l),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:c}}),le(this,"pair",async i=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[Js.pairing_started]}});this.isValidPair(i,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:l,methods:c}=of(i.uri);r.props.properties.topic=n,r.addTrace(Js.pairing_uri_validation_success),r.addTrace(Js.pairing_uri_not_expired);let h;if(this.pairings.keys.includes(n)){if(h=this.pairings.get(n),r.addTrace(Js.existing_pairing),h.active)throw r.setError(ui.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(Js.pairing_not_expired)}const u=l||dt(E.FIVE_MINUTES),d={topic:n,relay:a,expiry:u,active:!1,methods:c};this.core.expirer.set(n,u),await this.pairings.set(n,d),r.addTrace(Js.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(lr.create,d),r.addTrace(Js.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(Js.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(ui.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw r.setError(ui.subscribe_pairing_topic_failure),p}return r.addTrace(Js.subscribe_pairing_topic_success),d}),le(this,"activate",async({topic:i})=>{this.isInitialized();const r=dt(E.FIVE_MINUTES);this.core.expirer.set(i,r),await this.pairings.update(i,{active:!0,expiry:r})}),le(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=i;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:l}=or();this.events.once(Ee("pairing_ping",n),({error:c})=>{c?l(c):a()}),await o()}}),le(this,"updateExpiry",async({topic:i,expiry:r})=>{this.isInitialized(),await this.pairings.update(i,{expiry:r})}),le(this,"updateMetadata",async({topic:i,metadata:r})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:r})}),le(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),le(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:r}=i;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Me("USER_DISCONNECTED")),await this.deletePairing(r))}),le(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=i,l=this.core.crypto.keychain.get(r);return af({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:l,relay:n,expiryTimestamp:o,methods:a})}),le(this,"sendRequest",async(i,r,n)=>{const o=Gt(r,n),a=await this.core.crypto.encode(i,o),l=Ao[r].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,l),o.id}),le(this,"sendResult",async(i,r,n)=>{const o=Vi(i,n),a=await this.core.crypto.encode(r,o),l=(await this.core.history.get(r,i)).request.method,c=Ao[l].res;await this.core.relayer.publish(r,a,c),await this.core.history.resolve(o)}),le(this,"sendError",async(i,r,n)=>{const o=ca(i,n),a=await this.core.crypto.encode(r,o),l=(await this.core.history.get(r,i)).request.method,c=Ao[l]?Ao[l].res:Ao.unregistered_method.res;await this.core.relayer.publish(r,a,c),await this.core.history.resolve(o)}),le(this,"deletePairing",async(i,r)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Me("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),r?Promise.resolve():this.core.expirer.del(i)])}),le(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(r=>Ti(r.expiry));await Promise.all(i.map(r=>this.deletePairing(r.topic)))}),le(this,"onRelayEventRequest",async i=>{const{topic:r,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,n);default:return await this.onUnknownRpcMethodRequest(r,n)}}),le(this,"onRelayEventResponse",async i=>{const{topic:r,payload:n}=i,o=(await this.core.history.get(r,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,n);default:return this.onUnknownRpcMethodResponse(o)}}),le(this,"onPairingPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(lr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),le(this,"onPairingPingResponse",(i,r)=>{const{id:n}=r;setTimeout(()=>{vt(r)?this.events.emit(Ee("pairing_ping",n),{}):st(r)&&this.events.emit(Ee("pairing_ping",n),{error:r.error})},500)}),le(this,"onPairingDeleteRequest",async(i,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(lr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),le(this,"onUnknownRpcMethodRequest",async(i,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Me("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),le(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(Me("WC_METHOD_UNSUPPORTED",i))}),le(this,"isValidPair",(i,r)=>{var n;if(!rs(i)){const{message:a}=j("MISSING_OR_INVALID",`pair() params: ${i}`);throw r.setError(ui.malformed_pairing_uri),new Error(a)}if(!Tj(i.uri)){const{message:a}=j("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw r.setError(ui.malformed_pairing_uri),new Error(a)}const o=of(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=j("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(ui.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=j("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(ui.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&E.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(ui.pairing_expired);const{message:a}=j("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),le(this,"isValidPing",async i=>{if(!rs(i)){const{message:n}=j("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),le(this,"isValidDisconnect",async i=>{if(!rs(i)){const{message:n}=j("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),le(this,"isValidPairingTopic",async i=>{if(!at(i,!1)){const{message:r}=j("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(r)}if(!this.pairings.keys.includes(i)){const{message:r}=j("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(r)}if(Ti(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:r}=j("EXPIRED",`pairing topic: ${i}`);throw new Error(r)}}),this.core=e,this.logger=Ne(t,this.name),this.pairings=new jr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return qe(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Et.message,async e=>{const{topic:t,message:i,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==Ke.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(t,i);Kn(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):$r(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(Ss.expired,async e=>{const{topic:t}=Wy(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(lr.expire,{topic:t}))})}}var yU=Object.defineProperty,bU=(s,e,t)=>e in s?yU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Tt=(s,e,t)=>bU(s,typeof e!="symbol"?e+"":e,t);class vU extends _D{constructor(e,t){super(e,t),this.core=e,this.logger=t,Tt(this,"records",new Map),Tt(this,"events",new kt.EventEmitter),Tt(this,"name",ER),Tt(this,"version",AR),Tt(this,"cached",[]),Tt(this,"initialized",!1),Tt(this,"storagePrefix",ii),Tt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Tt(this,"set",(i,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:i,request:{method:r.method,params:r.params||null},chainId:n,expiry:dt(E.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(js.created,o)}),Tt(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const r=await this.getRecord(i.id);typeof r.response>"u"&&(r.response=st(i)?{error:i.error}:{result:i.result},this.records.set(r.id,r),this.persist(),this.events.emit(js.updated,r))}),Tt(this,"get",async(i,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:r}),await this.getRecord(r))),Tt(this,"delete",(i,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===i){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(js.deleted,n)}}),this.persist()}),Tt(this,"exists",async(i,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===i:!1)),Tt(this,"on",(i,r)=>{this.events.on(i,r)}),Tt(this,"once",(i,r)=>{this.events.once(i,r)}),Tt(this,"off",(i,r)=>{this.events.off(i,r)}),Tt(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=Ne(t,this.name)}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:Gt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(js.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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(js.created,e=>{const t=js.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(js.updated,e=>{const t=js.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(js.deleted,e=>{const t=js.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(qs.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{E.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(js.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var IU=Object.defineProperty,EU=(s,e,t)=>e in s?IU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ft=(s,e,t)=>EU(s,typeof e!="symbol"?e+"":e,t);class AU extends MD{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ft(this,"expirations",new Map),Ft(this,"events",new kt.EventEmitter),Ft(this,"name",NR),Ft(this,"version",_R),Ft(this,"cached",[]),Ft(this,"initialized",!1),Ft(this,"storagePrefix",ii),Ft(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ft(this,"has",i=>{try{const r=this.formatTarget(i);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ft(this,"set",(i,r)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(Ss.created,{target:n,expiration:o})}),Ft(this,"get",i=>{this.isInitialized();const r=this.formatTarget(i);return this.getExpiration(r)}),Ft(this,"del",i=>{if(this.isInitialized(),this.has(i)){const r=this.formatTarget(i),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Ss.deleted,{target:r,expiration:n})}}),Ft(this,"on",(i,r)=>{this.events.on(i,r)}),Ft(this,"once",(i,r)=>{this.events.once(i,r)}),Ft(this,"off",(i,r)=>{this.events.off(i,r)}),Ft(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=Ne(t,this.name)}get context(){return qe(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 u3(e);if(typeof e=="number")return d3(e);const{message:t}=j("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Ss.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:i}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;E.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Ss.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(qs.pulse,()=>this.checkExpirations()),this.events.on(Ss.created,e=>{const t=Ss.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Ss.expired,e=>{const t=Ss.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Ss.deleted,e=>{const t=Ss.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var NU=Object.defineProperty,_U=(s,e,t)=>e in s?NU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,nt=(s,e,t)=>_U(s,typeof e!="symbol"?e+"":e,t);class CU extends OD{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,nt(this,"name",CR),nt(this,"abortController"),nt(this,"isDevEnv"),nt(this,"verifyUrlV3",$R),nt(this,"storagePrefix",ii),nt(this,"version",bb),nt(this,"publicKey"),nt(this,"fetchPromise"),nt(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&E.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),nt(this,"register",async r=>{if(!Ia()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=r,l=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const c=Wi(),h=this.startAbortTimer(E.ONE_SECOND*5),u=await new Promise((d,p)=>{const g=()=>{window.removeEventListener("message",y),c.body.removeChild(f),p("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const f=c.createElement("iframe");f.src=l,f.style.display="none",f.addEventListener("error",g,{signal:this.abortController.signal});const y=w=>{if(w.data&&typeof w.data=="string")try{const m=JSON.parse(w.data);if(m.type==="verify_attestation"){if(jn(m.attestation).payload.id!==o)return;clearInterval(h),c.body.removeChild(f),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",y),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};c.body.appendChild(f),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(c){this.logger.warn(c)}return""}),nt(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(jn(n).payload.id!==a)return;const c=await this.isValidJwtAttestation(n);if(c){if(!c.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return c}}if(!o)return;const l=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,l)}),nt(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(E.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),nt(this,"getVerifyUrl",r=>{let n=r||zo;return PR.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${zo}`),n=zo),n}),nt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(E.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),nt(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),nt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),nt(this,"isValidJwtAttestation",async r=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(r,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),nt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),nt(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),nt(this,"validateAttestation",(r,n)=>{const o=wj(r,n.publicKey),a={hasExpired:E.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ne(t,this.name),this.abortController=new AbortController,this.isDevEnv=Fu(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return qe(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),E.toMiliseconds(e))}}var SU=Object.defineProperty,$U=(s,e,t)=>e in s?SU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Df=(s,e,t)=>$U(s,typeof e!="symbol"?e+"":e,t);class PU extends xD{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Df(this,"context",TR),Df(this,"registerDeviceToken",async i=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=i,l=`${MR}/${this.projectId}/clients`;await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=Ne(t,this.context)}}var TU=Object.defineProperty,kf=Object.getOwnPropertySymbols,MU=Object.prototype.hasOwnProperty,OU=Object.prototype.propertyIsEnumerable,hu=(s,e,t)=>e in s?TU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Co=(s,e)=>{for(var t in e||(e={}))MU.call(e,t)&&hu(s,t,e[t]);if(kf)for(var t of kf(e))OU.call(e,t)&&hu(s,t,e[t]);return s},mt=(s,e,t)=>hu(s,typeof e!="symbol"?e+"":e,t);class xU extends DD{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,mt(this,"context",xR),mt(this,"storagePrefix",ii),mt(this,"storageVersion",OR),mt(this,"events",new Map),mt(this,"shouldPersist",!1),mt(this,"init",async()=>{if(!Fu())try{const r={eventId:Og(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:By(this.core.relayer.protocol,this.core.relayer.version,su)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),mt(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:l}}=r,c=Og(),h=this.core.projectId||"",u=Date.now(),d=Co({eventId:c,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:l}},bundleId:h,domain:this.getAppDomain()},this.setMethods(c));return this.telemetryEnabled&&(this.events.set(c,d),this.shouldPersist=!0),d}),mt(this,"getEvent",r=>{const{eventId:n,topic:o}=r;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(l=>l.props.properties.topic===o);if(a)return Co(Co({},a),this.setMethods(a.eventId))}),mt(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),mt(this,"setEventListeners",()=>{this.core.heartbeat.on(qs.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{E.fromMiliseconds(Date.now())-E.fromMiliseconds(r.timestamp)>DR&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),mt(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),mt(this,"addTrace",(r,n)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(n),this.events.set(r,o),this.shouldPersist=!0)}),mt(this,"setError",(r,n)=>{const o=this.events.get(r);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),mt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),mt(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(n=>{this.events.set(n.eventId,Co(Co({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),mt(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[n,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const n of r)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),mt(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${kR}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${su}${n}`,{method:"POST",body:JSON.stringify(r)})}),mt(this,"getAppDomain",()=>qy().url),this.logger=Ne(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var DU=Object.defineProperty,jf=Object.getOwnPropertySymbols,kU=Object.prototype.hasOwnProperty,jU=Object.prototype.propertyIsEnumerable,uu=(s,e,t)=>e in s?DU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Rf=(s,e)=>{for(var t in e||(e={}))kU.call(e,t)&&uu(s,t,e[t]);if(jf)for(var t of jf(e))jU.call(e,t)&&uu(s,t,e[t]);return s},Le=(s,e,t)=>uu(s,typeof e!="symbol"?e+"":e,t);let RU=class xb extends ID{constructor(e){var t;super(e),Le(this,"protocol",yb),Le(this,"version",bb),Le(this,"name",tu),Le(this,"relayUrl"),Le(this,"projectId"),Le(this,"customStoragePrefix"),Le(this,"events",new kt.EventEmitter),Le(this,"logger"),Le(this,"heartbeat"),Le(this,"relayer"),Le(this,"crypto"),Le(this,"storage"),Le(this,"history"),Le(this,"expirer"),Le(this,"pairing"),Le(this,"verify"),Le(this,"echoClient"),Le(this,"linkModeSupportedApps"),Le(this,"eventClient"),Le(this,"initialized",!1),Le(this,"logChunkController"),Le(this,"on",(o,a)=>this.events.on(o,a)),Le(this,"once",(o,a)=>this.events.once(o,a)),Le(this,"off",(o,a)=>this.events.off(o,a)),Le(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),Le(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:l})=>{if(!o||!a)return;const c={topic:o,message:a,publishedAt:Date.now(),transportType:Ke.link_mode};this.relayer.onLinkMessageEvent(c,{sessionExists:l})}),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Ib,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=yi({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:iR.logger,name:tu}),{logger:r,chunkLoggerController:n}=Au({opts:i,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=n,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,a;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((a=this.logChunkController)==null||a.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ne(r,this.name),this.heartbeat=new jm,this.crypto=new hL(this,this.logger,e==null?void 0:e.keychain),this.history=new vU(this,this.logger),this.expirer=new AU(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new uk(Rf(Rf({},rR),e==null?void 0:e.storageOptions)),this.relayer=new RL({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new wU(this,this.logger),this.verify=new CU(this,this.logger,this.storage),this.echoClient=new PU(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new xU(this,this.logger,e==null?void 0:e.telemetryEnabled)}static async init(e){const t=new xb(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(wR,i),t}get context(){return qe(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(mf,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(mf)||[],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}}};const LU=RU,Db="wc",kb=2,jb="client",Qu=`${Db}@${kb}:${jb}:`,Xl={name:jb,logger:"error"},Lf="WALLETCONNECT_DEEPLINK_CHOICE",UU="proposal",Uf="Proposal expired",zU="session",on=E.SEVEN_DAYS,FU="engine",wt={wc_sessionPropose:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1104},res:{ttl:E.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1106},res:{ttl:E.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1112},res:{ttl:E.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1114},res:{ttl:E.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:E.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:E.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1119}}},eh={min:E.FIVE_MINUTES,max:E.SEVEN_DAYS},Qs={idle:"IDLE",active:"ACTIVE"},zf={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},qU="request",BU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],HU="wc",WU="auth",VU="authKeys",KU="pairingTopics",GU="requests",ol=`${HU}@${1.5}:${WU}:`,gc=`${ol}:PUB_KEY`;var YU=Object.defineProperty,QU=Object.defineProperties,ZU=Object.getOwnPropertyDescriptors,Ff=Object.getOwnPropertySymbols,JU=Object.prototype.hasOwnProperty,XU=Object.prototype.propertyIsEnumerable,du=(s,e,t)=>e in s?YU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,De=(s,e)=>{for(var t in e||(e={}))JU.call(e,t)&&du(s,t,e[t]);if(Ff)for(var t of Ff(e))XU.call(e,t)&&du(s,t,e[t]);return s},Wt=(s,e)=>QU(s,ZU(e)),M=(s,e,t)=>du(s,typeof e!="symbol"?e+"":e,t);class ez extends LD{constructor(e){super(e),M(this,"name",FU),M(this,"events",new Wn),M(this,"initialized",!1),M(this,"requestQueue",{state:Qs.idle,queue:[]}),M(this,"sessionRequestQueue",{state:Qs.idle,queue:[]}),M(this,"requestQueueDelay",E.ONE_SECOND),M(this,"expectedPairingMethodMap",new Map),M(this,"recentlyDeletedMap",new Map),M(this,"recentlyDeletedLimit",200),M(this,"relayMessageCache",[]),M(this,"pendingSessions",new Map),M(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(wt)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},E.toMiliseconds(this.requestQueueDelay)))}),M(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Wt(De({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:l,relays:c}=i;let h=r,u,d=!1;try{if(h){const $=this.client.core.pairing.pairings.get(h);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(${h}) failed`),$}if(!h||!d){const{topic:$,uri:P}=await this.client.core.pairing.create();h=$,u=P}if(!h){const{message:$}=j("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error($)}const p=await this.client.core.crypto.generateKeyPair(),g=wt.wc_sessionPropose.req.ttl||E.FIVE_MINUTES,f=dt(g),y=Wt(De(De({requiredNamespaces:n,optionalNamespaces:o,relays:c??[{protocol:vb}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:f,pairingTopic:h},a&&{sessionProperties:a}),l&&{scopedProperties:l}),{id:qt()}),w=Ee("session_connect",y.id),{reject:m,resolve:b,done:I}=or(g,Uf),N=({id:$})=>{$===y.id&&(this.client.events.off("proposal_expire",N),this.pendingSessions.delete(y.id),this.events.emit(w,{error:{message:Uf,code:0}}))};return this.client.events.on("proposal_expire",N),this.events.once(w,({error:$,session:P})=>{this.client.events.off("proposal_expire",N),$?m($):P&&b(P)}),await this.sendRequest({topic:h,method:"wc_sessionPropose",params:y,throwOnFailedPublish:!0,clientRpcId:y.id}),await this.setProposal(y.id,y),{uri:u,approval:I}}),M(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}}),M(this,"approve",async t=>{var i,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=t==null?void 0:t.id)==null?void 0:i.toString(),trace:[Rs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(C){throw o.setError(tr.no_internet_connection),C}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(C){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(tr.proposal_not_found),C}try{await this.isValidApprove(t)}catch(C){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(tr.session_approve_namespace_validation_failure),C}const{id:a,relayProtocol:l,namespaces:c,sessionProperties:h,scopedProperties:u,sessionConfig:d}=t,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:f,requiredNamespaces:y,optionalNamespaces:w}=p;let m=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});m||(m=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Rs.session_approve_started,properties:{topic:g,trace:[Rs.session_approve_started,Rs.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),I=f.publicKey,N=await this.client.core.crypto.generateSharedKey(b,I),$=De(De(De({relay:{protocol:l??"irn"},namespaces:c,controller:{publicKey:b,metadata:this.client.metadata},expiry:dt(on)},h&&{sessionProperties:h}),u&&{scopedProperties:u}),d&&{sessionConfig:d}),P=Ke.relay;m.addTrace(Rs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(N,{transportType:P})}catch(C){throw m.setError(tr.subscribe_session_topic_failure),C}m.addTrace(Rs.subscribe_session_topic_success);const O=Wt(De({},$),{topic:N,requiredNamespaces:y,optionalNamespaces:w,pairingTopic:g,acknowledged:!1,self:$.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:b,transportType:Ke.relay});await this.client.session.set(N,O),m.addTrace(Rs.store_session);try{m.addTrace(Rs.publishing_session_settle),await this.sendRequest({topic:N,method:"wc_sessionSettle",params:$,throwOnFailedPublish:!0}).catch(C=>{throw m==null||m.setError(tr.session_settle_publish_failure),C}),m.addTrace(Rs.session_settle_publish_success),m.addTrace(Rs.publishing_session_approve),await this.sendResult({id:a,topic:g,result:{relay:{protocol:l??"irn"},responderPublicKey:b},throwOnFailedPublish:!0}).catch(C=>{throw m==null||m.setError(tr.session_approve_publish_failure),C}),m.addTrace(Rs.session_approve_publish_success)}catch(C){throw this.client.logger.error(C),this.client.session.delete(N,Me("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(N),C}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:f.metadata}),await this.client.proposal.delete(a,Me("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(N,dt(on)),{topic:N,acknowledged:()=>Promise.resolve(this.client.session.get(N))}}),M(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:r}=t;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&(await this.sendError({id:i,topic:n,error:r,rpcOpts:wt.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Me("USER_DISCONNECTED")))}),M(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:i,namespaces:r}=t,{done:n,resolve:o,reject:a}=or(),l=qt(),c=gs().toString(),h=this.client.session.get(i).namespaces;return this.events.once(Ee("session_update",l),({error:u})=>{u?a(u):o()}),await this.client.session.update(i,{namespaces:r}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:l,relayRpcId:c}).catch(u=>{this.client.logger.error(u),this.client.session.update(i,{namespaces:h}),a(u)}),{acknowledged:n}}),M(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(l){throw this.client.logger.error("extend() -> isValidExtend() failed"),l}const{topic:i}=t,r=qt(),{done:n,resolve:o,reject:a}=or();return this.events.once(Ee("session_extend",r),({error:l})=>{l?a(l):o()}),await this.setExpiry(i,dt(on)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(l=>{a(l)}),{acknowledged:n}}),M(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:i,request:r,topic:n,expiry:o=wt.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===Ke.relay&&await this.confirmOnlineStateOrThrow();const l=qt(),c=gs().toString(),{done:h,resolve:u,reject:d}=or(o,"Request expired. Please try again.");this.events.once(Ee("session_request",l),({error:w,result:m})=>{w?d(w):u(m)});const p="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:l,relayRpcId:c,topic:n,method:p,params:{request:Wt(De({},r),{expiryTimestamp:dt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:l}),await h();const f={request:Wt(De({},r),{expiryTimestamp:dt(o)}),chainId:i},y=this.shouldSetTVF(p,f);return await Promise.all([new Promise(async w=>{await this.sendRequest(De({clientRpcId:l,relayRpcId:c,topic:n,method:p,params:f,expiry:o,throwOnFailedPublish:!0},y&&{tvf:this.getTVFParams(l,f)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:l}),w()}),new Promise(async w=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const b=await m3(this.client.core.storage,Lf);await p3({id:l,topic:n,wcDeepLink:b})}w()}),h()]).then(w=>w[2])}),M(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:r}=t,{id:n}=r,o=this.client.session.get(i);o.transportType===Ke.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);vt(r)?await this.sendResult({id:n,topic:i,result:r.result,throwOnFailedPublish:!0,appLink:a}):st(r)&&await this.sendError({id:n,topic:i,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),M(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:i}=t;if(this.client.session.keys.includes(i)){const r=qt(),n=gs().toString(),{done:o,resolve:a,reject:l}=or();this.events.once(Ee("session_ping",r),({error:c})=>{c?l(c):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),M(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:r,chainId:n}=t,o=gs().toString(),a=qt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),M(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Me("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:r}=j("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(r)}}),M(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(i=>$j(i,t)))),M(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),M(this,"authenticate",async(t,i)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?Ke.link_mode:Ke.relay;o===Ke.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:l="",uri:c,domain:h,nonce:u,type:d,exp:p,nbf:g,methods:f=[],expiry:y}=t,w=[...t.resources||[]],{topic:m,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:b}});const I=await this.client.core.crypto.generateKeyPair(),N=dc(I);if(await Promise.all([this.client.auth.authKeys.set(gc,{responseTopic:N,publicKey:I}),this.client.auth.pairingTopics.set(N,{topic:N,pairingTopic:m})]),await this.client.core.relayer.subscribe(N,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),f.length>0){const{namespace:A}=xn(a[0]);let z=a4(A,"request",f);uc(w)&&(z=l4(z,w.pop())),w.push(z)}const $=y&&y>wt.wc_sessionAuthenticate.req.ttl?y:wt.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:d??"caip122",chains:a,statement:l,aud:c,domain:h,version:"1",nonce:u,iat:new Date().toISOString(),exp:p,nbf:g,resources:w},requester:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:dt($)},O={eip155:{chains:a,methods:[...new Set(["personal_sign",...f])],events:["chainChanged","accountsChanged"]}},C={requiredNamespaces:{},optionalNamespaces:O,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:dt(wt.wc_sessionPropose.req.ttl),id:qt()},{done:T,resolve:S,reject:R}=or($,"Request expired"),L=qt(),q=Ee("session_connect",C.id),B=Ee("session_request",L),U=async({error:A,session:z})=>{this.events.off(B,H),A?R(A):z&&S({session:z})},H=async A=>{var z,Y,K;if(await this.deletePendingAuthRequest(L,{message:"fulfilled",code:0}),A.error){const He=Me("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return A.error.code===He.code?void 0:(this.events.off(q,U),R(A.error.message))}await this.deleteProposal(C.id),this.events.off(q,U);const{cacaos:be,responder:oe}=A.result,Oe=[],lt=[];for(const He of be){await zg({cacao:He,projectId:this.client.core.projectId})||(this.client.logger.error(He,"Signature verification failed"),R(Me("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Qi}=He,Zi=uc(Qi.resources),so=[Gh(Qi.iss)],cl=Mc(Qi.iss);if(Zi){const Ji=Fg(Zi),ll=qg(Zi);Oe.push(...Ji),so.push(...ll)}for(const Ji of so)lt.push(`${Ji}:${cl}`)}const Be=await this.client.core.crypto.generateSharedKey(I,oe.publicKey);let Qe;Oe.length>0&&(Qe={topic:Be,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:oe,controller:oe.publicKey,expiry:dt(on),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:cf([...new Set(Oe)],[...new Set(lt)]),transportType:o},await this.client.core.relayer.subscribe(Be,{transportType:o}),await this.client.session.set(Be,Qe),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:oe.metadata}),Qe=this.client.session.get(Be)),(z=this.client.metadata.redirect)!=null&&z.linkMode&&(Y=oe.metadata.redirect)!=null&&Y.linkMode&&(K=oe.metadata.redirect)!=null&&K.universal&&i&&(this.client.core.addLinkModeSupportedApp(oe.metadata.redirect.universal),this.client.session.update(Be,{transportType:Ke.link_mode})),S({auths:be,session:Qe})};this.events.once(q,U),this.events.once(B,H);let W;try{if(n){const A=Gt("wc_sessionAuthenticate",P,L);this.client.core.history.set(m,A);const z=await this.client.core.crypto.encode("",A,{type:_a,encoding:Io});W=Ga(i,m,z)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:P,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:L}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:C,expiry:wt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:C.id})])}catch(A){throw this.events.off(q,U),this.events.off(B,H),A}return await this.setProposal(C.id,C),await this.setAuthRequest(L,{request:Wt(De({},P),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:W??b,response:T}}),M(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[sr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw n.setError(No.no_internet_connection),y}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(No.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Ke.relay;a===Ke.relay&&await this.confirmOnlineStateOrThrow();const l=o.requester.publicKey,c=await this.client.core.crypto.generateKeyPair(),h=dc(l),u={type:mi,receiverPublicKey:l,senderPublicKey:c},d=[],p=[];for(const y of r){if(!await zg({cacao:y,projectId:this.client.core.projectId})){n.setError(No.invalid_cacao);const N=Me("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:h,error:N,encodeOpts:u}),new Error(N.message)}n.addTrace(sr.cacaos_verified);const{p:w}=y,m=uc(w.resources),b=[Gh(w.iss)],I=Mc(w.iss);if(m){const N=Fg(m),$=qg(m);d.push(...N),b.push(...$)}for(const N of b)p.push(`${N}:${I}`)}const g=await this.client.core.crypto.generateSharedKey(c,l);n.addTrace(sr.create_authenticated_session_topic);let f;if((d==null?void 0:d.length)>0){f={topic:g,acknowledged:!0,self:{publicKey:c,metadata:this.client.metadata},peer:{publicKey:l,metadata:o.requester.metadata},controller:l,expiry:dt(on),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:cf([...new Set(d)],[...new Set(p)]),transportType:a},n.addTrace(sr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(y){throw n.setError(No.subscribe_authenticated_session_topic_failure),y}n.addTrace(sr.subscribe_authenticated_session_topic_success),await this.client.session.set(g,f),n.addTrace(sr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(sr.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:i,result:{cacaos:r,responder:{publicKey:c,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw n.setError(No.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:f}}),M(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:i,reason:r}=t,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===Ke.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),l=dc(o),c={type:mi,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:l,error:r,encodeOpts:c,rpcOpts:wt.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Me("USER_DISCONNECTED"))}),M(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:r}=t;return eb(i,r)}),M(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),M(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),r=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)===t.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),M(this,"deleteSession",async t=>{var i;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:l}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Me("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(l.publicKey)&&await this.client.core.crypto.deleteKeyPair(l.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Lf).catch(c=>this.client.logger.warn(c)),this.getPendingSessionRequests().forEach(c=>{c.topic===r&&this.deletePendingSessionRequest(c.id,Me("USER_DISCONNECTED"))}),r===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Qs.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),M(this,"deleteProposal",async(t,i)=>{if(i)try{const r=this.client.proposal.get(t),n=this.client.core.eventClient.getEvent({topic:r.pairingTopic});n==null||n.setError(tr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Me("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),M(this,"deletePendingSessionRequest",async(t,i,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==t),r&&(this.sessionRequestQueue.state=Qs.idle,this.client.events.emit("session_request_expire",{id:t}))}),M(this,"deletePendingAuthRequest",async(t,i,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)])}),M(this,"setExpiry",async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))}),M(this,"setProposal",async(t,i)=>{this.client.core.expirer.set(t,dt(wt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),M(this,"setAuthRequest",async(t,i)=>{const{request:r,pairingTopic:n,transportType:o=Ke.relay}=i;this.client.core.expirer.set(t,r.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:t,pairingTopic:n,verifyContext:r.verifyContext,transportType:o})}),M(this,"setPendingSessionRequest",async t=>{const{id:i,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||dt(wt.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:r,params:n,verifyContext:o})}),M(this,"sendRequest",async t=>{const{topic:i,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:l,throwOnFailedPublish:c,appLink:h,tvf:u}=t,d=Gt(r,n,l);let p;const g=!!h;try{const w=g?Io:Ui;p=await this.client.core.crypto.encode(i,d,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),w}let f;if(BU.includes(r)){const w=Xs(JSON.stringify(d)),m=Xs(p);f=await this.client.core.verify.register({id:m,decryptedId:w})}const y=wt[r].req;if(y.attestation=f,o&&(y.ttl=o),a&&(y.id=a),this.client.core.history.set(i,d),g){const w=Ga(h,i,p);await _.global.Linking.openURL(w,this.client.name)}else{const w=wt[r].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=Wt(De({},u),{correlationId:d.id}),c?(w.internal=Wt(De({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,w)):this.client.core.relayer.publish(i,p,w).catch(m=>this.client.logger.error(m))}return d.id}),M(this,"sendResult",async t=>{const{id:i,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:l}=t,c=Vi(i,n);let h;const u=l&&typeof(_.global==null?void 0:_.global.Linking)<"u";try{const g=u?Io:Ui;h=await this.client.core.crypto.encode(r,c,Wt(De({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let d,p;try{d=await this.client.core.history.get(r,i);const g=d.request;try{this.shouldSetTVF(g.method,g.params)&&(p=this.getTVFParams(i,g.params,n))}catch(f){this.client.logger.warn("sendResult() -> getTVFParams() failed",f)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${i}) failed`),g}if(u){const g=Ga(l,r,h);await _.global.Linking.openURL(g,this.client.name)}else{const g=d.request.method,f=wt[g].res;f.tvf=Wt(De({},p),{correlationId:i}),o?(f.internal=Wt(De({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,h,f)):this.client.core.relayer.publish(r,h,f).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(c)}),M(this,"sendError",async t=>{const{id:i,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:l}=t,c=ca(i,n);let h;const u=l&&typeof(_.global==null?void 0:_.global.Linking)<"u";try{const p=u?Io:Ui;h=await this.client.core.crypto.encode(r,c,Wt(De({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),p}let d;try{d=await this.client.core.history.get(r,i)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${r}, ${i}) failed`),p}if(u){const p=Ga(l,r,h);await _.global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,g=a||wt[p].res;this.client.core.relayer.publish(r,h,g)}await this.client.core.history.resolve(c)}),M(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(r=>{let n=!1;Ti(r.expiry)&&(n=!0),this.client.core.crypto.keychain.has(r.topic)||(n=!0),n&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{Ti(r.expiryTimestamp)&&i.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...i.map(r=>this.deleteProposal(r))])}),M(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),M(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),M(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Qs.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=Qs.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Qs.idle}),M(this,"processRequest",async t=>{const{topic:i,payload:r,attestation:n,transportType:o,encryptedId:a}=t,l=r.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:l}))switch(l){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,r);case"wc_sessionPing":return await this.onSessionPingRequest(i,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${l}`)}}),M(this,"onRelayEventResponse",async t=>{const{topic:i,payload:r,transportType:n}=t,o=(await this.client.core.history.get(i,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,r);case"wc_sessionExtend":return this.onSessionExtendResponse(i,r);case"wc_sessionPing":return this.onSessionPingResponse(i,r);case"wc_sessionRequest":return this.onSessionRequestResponse(i,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),M(this,"onRelayEventUnknownPayload",t=>{const{topic:i}=t,{message:r}=j("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),M(this,"shouldIgnorePairingRequest",t=>{const{topic:i,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),M(this,"onSessionProposeRequest",async t=>{const{topic:i,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:l}=r;try{const c=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),c==null||c.setError(ui.proposal_listener_not_found)),this.isValidConnect(De({},r.params));const h=a.expiryTimestamp||dt(wt.wc_sessionPropose.req.ttl),u=De({id:l,pairingTopic:i,expiryTimestamp:h},a);await this.setProposal(l,u);const d=await this.getVerifyContext({attestationId:n,hash:Xs(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});c==null||c.addTrace(Js.emit_session_proposal),this.client.events.emit("session_proposal",{id:l,params:u,verifyContext:d})}catch(c){await this.sendError({id:l,topic:i,error:c,rpcOpts:wt.wc_sessionPropose.autoReject}),this.client.logger.error(c)}}),M(this,"onSessionProposeResponse",async(t,i,r)=>{const{id:n}=i;if(vt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const l=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const c=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:c});const h=await this.client.core.crypto.generateSharedKey(l,c);this.pendingSessions.set(n,{sessionTopic:h,pairingTopic:t,proposalId:n,publicKey:l});const u=await this.client.core.relayer.subscribe(h,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(st(i)){await this.client.proposal.delete(n,Me("USER_DISCONNECTED"));const o=Ee("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),M(this,"onSessionSettleRequest",async(t,i)=>{const{id:r,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:l,namespaces:c,sessionProperties:h,scopedProperties:u,sessionConfig:d}=i.params,p=[...this.pendingSessions.values()].find(y=>y.sessionTopic===t);if(!p)return this.client.logger.error(`Pending session not found for topic ${t}`);const g=this.client.proposal.get(p.proposalId),f=Wt(De(De(De({topic:t,relay:o,expiry:l,namespaces:c,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},h&&{sessionProperties:h}),u&&{scopedProperties:u}),d&&{sessionConfig:d}),{transportType:Ke.relay});await this.client.session.set(f.topic,f),await this.setExpiry(f.topic,f.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:f.peer.metadata}),this.client.events.emit("session_connect",{session:f}),this.events.emit(Ee("session_connect",p.proposalId),{session:f}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(f),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),M(this,"onSessionSettleResponse",async(t,i)=>{const{id:r}=i;vt(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Ee("session_approve",r),{})):st(i)&&(await this.client.session.delete(t,Me("USER_DISCONNECTED")),this.events.emit(Ee("session_approve",r),{error:i.error}))}),M(this,"onSessionUpdateRequest",async(t,i)=>{const{params:r,id:n}=i;try{const o=`${t}_session_update`,a=Eo.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:t,error:Me("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(De({topic:t},r));try{Eo.set(o,n),await this.client.session.update(t,{namespaces:r.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(l){throw Eo.delete(o),l}this.client.events.emit("session_update",{id:n,topic:t,params:r})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}}),M(this,"isRequestOutOfSync",(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3)),M(this,"onSessionUpdateResponse",(t,i)=>{const{id:r}=i,n=Ee("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ee("session_update",r),{}):st(i)&&this.events.emit(Ee("session_update",r),{error:i.error})}),M(this,"onSessionExtendRequest",async(t,i)=>{const{id:r}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,dt(on)),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),M(this,"onSessionExtendResponse",(t,i)=>{const{id:r}=i,n=Ee("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ee("session_extend",r),{}):st(i)&&this.events.emit(Ee("session_extend",r),{error:i.error})}),M(this,"onSessionPingRequest",async(t,i)=>{const{id:r}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),M(this,"onSessionPingResponse",(t,i)=>{const{id:r}=i,n=Ee("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);vt(i)?this.events.emit(Ee("session_ping",r),{}):st(i)&&this.events.emit(Ee("session_ping",r),{error:i.error})},500)}),M(this,"onSessionDeleteRequest",async(t,i)=>{const{id:r}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(Et.publish,async()=>{n(await this.deleteSession({topic:t,id:r}))})}),this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Me("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),M(this,"onSessionRequest",async t=>{var i,r,n;const{topic:o,payload:a,attestation:l,encryptedId:c,transportType:h}=t,{id:u,params:d}=a;try{await this.isValidRequest(De({topic:o},d));const p=this.client.session.get(o),g=await this.getVerifyContext({attestationId:l,hash:Xs(JSON.stringify(Gt("wc_sessionRequest",d,u))),encryptedId:c,metadata:p.peer.metadata,transportType:h}),f={id:u,topic:o,params:d,verifyContext:g};await this.setPendingSessionRequest(f),h===Ke.link_mode&&(i=p.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((r=p.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(p){await this.sendError({id:u,topic:o,error:p}),this.client.logger.error(p)}}),M(this,"onSessionRequestResponse",(t,i)=>{const{id:r}=i,n=Ee("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ee("session_request",r),{result:i.result}):st(i)&&this.events.emit(Ee("session_request",r),{error:i.error})}),M(this,"onSessionEventRequest",async(t,i)=>{const{id:r,params:n}=i;try{const o=`${t}_session_event_${n.event.name}`,a=Eo.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(De({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),Eo.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),M(this,"onSessionAuthenticateResponse",(t,i)=>{const{id:r}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),vt(i)?this.events.emit(Ee("session_request",r),{result:i.result}):st(i)&&this.events.emit(Ee("session_request",r),{error:i.error})}),M(this,"onSessionAuthenticateRequest",async t=>{var i;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:l}=t;try{const{requester:c,authPayload:h,expiryTimestamp:u}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Xs(JSON.stringify(n)),encryptedId:a,metadata:c.metadata,transportType:l}),p={requester:c,pairingTopic:r,id:n.id,authPayload:h,verifyContext:d,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:p,pairingTopic:r,transportType:l}),l===Ke.link_mode&&(i=c.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:d})}catch(c){this.client.logger.error(c);const h=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,l),p={type:mi,receiverPublicKey:h,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:c,encodeOpts:p,rpcOpts:wt.wc_sessionAuthenticate.autoReject,appLink:d})}}),M(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),M(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Qs.idle,this.processSessionRequestQueue()},E.toMiliseconds(this.requestQueueDelay))}),M(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:i})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=Ee("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Ee("session_request",n.request.id),{error:i})})}),M(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Qs.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Qs.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}}),M(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),M(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:Gt("wc_sessionPropose",Wt(De({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id)})}),M(this,"isValidConnect",async t=>{if(!rs(t)){const{message:c}=j("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(c)}const{pairingTopic:i,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:l}=t;if(Dt(i)||await this.isValidPairingTopic(i),!zj(l)){const{message:c}=j("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(c)}if(!Dt(r)&&ra(r)!==0&&this.validateNamespaces(r,"requiredNamespaces"),!Dt(n)&&ra(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Dt(o)||this.validateSessionProps(o,"sessionProperties"),!Dt(a)){this.validateSessionProps(a,"scopedProperties");const c=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(h=>c.includes(h)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(c)}`)}}),M(this,"validateNamespaces",(t,i)=>{const r=Uj(t,"connect()",i);if(r)throw new Error(r.message)}),M(this,"isValidApprove",async t=>{if(!rs(t))throw new Error(j("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:r,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const l=this.client.proposal.get(i),c=Kl(r,"approve()");if(c)throw new Error(c.message);const h=uf(l.requiredNamespaces,r,"approve()");if(h)throw new Error(h.message);if(!at(n,!0)){const{message:u}=j("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(Dt(o)||this.validateSessionProps(o,"sessionProperties"),!Dt(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(d=>u.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),M(this,"isValidReject",async t=>{if(!rs(t)){const{message:n}=j("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:r}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!qj(r)){const{message:n}=j("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),M(this,"isValidSessionSettleRequest",t=>{if(!rs(t)){const{message:c}=j("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(c)}const{relay:i,controller:r,namespaces:n,expiry:o}=t;if(!wb(i)){const{message:c}=j("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}const a=xj(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const l=Kl(n,"onSessionSettleRequest()");if(l)throw new Error(l.message);if(Ti(o)){const{message:c}=j("EXPIRED","onSessionSettleRequest()");throw new Error(c)}}),M(this,"isValidUpdate",async t=>{if(!rs(t)){const{message:l}=j("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(l)}const{topic:i,namespaces:r}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=Kl(r,"update()");if(o)throw new Error(o.message);const a=uf(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),M(this,"isValidExtend",async t=>{if(!rs(t)){const{message:r}=j("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),M(this,"isValidRequest",async t=>{if(!rs(t)){const{message:l}=j("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(l)}const{topic:i,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!hf(a,n)){const{message:l}=j("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(l)}if(!Bj(r)){const{message:l}=j("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(l)}if(!Vj(a,n,r.method)){const{message:l}=j("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(l)}if(o&&!Qj(o,eh)){const{message:l}=j("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${eh.min} and ${eh.max}`);throw new Error(l)}}),M(this,"isValidRespond",async t=>{var i;if(!rs(t)){const{message:o}=j("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(i=t==null?void 0:t.response)!=null&&i.id&&this.cleanupAfterResponse(t),o}if(!Hj(n)){const{message:o}=j("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),M(this,"isValidPing",async t=>{if(!rs(t)){const{message:r}=j("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),M(this,"isValidEmit",async t=>{if(!rs(t)){const{message:a}=j("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:i,event:r,chainId:n}=t;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!hf(o,n)){const{message:a}=j("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Wj(r)){const{message:a}=j("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Kj(o,n,r.name)){const{message:a}=j("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),M(this,"isValidDisconnect",async t=>{if(!rs(t)){const{message:r}=j("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),M(this,"isValidAuthenticate",t=>{const{chains:i,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!at(r,!1))throw new Error("uri is required parameter");if(!at(n,!1))throw new Error("domain is required parameter");if(!at(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(l=>xn(l).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=xn(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),M(this,"getVerifyContext",async t=>{const{attestationId:i,hash:r,encryptedId:n,metadata:o,transportType:a}=t,l={verified:{verifyUrl:o.verifyUrl||zo,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Ke.link_mode){const h=this.getAppLinkIfEnabled(o,a);return l.verified.validation=h&&new URL(h).origin===new URL(o.url).origin?"VALID":"INVALID",l}const c=await this.client.core.verify.resolve({attestationId:i,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});c&&(l.verified.origin=c.origin,l.verified.isScam=c.isScam,l.verified.validation=c.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(c){this.client.logger.warn(c)}return this.client.logger.debug(`Verify context: ${JSON.stringify(l)}`),l}),M(this,"validateSessionProps",(t,i)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=j("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),M(this,"getPendingAuthRequest",t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0}),M(this,"addToRecentlyDeleted",(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=n)break;this.recentlyDeletedMap.delete(o)}}}),M(this,"checkRecentlyDeleted",t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:r}=j("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(r)}}),M(this,"isLinkModeEnabled",(t,i)=>{var r,n,o,a,l,c,h,u,d;return!t||i!==Ke.link_mode?!1:((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((c=(l=this.client.metadata)==null?void 0:l.redirect)==null?void 0:c.universal)!==""&&((h=t==null?void 0:t.redirect)==null?void 0:h.universal)!==void 0&&((u=t==null?void 0:t.redirect)==null?void 0:u.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(_.global==null?void 0:_.global.Linking)<"u"}),M(this,"getAppLinkIfEnabled",(t,i)=>{var r;return this.isLinkModeEnabled(t,i)?(r=t==null?void 0:t.redirect)==null?void 0:r.universal:void 0}),M(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Mg(t,"topic")||"",r=decodeURIComponent(Mg(t,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:Ke.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:r,sessionExists:n})}),M(this,"registerLinkModeListeners",async()=>{var t;if(Fu()||Yi()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=_.global==null?void 0:_.global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await i.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),M(this,"shouldSetTVF",(t,i)=>{if(!i||t!=="wc_sessionRequest")return!1;const{request:r}=i;return Object.keys(zf).includes(r.method)}),M(this,"getTVFParams",(t,i,r)=>{var n,o;try{const a=i.request.method,l=this.extractTxHashesFromResult(a,r);return Wt(De({correlationId:t,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:l})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),M(this,"isValidContractData",t=>{var i;if(!t)return!1;try{const r=(t==null?void 0:t.data)||((i=t==null?void 0:t[0])==null?void 0:i.data);if(!r.startsWith("0x"))return!1;const n=r.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),M(this,"extractTxHashesFromResult",(t,i)=>{try{const r=zf[t];if(typeof i=="string")return[i];const n=i[r.key];if(_r(n))return t==="solana_signAllTransactions"?n.map(o=>K3(o)):n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,r]of Object.entries(t))for(const n of r)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Et.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(gc)?this.client.auth.authKeys.get(gc):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===Ke.link_mode?Io:Ui});Kn(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:Xs(i)})):$r(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,i)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Ss.expired,async e=>{const{topic:t,id:i}=Wy(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,j("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,j("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(lr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(lr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!at(e,!1)){const{message:t}=j("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=j("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Ti(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=j("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!at(e,!1)){const{message:t}=j("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=j("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Ti(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=j("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=j("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(at(e,!1)){const{message:t}=j("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=j("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!Fj(e)){const{message:t}=j("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=j("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Ti(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=j("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class tz extends jr{constructor(e,t){super(e,t,UU,Qu),this.core=e,this.logger=t}}let sz=class extends jr{constructor(e,t){super(e,t,zU,Qu),this.core=e,this.logger=t}};class iz extends jr{constructor(e,t){super(e,t,qU,Qu,i=>i.id),this.core=e,this.logger=t}}class rz extends jr{constructor(e,t){super(e,t,VU,ol,()=>gc),this.core=e,this.logger=t}}class nz extends jr{constructor(e,t){super(e,t,KU,ol),this.core=e,this.logger=t}}class oz extends jr{constructor(e,t){super(e,t,GU,ol,i=>i.id),this.core=e,this.logger=t}}var az=Object.defineProperty,cz=(s,e,t)=>e in s?az(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,th=(s,e,t)=>cz(s,typeof e!="symbol"?e+"":e,t);class lz{constructor(e,t){this.core=e,this.logger=t,th(this,"authKeys"),th(this,"pairingTopics"),th(this,"requests"),this.authKeys=new rz(this.core,this.logger),this.pairingTopics=new nz(this.core,this.logger),this.requests=new oz(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var hz=Object.defineProperty,uz=(s,e,t)=>e in s?hz(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,he=(s,e,t)=>uz(s,typeof e!="symbol"?e+"":e,t);let dz=class Rb extends RD{constructor(e){super(e),he(this,"protocol",Db),he(this,"version",kb),he(this,"name",Xl.name),he(this,"metadata"),he(this,"core"),he(this,"logger"),he(this,"events",new kt.EventEmitter),he(this,"engine"),he(this,"session"),he(this,"proposal"),he(this,"pendingRequest"),he(this,"auth"),he(this,"signConfig"),he(this,"on",(i,r)=>this.events.on(i,r)),he(this,"once",(i,r)=>this.events.once(i,r)),he(this,"off",(i,r)=>this.events.off(i,r)),he(this,"removeListener",(i,r)=>this.events.removeListener(i,r)),he(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),he(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"update",async i=>{try{return await this.engine.update(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"request",async i=>{try{return await this.engine.request(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"find",i=>{try{return this.engine.find(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),he(this,"authenticate",async(i,r)=>{try{return await this.engine.authenticate(i,r)}catch(n){throw this.logger.error(n.message),n}}),he(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||Xl.name,this.metadata=(e==null?void 0:e.metadata)||qy(),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Vn(yi({level:(e==null?void 0:e.logger)||Xl.logger}));this.core=(e==null?void 0:e.core)||new LU(e),this.logger=Ne(t,this.name),this.session=new sz(this.core,this.logger),this.proposal=new tz(this.core,this.logger),this.pendingRequest=new iz(this.core,this.logger),this.engine=new ez(this),this.auth=new lz(this.core,this.logger)}static async init(e){const t=new Rb(e);return await t.initialize(),t}get context(){return qe(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()},E.toMiliseconds(E.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const qf="error",pz="wss://relay.walletconnect.org",gz="wc",fz="universal_provider",Qa=`${gz}@2:${fz}:`,Lb="https://rpc.walletconnect.org/v1/",An="generic",mz=`${Lb}bundler`,Ms={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function wz(){}function Zu(s){return s==null||typeof s!="object"&&typeof s!="function"}function Ju(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)}function yz(s){if(Zu(s))return s;if(Array.isArray(s)||Ju(s)||s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer)return s.slice(0);const e=Object.getPrototypeOf(s),t=e.constructor;if(s instanceof Date||s instanceof Map||s instanceof Set)return new t(s);if(s instanceof RegExp){const i=new t(s);return i.lastIndex=s.lastIndex,i}if(s instanceof DataView)return new t(s.buffer.slice(0));if(s instanceof Error){const i=new t(s.message);return i.stack=s.stack,i.name=s.name,i.cause=s.cause,i}if(typeof File<"u"&&s instanceof File)return new t([s],s.name,{type:s.type,lastModified:s.lastModified});if(typeof s=="object"){const i=Object.create(e);return Object.assign(i,s)}return s}function Bf(s){return typeof s=="object"&&s!==null}function Ub(s){return Object.getOwnPropertySymbols(s).filter(e=>Object.prototype.propertyIsEnumerable.call(s,e))}function zb(s){return s==null?s===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(s)}const bz="[object RegExp]",Fb="[object String]",qb="[object Number]",Bb="[object Boolean]",Hb="[object Arguments]",vz="[object Symbol]",Iz="[object Date]",Ez="[object Map]",Az="[object Set]",Nz="[object Array]",_z="[object ArrayBuffer]",Cz="[object Object]",Sz="[object DataView]",$z="[object Uint8Array]",Pz="[object Uint8ClampedArray]",Tz="[object Uint16Array]",Mz="[object Uint32Array]",Oz="[object Int8Array]",xz="[object Int16Array]",Dz="[object Int32Array]",kz="[object Float32Array]",jz="[object Float64Array]";function Rz(s,e){return Pn(s,void 0,s,new Map,e)}function Pn(s,e,t,i=new Map,r=void 0){const n=r==null?void 0:r(s,e,t,i);if(n!=null)return n;if(Zu(s))return s;if(i.has(s))return i.get(s);if(Array.isArray(s)){const o=new Array(s.length);i.set(s,o);for(let a=0;a<s.length;a++)o[a]=Pn(s[a],a,t,i,r);return Object.hasOwn(s,"index")&&(o.index=s.index),Object.hasOwn(s,"input")&&(o.input=s.input),o}if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp){const o=new RegExp(s.source,s.flags);return o.lastIndex=s.lastIndex,o}if(s instanceof Map){const o=new Map;i.set(s,o);for(const[a,l]of s)o.set(a,Pn(l,a,t,i,r));return o}if(s instanceof Set){const o=new Set;i.set(s,o);for(const a of s)o.add(Pn(a,void 0,t,i,r));return o}if(typeof _.Buffer<"u"&&_.Buffer.isBuffer(s))return s.subarray();if(Ju(s)){const o=new(Object.getPrototypeOf(s)).constructor(s.length);i.set(s,o);for(let a=0;a<s.length;a++)o[a]=Pn(s[a],a,t,i,r);return o}if(s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer)return s.slice(0);if(s instanceof DataView){const o=new DataView(s.buffer.slice(0),s.byteOffset,s.byteLength);return i.set(s,o),hr(o,s,t,i,r),o}if(typeof File<"u"&&s instanceof File){const o=new File([s],s.name,{type:s.type});return i.set(s,o),hr(o,s,t,i,r),o}if(s instanceof Blob){const o=new Blob([s],{type:s.type});return i.set(s,o),hr(o,s,t,i,r),o}if(s instanceof Error){const o=new s.constructor;return i.set(s,o),o.message=s.message,o.name=s.name,o.stack=s.stack,o.cause=s.cause,hr(o,s,t,i,r),o}if(typeof s=="object"&&Lz(s)){const o=Object.create(Object.getPrototypeOf(s));return i.set(s,o),hr(o,s,t,i,r),o}return s}function hr(s,e,t=s,i,r){const n=[...Object.keys(e),...Ub(e)];for(let o=0;o<n.length;o++){const a=n[o],l=Object.getOwnPropertyDescriptor(s,a);(l==null||l.writable)&&(s[a]=Pn(e[a],a,t,i,r))}}function Lz(s){switch(zb(s)){case Hb:case Nz:case _z:case Sz:case Bb:case Iz:case kz:case jz:case Oz:case xz:case Dz:case Ez:case qb:case Cz:case bz:case Az:case Fb:case vz:case $z:case Pz:case Tz:case Mz:return!0;default:return!1}}function Uz(s,e){return Rz(s,(t,i,r,n)=>{if(typeof s=="object")switch(Object.prototype.toString.call(s)){case qb:case Fb:case Bb:{const o=new s.constructor(s==null?void 0:s.valueOf());return hr(o,s),o}case Hb:{const o={};return hr(o,s),o.length=s.length,o[Symbol.iterator]=s[Symbol.iterator],o}default:return}})}function Hf(s){return Uz(s)}function Wf(s){return s!==null&&typeof s=="object"&&zb(s)==="[object Arguments]"}function zz(s){return Ju(s)}function Fz(s){var t;if(typeof s!="object"||s==null)return!1;if(Object.getPrototypeOf(s)===null)return!0;if(Object.prototype.toString.call(s)!=="[object Object]"){const i=s[Symbol.toStringTag];return i==null||!((t=Object.getOwnPropertyDescriptor(s,Symbol.toStringTag))!=null&&t.writable)?!1:s.toString()===`[object ${i}]`}let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}function qz(s,...e){const t=e.slice(0,-1),i=e[e.length-1];let r=s;for(let n=0;n<t.length;n++){const o=t[n];r=pu(r,o,i,new Map)}return r}function pu(s,e,t,i){if(Zu(s)&&(s=Object(s)),e==null||typeof e!="object")return s;if(i.has(e))return yz(i.get(e));if(i.set(e,s),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const r=[...Object.keys(e),...Ub(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],l=s[o];if(Wf(a)&&(a={...a}),Wf(l)&&(l={...l}),typeof _.Buffer<"u"&&_.Buffer.isBuffer(a)&&(a=Hf(a)),Array.isArray(a))if(typeof l=="object"&&l!=null){const h=[],u=Reflect.ownKeys(l);for(let d=0;d<u.length;d++){const p=u[d];h[p]=l[p]}l=h}else l=[];const c=t(l,a,o,s,e,i);c!=null?s[o]=c:Array.isArray(a)||Bf(l)&&Bf(a)?s[o]=pu(l,a,t,i):l==null&&Fz(a)?s[o]=pu({},a,t,i):l==null&&zz(a)?s[o]=Hf(a):(l===void 0||a!==void 0)&&(s[o]=a)}return s}function Bz(s,...e){return qz(s,...e,wz)}var Hz=Object.defineProperty,Wz=Object.defineProperties,Vz=Object.getOwnPropertyDescriptors,Vf=Object.getOwnPropertySymbols,Kz=Object.prototype.hasOwnProperty,Gz=Object.prototype.propertyIsEnumerable,Kf=(s,e,t)=>e in s?Hz(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Za=(s,e)=>{for(var t in e||(e={}))Kz.call(e,t)&&Kf(s,t,e[t]);if(Vf)for(var t of Vf(e))Gz.call(e,t)&&Kf(s,t,e[t]);return s},Yz=(s,e)=>Wz(s,Vz(e));function ys(s,e,t){var i;const r=xn(s);return((i=e.rpcMap)==null?void 0:i[r.reference])||`${Lb}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Rr(s){return s.includes(":")?s.split(":")[1]:s}function Wb(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function Qz(s,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(s));if(!t.length)return[];const i=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;i.push(...n)}),i}function sh(s={},e={}){const t=Gf(s),i=Gf(e);return Bz(t,i)}function Gf(s){var e,t,i,r;const n={};if(!ra(s))return n;for(const[o,a]of Object.entries(s)){const l=Gu(o)?[o]:a.chains,c=a.methods||[],h=a.events||[],u=a.rpcMap||{},d=xo(o);n[d]=Yz(Za(Za({},n[d]),a),{chains:hc(l,(e=n[d])==null?void 0:e.chains),methods:hc(c,(t=n[d])==null?void 0:t.methods),events:hc(h,(i=n[d])==null?void 0:i.events),rpcMap:Za(Za({},u),(r=n[d])==null?void 0:r.rpcMap)})}return n}function Zz(s){return s.includes(":")?s.split(":")[2]:s}function Yf(s){const e={};for(const[t,i]of Object.entries(s)){const r=i.methods||[],n=i.events||[],o=i.accounts||[],a=Gu(t)?[t]:i.chains?i.chains:Wb(i.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function ih(s){return typeof s=="number"?s:s.includes("0x")?parseInt(s,16):(s=s.includes(":")?s.split(":")[1]:s,isNaN(Number(s))?s:Number(s))}const Vb={},ye=s=>Vb[s],rh=(s,e)=>{Vb[s]=e};var Jz=Object.defineProperty,Xz=(s,e,t)=>e in s?Jz(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,an=(s,e,t)=>Xz(s,typeof e!="symbol"?e+"":e,t);class e8{constructor(e){an(this,"name","polkadot"),an(this,"client"),an(this,"httpProviders"),an(this,"events"),an(this,"namespace"),an(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Rr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var t8=Object.defineProperty,s8=Object.defineProperties,i8=Object.getOwnPropertyDescriptors,Qf=Object.getOwnPropertySymbols,r8=Object.prototype.hasOwnProperty,n8=Object.prototype.propertyIsEnumerable,gu=(s,e,t)=>e in s?t8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Zf=(s,e)=>{for(var t in e||(e={}))r8.call(e,t)&&gu(s,t,e[t]);if(Qf)for(var t of Qf(e))n8.call(e,t)&&gu(s,t,e[t]);return s},Jf=(s,e)=>s8(s,i8(e)),cn=(s,e,t)=>gu(s,typeof e!="symbol"?e+"":e,t);class o8{constructor(e){cn(this,"name","eip155"),cn(this,"client"),cn(this,"chainId"),cn(this,"namespace"),cn(this,"httpProviders"),cn(this,"events"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(Ms.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,t){const i=t||ys(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=parseInt(Rr(t));e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let r=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const n=parseInt(r,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:r}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,r;const n=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0];if(!n)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const o=this.client.session.get(e.topic),a=((r=o==null?void 0:o.sessionProperties)==null?void 0:r.capabilities)||{};if(a!=null&&a[n])return a==null?void 0:a[n];const l=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Jf(Zf({},o.sessionProperties||{}),{capabilities:Jf(Zf({},a||{}),{[n]:l})})})}catch(c){console.warn("Failed to update session with capabilities",c)}return l}async getCallStatus(e){var t,i;const r=this.client.session.get(e.topic),n=(t=r.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from bundler",l,a)}}const o=(i=r.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Gt("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${mz}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var a8=Object.defineProperty,c8=(s,e,t)=>e in s?a8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ln=(s,e,t)=>c8(s,typeof e!="symbol"?e+"":e,t);class l8{constructor(e){ln(this,"name","solana"),ln(this,"client"),ln(this,"httpProviders"),ln(this,"events"),ln(this,"namespace"),ln(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Rr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var h8=Object.defineProperty,u8=(s,e,t)=>e in s?h8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,hn=(s,e,t)=>u8(s,typeof e!="symbol"?e+"":e,t);class d8{constructor(e){hn(this,"name","cosmos"),hn(this,"client"),hn(this,"httpProviders"),hn(this,"events"),hn(this,"namespace"),hn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Rr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var p8=Object.defineProperty,g8=(s,e,t)=>e in s?p8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,un=(s,e,t)=>g8(s,typeof e!="symbol"?e+"":e,t);class f8{constructor(e){un(this,"name","algorand"),un(this,"client"),un(this,"httpProviders"),un(this,"events"),un(this,"namespace"),un(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){if(!this.httpProviders[e]){const i=t||ys(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(Ms.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new Ye(new tt(i,ye("disableProviderPing")))}}var m8=Object.defineProperty,w8=(s,e,t)=>e in s?m8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,dn=(s,e,t)=>w8(s,typeof e!="symbol"?e+"":e,t);class y8{constructor(e){dn(this,"name","cip34"),dn(this,"client"),dn(this,"httpProviders"),dn(this,"events"),dn(this,"namespace"),dn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),r=Rr(t);e[r]=this.createHttpProvider(r,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var b8=Object.defineProperty,v8=(s,e,t)=>e in s?b8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,pn=(s,e,t)=>v8(s,typeof e!="symbol"?e+"":e,t);class I8{constructor(e){pn(this,"name","elrond"),pn(this,"client"),pn(this,"httpProviders"),pn(this,"events"),pn(this,"namespace"),pn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Rr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var E8=Object.defineProperty,A8=(s,e,t)=>e in s?E8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,gn=(s,e,t)=>A8(s,typeof e!="symbol"?e+"":e,t);class N8{constructor(e){gn(this,"name","multiversx"),gn(this,"client"),gn(this,"httpProviders"),gn(this,"events"),gn(this,"namespace"),gn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Rr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var _8=Object.defineProperty,C8=(s,e,t)=>e in s?_8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fn=(s,e,t)=>C8(s,typeof e!="symbol"?e+"":e,t);class S8{constructor(e){fn(this,"name","near"),fn(this,"client"),fn(this,"httpProviders"),fn(this,"events"),fn(this,"namespace"),fn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||ys(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Ms.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace);return typeof i>"u"?void 0:new Ye(new tt(i,ye("disableProviderPing")))}}var $8=Object.defineProperty,P8=(s,e,t)=>e in s?$8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,mn=(s,e,t)=>P8(s,typeof e!="symbol"?e+"":e,t);class T8{constructor(e){mn(this,"name","tezos"),mn(this,"client"),mn(this,"httpProviders"),mn(this,"events"),mn(this,"namespace"),mn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||ys(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Ms.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace);return typeof i>"u"?void 0:new Ye(new tt(i))}}var M8=Object.defineProperty,O8=(s,e,t)=>e in s?M8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,wn=(s,e,t)=>O8(s,typeof e!="symbol"?e+"":e,t);class x8{constructor(e){wn(this,"name",An),wn(this,"client"),wn(this,"httpProviders"),wn(this,"events"),wn(this,"namespace"),wn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=xn(r);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var D8=Object.defineProperty,k8=Object.defineProperties,j8=Object.getOwnPropertyDescriptors,Xf=Object.getOwnPropertySymbols,R8=Object.prototype.hasOwnProperty,L8=Object.prototype.propertyIsEnumerable,fu=(s,e,t)=>e in s?D8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ja=(s,e)=>{for(var t in e||(e={}))R8.call(e,t)&&fu(s,t,e[t]);if(Xf)for(var t of Xf(e))L8.call(e,t)&&fu(s,t,e[t]);return s},nh=(s,e)=>k8(s,j8(e)),Ns=(s,e,t)=>fu(s,typeof e!="symbol"?e+"":e,t);let U8=class Kb{constructor(e){Ns(this,"client"),Ns(this,"namespaces"),Ns(this,"optionalNamespaces"),Ns(this,"sessionProperties"),Ns(this,"scopedProperties"),Ns(this,"events",new Wn),Ns(this,"rpcProviders",{}),Ns(this,"session"),Ns(this,"providerOpts"),Ns(this,"logger"),Ns(this,"uri"),Ns(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Vn(yi({level:(e==null?void 0:e.logger)||qf})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Kb(e);return await t.initialize(),t}async request(e,t,i){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Ja({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,r){const n=new Date().getTime();this.request(e,i,r).then(o=>t(null,Vi(n,o))).catch(o=>t(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:Me("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,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:r}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await r();if(this.session=n.session,this.session){const o=Yf(this.session.namespaces);this.namespaces=sh(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await i();this.session=r;const n=Yf(r.namespaces);return this.namespaces=sh(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,r]=this.validateChain(e),n=this.getProvider(i);n.name===An?n.setDefaultChain(`${i}:${r}`,t):n.setDefaultChain(r,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(_r(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}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,t;if(this.client=this.providerOpts.client||await dz.init({core:this.providerOpts.core,logger:this.providerOpts.logger||qf,relayUrl:this.providerOpts.relayUrl||pz,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>xo(t)))];rh("client",this.client),rh("events",this.events),rh("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=Qz(t,this.session),r=Wb(i),n=sh(this.namespaces,this.optionalNamespaces),o=nh(Ja({},n[t]),{accounts:i,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new o8({namespace:o});break;case"algorand":this.rpcProviders[t]=new f8({namespace:o});break;case"solana":this.rpcProviders[t]=new l8({namespace:o});break;case"cosmos":this.rpcProviders[t]=new d8({namespace:o});break;case"polkadot":this.rpcProviders[t]=new e8({namespace:o});break;case"cip34":this.rpcProviders[t]=new y8({namespace:o});break;case"elrond":this.rpcProviders[t]=new I8({namespace:o});break;case"multiversx":this.rpcProviders[t]=new N8({namespace:o});break;case"near":this.rpcProviders[t]=new S8({namespace:o});break;case"tezos":this.rpcProviders[t]=new T8({namespace:o});break;default:this.rpcProviders[An]?this.rpcProviders[An].updateNamespace(o):this.rpcProviders[An]=new x8({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:i}=e;i===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:i,topic:r}=e;if(r!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&_r(o)&&this.events.emit("accountsChanged",o.map(Zz))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,l=xo(o),c=ih(o)!==ih(a)?`${l}:${ih(a)}`:o;this.onChainChanged(c)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i,r;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=t,o=(r=this.client)==null?void 0:r.session.get(e);this.session=nh(Ja({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",nh(Ja({},Me("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Ms.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[An]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t,optionalNamespaces:i,sessionProperties:r,scopedProperties:n}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>xo(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const r=xo(Object.keys(this.namespaces)[0]),n=this.rpcProviders[r].getDefaultChain();return[r,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,r]=this.validateChain(e);r&&(t||this.getProvider(i).setDefaultChain(r),this.namespaces[i]?this.namespaces[i].defaultChain=r:this.namespaces[`${i}:${r}`]?this.namespaces[`${i}:${r}`].defaultChain=r:this.namespaces[`${i}:${r}`]={defaultChain:r},this.events.emit("chainChanged",r),await this.persist("namespaces",this.namespaces))}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,t){var i;const r=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${Qa}/${e}${r}`,t)}async getFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${Qa}/${e}${i}`)}async deleteFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${Qa}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const i of t)i.startsWith(Qa)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const _i={EIP155:"eip155",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED"},Dc={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","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:{[Q.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Q.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Q.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[Q.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[Q.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[Q.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[Q.CONNECTOR_ID.INJECTED]:"Browser Wallet",[Q.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[Q.CONNECTOR_ID.COINBASE]:"Coinbase",[Q.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[Q.CONNECTOR_ID.LEDGER]:"Ledger",[Q.CONNECTOR_ID.SAFE]:"Safe"}},Gb={getCaipTokens(s){if(!s)return;const e={};return Object.entries(s).forEach(([t,i])=>{e[`${_i.EIP155}:${t}`]=i}),e},isLowerCaseMatch(s,e){return(s==null?void 0:s.toLowerCase())===(e==null?void 0:e.toLowerCase())}},Xa={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 ${z8()?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},SOCIALS_TIMEOUT:{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 z8(){return typeof window<"u"}const F8={createLogger(s,e="error"){const t=yi({level:e}),{logger:i}=Au({opts:t});return i.error=(...r)=>{for(const n of r)if(n instanceof Error){s(n,...r);return}s(void 0,...r)},i}},q8="rpc.walletconnect.org";function B8(s,e){const t=new URL("https://rpc.walletconnect.org/v1/");return t.searchParams.set("chainId",s),t.searchParams.set("projectId",e),t.toString()}const oh=["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"],Nn={extendRpcUrlWithProjectId(s,e){let t=!1;try{t=new URL(s).host===q8}catch{t=!1}if(t){const i=new URL(s);return i.searchParams.has("projectId")||i.searchParams.set("projectId",e),i.toString()}return s},isCaipNetwork(s){return"chainNamespace"in s&&"caipNetworkId"in s},getChainNamespace(s){return this.isCaipNetwork(s)?s.chainNamespace:Q.CHAIN.EVM},getCaipNetworkId(s){return this.isCaipNetwork(s)?s.caipNetworkId:`${Q.CHAIN.EVM}:${s.id}`},getDefaultRpcUrl(s,e,t){var r,n,o;const i=(o=(n=(r=s.rpcUrls)==null?void 0:r.default)==null?void 0:n.http)==null?void 0:o[0];return oh.includes(e)?B8(e,t):i||""},extendCaipNetwork(s,{customNetworkImageUrls:e,projectId:t,customRpcUrls:i}){var d,p,g,f,y;const r=this.getChainNamespace(s),n=this.getCaipNetworkId(s),o=(d=s.rpcUrls.default.http)==null?void 0:d[0],a=this.getDefaultRpcUrl(s,n,t),l=((f=(g=(p=s==null?void 0:s.rpcUrls)==null?void 0:p.chainDefault)==null?void 0:g.http)==null?void 0:f[0])||o,c=((y=i==null?void 0:i[n])==null?void 0:y.map(w=>w.url))||[],h=[...c,a],u=[...c];return l&&!u.includes(l)&&u.push(l),{...s,chainNamespace:r,caipNetworkId:n,assets:{imageId:Dc.NetworkImageIds[s.id],imageUrl:e==null?void 0:e[s.id]},rpcUrls:{...s.rpcUrls,default:{http:h},chainDefault:{http:u}}}},extendCaipNetworks(s,{customNetworkImageUrls:e,projectId:t,customRpcUrls:i}){return s.map(r=>Nn.extendCaipNetwork(r,{customNetworkImageUrls:e,customRpcUrls:i,projectId:t}))},getViemTransport(s,e,t){const i=[];if(t==null||t.forEach(r=>{i.push(hl(r.url,r.config))}),oh.includes(s.caipNetworkId)){const r=this.getDefaultRpcUrl(s,s.caipNetworkId,e);i.push(hl(r,{fetchOptions:{headers:{"Content-Type":"text/plain"}}}))}return od(i)},extendWagmiTransports(s,e,t){if(oh.includes(s.caipNetworkId)){const i=this.getDefaultRpcUrl(s,s.caipNetworkId,e);return od([t,hl(i)])}return t},getUnsupportedNetwork(s){return{id:s.split(":")[1],caipNetworkId:s,name:Q.UNSUPPORTED_NETWORK_NAME,chainNamespace:s.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(s){var l;const e=G.getActiveCaipNetworkId(),t=v.getAllRequestedCaipNetworks(),i=Array.from(((l=v.state.chains)==null?void 0:l.keys())||[]),r=e==null?void 0:e.split(":")[0],n=r?i.includes(r):!1,o=t==null?void 0:t.find(c=>c.caipNetworkId===e);return n&&!o&&e?this.getUnsupportedNetwork(e):o||s||(t==null?void 0:t[0])}},kc={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0},es=Xe({providers:{...kc},providerIds:{...kc}}),Je={state:es,subscribeKey(s,e){return vs(es,s,e)},subscribe(s){return Yt(es,()=>{s(es)})},subscribeProviders(s){return Yt(es.providers,()=>s(es.providers))},setProvider(s,e){e&&(es.providers[s]=Ir(e))},getProvider(s){return es.providers[s]},setProviderId(s,e){e&&(es.providerIds[s]=e)},getProviderId(s){if(s)return es.providerIds[s]},reset(){es.providers={...kc},es.providerIds={...kc}},resetChain(s){es.providers[s]=void 0,es.providerIds[s]=void 0}},H8={VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},mu={filterOutDuplicatesByRDNS(s){const e=D.state.enableEIP6963?te.state.connectors:[],t=G.getRecentWallets(),i=e.map(a=>{var l;return(l=a.info)==null?void 0:l.rdns}).filter(Boolean),r=t.map(a=>a.rdns).filter(Boolean),n=i.concat(r);if(n.includes("io.metamask.mobile")&&se.isMobile()){const a=n.indexOf("io.metamask.mobile");n[a]="io.metamask"}return s.filter(a=>!n.includes(String(a==null?void 0:a.rdns)))},filterOutDuplicatesByIds(s){const e=te.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),t=G.getRecentWallets(),i=e.map(a=>a.explorerId),r=t.map(a=>a.id),n=i.concat(r);return s.filter(a=>!n.includes(a==null?void 0:a.id))},filterOutDuplicateWallets(s){const e=this.filterOutDuplicatesByRDNS(s);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(s){const{connectors:e}=te.state,t=e.filter(n=>n.type==="ANNOUNCED").reduce((n,o)=>{var a;return(a=o.info)!=null&&a.rdns&&(n[o.info.rdns]=!0),n},{});return s.map(n=>({...n,installed:!!n.rdns&&!!t[n.rdns??""]})).sort((n,o)=>Number(o.installed)-Number(n.installed))},getConnectOrderMethod(s,e){var l;const t=(s==null?void 0:s.connectMethodsOrder)||((l=D.state.features)==null?void 0:l.connectMethodsOrder),i=e||te.state.connectors;if(t)return t;const{injected:r,announced:n}=fc.getConnectorsByType(i,ie.state.recommended,ie.state.featured),o=r.filter(fc.showConnector),a=n.filter(fc.showConnector);return o.length||a.length?["wallet","email","social"]:H8.DEFAULT_CONNECT_METHOD_ORDER}},fc={getConnectorsByType(s,e,t){const{customWallets:i}=D.state,r=G.getRecentWallets(),n=mu.filterOutDuplicateWallets(e),o=mu.filterOutDuplicateWallets(t),a=s.filter(u=>u.type==="MULTI_CHAIN"),l=s.filter(u=>u.type==="ANNOUNCED"),c=s.filter(u=>u.type==="INJECTED"),h=s.filter(u=>u.type==="EXTERNAL");return{custom:i,recent:r,external:h,multiChain:a,announced:l,injected:c,recommended:n,featured:o}},showConnector(s){var r;const e=(r=s.info)==null?void 0:r.rdns,t=!!e&&ie.state.excludedWallets.some(n=>n.rdns===e),i=!!s.name&&ie.state.excludedWallets.some(n=>Gb.isLowerCaseMatch(n.name,s.name));return!(s.type==="INJECTED"&&(!se.isMobile()&&s.name==="Browser Wallet"||!e&&!Ue.checkInstalled()||t||i)||s.type==="ANNOUNCED"&&(t||i))},getIsConnectedWithWC(){return Array.from(v.state.chains.values()).some(t=>te.getConnectorId(t.namespace)===Q.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:s,featured:e,custom:t,recent:i,announced:r,injected:n,multiChain:o,external:a,overriddenConnectors:l=(c=>(c=D.state.features)==null?void 0:c.connectorTypeOrder)()??[]}){const h=fc.getIsConnectedWithWC(),p=[{type:"walletConnect",isEnabled:D.state.enableWalletConnect&&!h},{type:"recent",isEnabled:i.length>0},{type:"injected",isEnabled:[...n,...r,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:t&&t.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:s.length>0}].filter(w=>w.isEnabled),g=new Set(p.map(w=>w.type)),f=l.filter(w=>g.has(w)).map(w=>({type:w,isEnabled:!0})),y=p.filter(({type:w})=>!f.some(({type:b})=>b===w));return Array.from(new Set([...f,...y].map(({type:w})=>w)))}};/**
22
+ Approved: ${d.toString()}`))}),o.forEach(u=>{i||(pr(r[u].methods,n[u].methods)?pr(r[u].events,n[u].events)||(i=j("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):i=j("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),i}function Gj(s){const e={};return Object.keys(s).forEach(t=>{var i;t.includes(":")?e[t]=s[t]:(i=s[t].chains)==null||i.forEach(r=>{e[r]={methods:s[t].methods,events:s[t].events}})}),e}function df(s){return[...new Set(s.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Yj(s){const e={};return Object.keys(s).forEach(t=>{if(t.includes(":"))e[t]=s[t];else{const i=to(s[t].accounts);i==null||i.forEach(r=>{e[r]={accounts:s[t].accounts.filter(n=>n.includes(`${r}:`)),methods:s[t].methods,events:s[t].events}})}}),e}function Qj(s,e){return Yu(s,!1)&&s<=e.max&&s>=e.min}function pf(){const s=Ea();return new Promise(e=>{switch(s){case ms.browser:e(Zj());break;case ms.reactNative:e(Jj());break;case ms.node:e(Xj());break;default:e(!0)}})}function Zj(){return Ia()&&(navigator==null?void 0:navigator.onLine)}async function Jj(){if(Yi()&&typeof _.global<"u"&&_.global!=null&&_.global.NetInfo){const s=await(_.global==null?void 0:_.global.NetInfo.fetch());return s==null?void 0:s.isConnected}return!0}function Xj(){return!0}function eR(s){switch(Ea()){case ms.browser:tR(s);break;case ms.reactNative:sR(s);break}}function tR(s){!Yi()&&Ia()&&(window.addEventListener("online",()=>s(!0)),window.addEventListener("offline",()=>s(!1)))}function sR(s){var e;Yi()&&typeof _.global<"u"&&_.global!=null&&_.global.NetInfo&&((e=_.global)==null||e.NetInfo.addEventListener(t=>s(t==null?void 0:t.isConnected)))}const Gl={};class Eo{static get(e){return Gl[e]}static set(e,t){Gl[e]=t}static delete(e){delete Gl[e]}}const yb="wc",bb=2,tu="core",ii=`${yb}@2:${tu}:`,iR={logger:"error"},rR={database:":memory:"},nR="crypto",gf="client_ed25519_seed",oR=E.ONE_DAY,aR="keychain",cR="0.3",lR="messages",hR="0.3",ff=E.SIX_HOURS,uR="publisher",vb="irn",dR="error",Ib="wss://relay.walletconnect.org",pR="relayer",Et={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"},gR="_subscription",As={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},fR=.1,su="2.19.1",Ke={link_mode:"link_mode",relay:"relay"},pc={inbound:"inbound",outbound:"outbound"},mR="0.3",wR="WALLETCONNECT_CLIENT_ID",mf="WALLETCONNECT_LINK_MODE_APPS",us={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},yR="subscription",bR="0.3",vR="pairing",IR="0.3",Ao={wc_pairingDelete:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:E.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:E.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:E.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:E.ONE_DAY,prompt:!1,tag:0},res:{ttl:E.ONE_DAY,prompt:!1,tag:0}}},lr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},js={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},ER="history",AR="0.3",NR="expirer",Ss={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},_R="0.3",CR="verify-api",SR="https://verify.walletconnect.com",Eb="https://verify.walletconnect.org",zo=Eb,$R=`${zo}/v3`,PR=[SR,Eb],TR="echo",MR="https://echo.walletconnect.com",Js={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"},ui={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Rs={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},tr={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"},sr={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},No={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},OR=.1,xR="event-client",DR=86400,kR="https://pulse.walletconnect.org/batch";function jR(s,e){if(s.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var r=0;r<s.length;r++){var n=s.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=s.length,l=s.charAt(0),c=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var f=0,y=0,w=0,m=g.length;w!==m&&g[w]===0;)w++,f++;for(var b=(m-w)*h+1>>>0,I=new Uint8Array(b);w!==m;){for(var N=g[w],$=0,P=b-1;(N!==0||$<y)&&P!==-1;P--,$++)N+=256*I[P]>>>0,I[P]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");y=$,w++}for(var O=b-y;O!==b&&I[O]===0;)O++;for(var C=l.repeat(f);O<b;++O)C+=s.charAt(I[O]);return C}function d(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var f=0;if(g[f]!==" "){for(var y=0,w=0;g[f]===l;)y++,f++;for(var m=(g.length-f)*c+1>>>0,b=new Uint8Array(m);g[f];){var I=t[g.charCodeAt(f)];if(I===255)return;for(var N=0,$=m-1;(I!==0||N<w)&&$!==-1;$--,N++)I+=a*b[$]>>>0,b[$]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");w=N,f++}if(g[f]!==" "){for(var P=m-w;P!==m&&b[P]===0;)P++;for(var O=new Uint8Array(y+(m-P)),C=y;P!==m;)O[C++]=b[P++];return O}}}function p(g){var f=d(g);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:p}}var RR=jR,LR=RR;const Ab=s=>{if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);throw new Error("Unknown type, must be binary type")},UR=s=>new TextEncoder().encode(s),zR=s=>new TextDecoder().decode(s);class FR{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class qR{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Nb(this,e)}}class BR{constructor(e){this.decoders=e}or(e){return Nb(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Nb=(s,e)=>new BR({...s.decoders||{[s.prefix]:s},...e.decoders||{[e.prefix]:e}});class HR{constructor(e,t,i,r){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=r,this.encoder=new FR(e,t,i),this.decoder=new qR(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const nl=({name:s,prefix:e,encode:t,decode:i})=>new HR(s,e,t,i),Ca=({prefix:s,name:e,alphabet:t})=>{const{encode:i,decode:r}=LR(t,e);return nl({prefix:s,name:e,encode:i,decode:n=>Ab(r(n))})},WR=(s,e,t,i)=>{const r={};for(let h=0;h<e.length;++h)r[e[h]]=h;let n=s.length;for(;s[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,l=0,c=0;for(let h=0;h<n;++h){const u=r[s[h]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);l=l<<t|u,a+=t,a>=8&&(a-=8,o[c++]=255&l>>a)}if(a>=t||255&l<<8-a)throw new SyntaxError("Unexpected end of data");return o},VR=(s,e,t)=>{const i=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Lt=({name:s,prefix:e,bitsPerChar:t,alphabet:i})=>nl({prefix:e,name:s,encode(r){return VR(r,i,t)},decode(r){return WR(r,i,t,s)}}),KR=nl({prefix:"\0",name:"identity",encode:s=>zR(s),decode:s=>UR(s)});var GR=Object.freeze({__proto__:null,identity:KR});const YR=Lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var QR=Object.freeze({__proto__:null,base2:YR});const ZR=Lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var JR=Object.freeze({__proto__:null,base8:ZR});const XR=Ca({prefix:"9",name:"base10",alphabet:"0123456789"});var e5=Object.freeze({__proto__:null,base10:XR});const t5=Lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),s5=Lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var i5=Object.freeze({__proto__:null,base16:t5,base16upper:s5});const r5=Lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),n5=Lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),o5=Lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),a5=Lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),c5=Lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),l5=Lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),h5=Lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),u5=Lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),d5=Lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var p5=Object.freeze({__proto__:null,base32:r5,base32upper:n5,base32pad:o5,base32padupper:a5,base32hex:c5,base32hexupper:l5,base32hexpad:h5,base32hexpadupper:u5,base32z:d5});const g5=Ca({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),f5=Ca({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var m5=Object.freeze({__proto__:null,base36:g5,base36upper:f5});const w5=Ca({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),y5=Ca({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var b5=Object.freeze({__proto__:null,base58btc:w5,base58flickr:y5});const v5=Lt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),I5=Lt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),E5=Lt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),A5=Lt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var N5=Object.freeze({__proto__:null,base64:v5,base64pad:I5,base64url:E5,base64urlpad:A5});const _b=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),_5=_b.reduce((s,e,t)=>(s[t]=e,s),[]),C5=_b.reduce((s,e,t)=>(s[e.codePointAt(0)]=t,s),[]);function S5(s){return s.reduce((e,t)=>(e+=_5[t],e),"")}function $5(s){const e=[];for(const t of s){const i=C5[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const P5=nl({prefix:"🚀",name:"base256emoji",encode:S5,decode:$5});var T5=Object.freeze({__proto__:null,base256emoji:P5}),M5=Cb,wf=128,O5=-128,x5=Math.pow(2,31);function Cb(s,e,t){e=e||[],t=t||0;for(var i=t;s>=x5;)e[t++]=s&255|wf,s/=128;for(;s&O5;)e[t++]=s&255|wf,s>>>=7;return e[t]=s|0,Cb.bytes=t-i+1,e}var D5=iu,k5=128,yf=127;function iu(s,i){var t=0,i=i||0,r=0,n=i,o,a=s.length;do{if(n>=a)throw iu.bytes=0,new RangeError("Could not decode varint");o=s[n++],t+=r<28?(o&yf)<<r:(o&yf)*Math.pow(2,r),r+=7}while(o>=k5);return iu.bytes=n-i,t}var j5=Math.pow(2,7),R5=Math.pow(2,14),L5=Math.pow(2,21),U5=Math.pow(2,28),z5=Math.pow(2,35),F5=Math.pow(2,42),q5=Math.pow(2,49),B5=Math.pow(2,56),H5=Math.pow(2,63),W5=function(s){return s<j5?1:s<R5?2:s<L5?3:s<U5?4:s<z5?5:s<F5?6:s<q5?7:s<B5?8:s<H5?9:10},V5={encode:M5,decode:D5,encodingLength:W5},Sb=V5;const bf=(s,e,t=0)=>(Sb.encode(s,e,t),e),vf=s=>Sb.encodingLength(s),ru=(s,e)=>{const t=e.byteLength,i=vf(s),r=i+vf(t),n=new Uint8Array(r+t);return bf(s,n,0),bf(t,n,i),n.set(e,r),new K5(s,t,e,n)};class K5{constructor(e,t,i,r){this.code=e,this.size=t,this.digest=i,this.bytes=r}}const $b=({name:s,code:e,encode:t})=>new G5(s,e,t);class G5{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?ru(this.code,t):t.then(i=>ru(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Pb=s=>async e=>new Uint8Array(await crypto.subtle.digest(s,e)),Y5=$b({name:"sha2-256",code:18,encode:Pb("SHA-256")}),Q5=$b({name:"sha2-512",code:19,encode:Pb("SHA-512")});var Z5=Object.freeze({__proto__:null,sha256:Y5,sha512:Q5});const Tb=0,J5="identity",Mb=Ab,X5=s=>ru(Tb,Mb(s)),eL={code:Tb,name:J5,encode:Mb,digest:X5};var tL=Object.freeze({__proto__:null,identity:eL});new TextEncoder,new TextDecoder;const If={...GR,...QR,...JR,...e5,...i5,...p5,...m5,...b5,...N5,...T5};({...Z5,...tL});function sL(s=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(s):new Uint8Array(s)}function Ob(s,e,t,i){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:i}}}const Ef=Ob("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),Yl=Ob("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);const e=sL(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),iL={utf8:Ef,"utf-8":Ef,hex:If.base16,latin1:Yl,ascii:Yl,binary:Yl,...If};function rL(s,e="utf8"){const t=iL[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(s,"utf8"):t.decoder.decode(`${t.prefix}${s}`)}var nL=Object.defineProperty,oL=(s,e,t)=>e in s?nL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ys=(s,e,t)=>oL(s,typeof e!="symbol"?e+"":e,t);class aL{constructor(e,t){this.core=e,this.logger=t,Ys(this,"keychain",new Map),Ys(this,"name",aR),Ys(this,"version",cR),Ys(this,"initialized",!1),Ys(this,"storagePrefix",ii),Ys(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Ys(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Ys(this,"set",async(i,r)=>{this.isInitialized(),this.keychain.set(i,r),await this.persist()}),Ys(this,"get",i=>{this.isInitialized();const r=this.keychain.get(i);if(typeof r>"u"){const{message:n}=j("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return r}),Ys(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Ne(t,this.name)}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Vh(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Kh(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var cL=Object.defineProperty,lL=(s,e,t)=>e in s?cL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Pt=(s,e,t)=>lL(s,typeof e!="symbol"?e+"":e,t);class hL{constructor(e,t,i){this.core=e,this.logger=t,Pt(this,"name",nR),Pt(this,"keychain"),Pt(this,"randomSessionIdentifier",eu()),Pt(this,"initialized",!1),Pt(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Pt(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Pt(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=vc(r);return $m(n.publicKey)}),Pt(this,"generateKeyPair",()=>{this.isInitialized();const r=aj();return this.setPrivateKey(r.publicKey,r.privateKey)}),Pt(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=vc(n),a=this.randomSessionIdentifier;return await Pm(a,r,oR,o)}),Pt(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),l=cj(a,n);return this.setSymKey(l,o)}),Pt(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||dc(r);return await this.keychain.set(o,r),o}),Pt(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Pt(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Pt(this,"encode",async(r,n,o)=>{this.isInitialized();const a=fb(o),l=Sr(n);if(nf(a))return uj(l,o==null?void 0:o.encoding);if(rf(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;r=await this.generateSharedKey(d,p)}const c=this.getSymKey(r),{type:h,senderPublicKey:u}=a;return lj({type:h,symKey:c,message:l,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Pt(this,"decode",async(r,n,o)=>{this.isInitialized();const a=pj(n,o);if(nf(a)){const l=dj(n,o==null?void 0:o.encoding);return wi(l)}if(rf(a)){const l=a.receiverPublicKey,c=a.senderPublicKey;r=await this.generateSharedKey(l,c)}try{const l=this.getSymKey(r),c=hj({symKey:l,encoded:n,encoding:o==null?void 0:o.encoding});return wi(c)}catch(l){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(l)}}),Pt(this,"getPayloadType",(r,n=Ui)=>{const o=ia({encoded:r,encoding:n});return Nr(o.type)}),Pt(this,"getPayloadSenderPublicKey",(r,n=Ui)=>{const o=ia({encoded:r,encoding:n});return o.senderPublicKey?Ae(o.senderPublicKey,Ht):void 0}),this.core=e,this.logger=Ne(t,this.name),this.keychain=i||new aL(this.core,this.logger)}get context(){return qe(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(gf)}catch{e=eu(),await this.keychain.set(gf,e)}return rL(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var uL=Object.defineProperty,dL=Object.defineProperties,pL=Object.getOwnPropertyDescriptors,Af=Object.getOwnPropertySymbols,gL=Object.prototype.hasOwnProperty,fL=Object.prototype.propertyIsEnumerable,nu=(s,e,t)=>e in s?uL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,mL=(s,e)=>{for(var t in e||(e={}))gL.call(e,t)&&nu(s,t,e[t]);if(Af)for(var t of Af(e))fL.call(e,t)&&nu(s,t,e[t]);return s},wL=(s,e)=>dL(s,pL(e)),ls=(s,e,t)=>nu(s,typeof e!="symbol"?e+"":e,t);class yL extends CD{constructor(e,t){super(e,t),this.logger=e,this.core=t,ls(this,"messages",new Map),ls(this,"messagesWithoutClientAck",new Map),ls(this,"name",lR),ls(this,"version",hR),ls(this,"initialized",!1),ls(this,"storagePrefix",ii),ls(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ls(this,"set",async(i,r,n)=>{this.isInitialized();const o=Xs(r);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(i,a),n===pc.inbound){const l=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,wL(mL({},l),{[o]:r}))}return await this.persist(),o}),ls(this,"get",i=>{this.isInitialized();let r=this.messages.get(i);return typeof r>"u"&&(r={}),r}),ls(this,"getWithoutAck",i=>{this.isInitialized();const r={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};r[n]=Object.values(o)}return r}),ls(this,"has",(i,r)=>{this.isInitialized();const n=this.get(i),o=Xs(r);return typeof n[o]<"u"}),ls(this,"ack",async(i,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=Xs(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),ls(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=Ne(e,this.name),this.core=t}get context(){return qe(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,Vh(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Vh(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Kh(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Kh(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var bL=Object.defineProperty,vL=Object.defineProperties,IL=Object.getOwnPropertyDescriptors,Nf=Object.getOwnPropertySymbols,EL=Object.prototype.hasOwnProperty,AL=Object.prototype.propertyIsEnumerable,ou=(s,e,t)=>e in s?bL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ya=(s,e)=>{for(var t in e||(e={}))EL.call(e,t)&&ou(s,t,e[t]);if(Nf)for(var t of Nf(e))AL.call(e,t)&&ou(s,t,e[t]);return s},Ql=(s,e)=>vL(s,IL(e)),Ls=(s,e,t)=>ou(s,typeof e!="symbol"?e+"":e,t);class NL extends SD{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Ls(this,"events",new kt.EventEmitter),Ls(this,"name",uR),Ls(this,"queue",new Map),Ls(this,"publishTimeout",E.toMiliseconds(E.ONE_MINUTE)),Ls(this,"initialPublishTimeout",E.toMiliseconds(E.ONE_SECOND*15)),Ls(this,"needsTransportRestart",!1),Ls(this,"publish",async(i,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:r,opts:n}});const a=(n==null?void 0:n.ttl)||ff,l=Oc(n),c=(n==null?void 0:n.prompt)||!1,h=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||gs().toString(),d={topic:i,message:r,opts:{ttl:a,relay:l,prompt:c,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},p=`Failed to publish payload, please try again. id:${u} tag:${h}`;try{const g=new Promise(async f=>{const y=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(Et.publish,y),f(d))};this.relayer.events.on(Et.publish,y);const w=Li(new Promise((m,b)=>{this.rpcPublish({topic:i,message:r,ttl:a,prompt:c,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(m).catch(I=>{this.logger.warn(I,I==null?void 0:I.message),b(I)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${h}`);try{await w,this.events.removeListener(Et.publish,y)}catch(m){this.queue.set(u,Ql(Ya({},d),{attempt:1})),this.logger.warn(m,m==null?void 0:m.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:i,message:r,opts:n}}),await Li(g,this.publishTimeout,p)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(u)}}),Ls(this,"on",(i,r)=>{this.events.on(i,r)}),Ls(this,"once",(i,r)=>{this.events.once(i,r)}),Ls(this,"off",(i,r)=>{this.events.off(i,r)}),Ls(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.relayer=e,this.logger=Ne(t,this.name),this.registerEventListeners()}get context(){return qe(this.logger)}async rpcPublish(e){var t,i,r,n;const{topic:o,message:a,ttl:l=ff,prompt:c,tag:h,id:u,attestation:d,tvf:p}=e,g={method:Oo(Oc().protocol).publish,params:Ya({topic:o,message:a,ttl:l,prompt:c,tag:h,attestation:d},p),id:u};Dt((t=g.params)==null?void 0:t.prompt)&&((i=g.params)==null||delete i.prompt),Dt((r=g.params)==null?void 0:r.tag)&&((n=g.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const f=await this.relayer.request(g);return this.relayer.events.emit(Et.publish,e),this.logger.debug("Successfully Published Payload"),f}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,Ql(Ya({},e),{attempt:i}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Ql(Ya({},e),{topic:r,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(qs.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Et.connection_stalled);return}this.checkQueue()}),this.relayer.on(Et.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var _L=Object.defineProperty,CL=(s,e,t)=>e in s?_L(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,nn=(s,e,t)=>CL(s,typeof e!="symbol"?e+"":e,t);class SL{constructor(){nn(this,"map",new Map),nn(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),nn(this,"get",e=>this.map.get(e)||[]),nn(this,"exists",(e,t)=>this.get(e).includes(t)),nn(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const r=i.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),nn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var $L=Object.defineProperty,PL=Object.defineProperties,TL=Object.getOwnPropertyDescriptors,_f=Object.getOwnPropertySymbols,ML=Object.prototype.hasOwnProperty,OL=Object.prototype.propertyIsEnumerable,au=(s,e,t)=>e in s?$L(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,_o=(s,e)=>{for(var t in e||(e={}))ML.call(e,t)&&au(s,t,e[t]);if(_f)for(var t of _f(e))OL.call(e,t)&&au(s,t,e[t]);return s},Zl=(s,e)=>PL(s,TL(e)),xe=(s,e,t)=>au(s,typeof e!="symbol"?e+"":e,t);class xL extends TD{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,xe(this,"subscriptions",new Map),xe(this,"topicMap",new SL),xe(this,"events",new kt.EventEmitter),xe(this,"name",yR),xe(this,"version",bR),xe(this,"pending",new Map),xe(this,"cached",[]),xe(this,"initialized",!1),xe(this,"storagePrefix",ii),xe(this,"subscribeTimeout",E.toMiliseconds(E.ONE_MINUTE)),xe(this,"initialSubscribeTimeout",E.toMiliseconds(E.ONE_SECOND*15)),xe(this,"clientId"),xe(this,"batchSubscribeTopicsLimit",500),xe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),xe(this,"subscribe",async(i,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}});try{const n=Oc(r),o={topic:i,relay:n,transportType:r==null?void 0:r.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,r);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),xe(this,"unsubscribe",async(i,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(i,r.id,r):await this.unsubscribeByTopic(i,r)}),xe(this,"isSubscribed",i=>new Promise(r=>{r(this.topicMap.topics.includes(i))})),xe(this,"isKnownTopic",i=>new Promise(r=>{r(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),xe(this,"on",(i,r)=>{this.events.on(i,r)}),xe(this,"once",(i,r)=>{this.events.once(i,r)}),xe(this,"off",(i,r)=>{this.events.off(i,r)}),xe(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),xe(this,"start",async()=>{await this.onConnect()}),xe(this,"stop",async()=>{await this.onDisconnect()}),xe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),xe(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(r=>{i.push(r)}),await this.batchSubscribe(i)}),xe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(qs.pulse,async()=>{await this.checkPending()}),this.events.on(us.created,async i=>{const r=us.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()}),this.events.on(us.deleted,async i=>{const r=us.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()})}),this.relayer=e,this.logger=Ne(t,this.name),this.clientId=""}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const r=Oc(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Me("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,i){var r;(!i||(i==null?void 0:i.transportType)===Ke.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Oo(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=i==null?void 0:i.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===Ke.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(h=>this.logger.warn(h))},E.toMiliseconds(E.ONE_SECOND)),a;const l=new Promise(async h=>{const u=d=>{d.topic===e&&(this.events.removeListener(us.created,u),h(d.id))};this.events.on(us.created,u);try{const d=await Li(new Promise((p,g)=>{this.relayer.request(n).catch(f=>{this.logger.warn(f,f==null?void 0:f.message),g(f)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(us.created,u),h(d)}catch{}}),c=await Li(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!c&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return c?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Et.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:Oo(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Li(new Promise(r=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Et.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:Oo(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let r;try{r=await await Li(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Et.connection_stalled)}return r}rpcUnsubscribe(e,t,i){const r={method:Oo(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,Zl(_o({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,_o({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,_o({},t)),this.topicMap.set(t.topic,e),this.events.emit(us.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(us.deleted,Zl(_o({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(us.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(us.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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 t=>Zl(_o({},t),{id:await this.getSubscriptionId(t.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await v3(E.toMiliseconds(E.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=j("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 Xs(e+await this.getClientId())}}var DL=Object.defineProperty,Cf=Object.getOwnPropertySymbols,kL=Object.prototype.hasOwnProperty,jL=Object.prototype.propertyIsEnumerable,cu=(s,e,t)=>e in s?DL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Sf=(s,e)=>{for(var t in e||(e={}))kL.call(e,t)&&cu(s,t,e[t]);if(Cf)for(var t of Cf(e))jL.call(e,t)&&cu(s,t,e[t]);return s},fe=(s,e,t)=>cu(s,typeof e!="symbol"?e+"":e,t);class RL extends $D{constructor(e){super(e),fe(this,"protocol","wc"),fe(this,"version",2),fe(this,"core"),fe(this,"logger"),fe(this,"events",new kt.EventEmitter),fe(this,"provider"),fe(this,"messages"),fe(this,"subscriber"),fe(this,"publisher"),fe(this,"name",pR),fe(this,"transportExplicitlyClosed",!1),fe(this,"initialized",!1),fe(this,"connectionAttemptInProgress",!1),fe(this,"relayUrl"),fe(this,"projectId"),fe(this,"packageName"),fe(this,"bundleId"),fe(this,"hasExperiencedNetworkDisruption",!1),fe(this,"pingTimeout"),fe(this,"heartBeatTimeout",E.toMiliseconds(E.THIRTY_SECONDS+E.FIVE_SECONDS)),fe(this,"reconnectTimeout"),fe(this,"connectPromise"),fe(this,"reconnectInProgress",!1),fe(this,"requestsInFlight",[]),fe(this,"connectTimeout",E.toMiliseconds(E.ONE_SECOND*15)),fe(this,"request",async t=>{var i,r;this.logger.debug("Publishing Request Payload");const n=t.id||gs().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((r=t.params)==null?void 0:r.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),fe(this,"resetPingTimeout",()=>{Tc()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),fe(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),fe(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Et.connect)}),fe(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),fe(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(Et.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),fe(this,"registerProviderListeners",()=>{this.provider.on(As.payload,this.onPayloadHandler),this.provider.on(As.connect,this.onConnectHandler),this.provider.on(As.disconnect,this.onDisconnectHandler),this.provider.on(As.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ne(e.logger,this.name):Wn(yi({level:e.logger||dR})),this.messages=new yL(this.logger,e.core),this.subscriber=new xL(this,this.logger),this.publisher=new NL(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Ib,this.projectId=e.projectId,n3()?this.packageName=Tg():o3()&&(this.bundleId=Tg()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return qe(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Ke.relay},pc.outbound)}async subscribe(e,t){var i,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=t==null?void 0:t.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(r=t==null?void 0:t.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",l;const c=h=>{h.topic===e&&(this.subscriber.off(us.created,c),l())};return await Promise.all([new Promise(h=>{l=h,this.subscriber.on(us.created,c)}),new Promise(async(h,u)=>{a=await this.subscriber.subscribe(e,Sf({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&u(d)})||a,h()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Li(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(t,i)=>{await this.connect(e).then(t).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await pf())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,r)=>i.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+(r==null?void 0:r.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const r=dt(E.FIVE_MINUTES),n={topic:i,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(Et.message,e),await this.recordMessageEvent(e,pc.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(As.disconnect,n),await Li(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off(As.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const l=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(As.disconnect,l),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(As.disconnect,l)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const r=i;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(i=>setTimeout(i,E.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,r,n;if(Tc())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(i=this.provider)==null?void 0:i.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ye(new Ow(h3({sdkVersion:su,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:i,message:r}=e;await this.messages.set(i,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,i);return r&&this.logger.warn(`Ignoring duplicate message: ${i}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Vn(e)){if(!e.method.endsWith(gR))return;const t=e.params,{topic:i,message:r,publishedAt:n,attestation:o}=t.data,a={topic:i,message:r,publishedAt:n,transportType:Ke.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Sf({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else $r(e)&&this.events.emit(Et.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,pc.inbound),this.events.emit(Et.message,e))}async acknowledgePayload(e){const t=Wi(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(As.payload,this.onPayloadHandler),this.provider.off(As.connect,this.onConnectHandler),this.provider.off(As.disconnect,this.onDisconnectHandler),this.provider.off(As.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await pf();eR(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Et.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},E.toMiliseconds(fR)))))}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}}function LL(){}function $f(s){if(!s||typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(s)==="[object Object]":!1}function Pf(s){return Object.getOwnPropertySymbols(s).filter(e=>Object.prototype.propertyIsEnumerable.call(s,e))}function Tf(s){return s==null?s===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(s)}const UL="[object RegExp]",zL="[object String]",FL="[object Number]",qL="[object Boolean]",Mf="[object Arguments]",BL="[object Symbol]",HL="[object Date]",WL="[object Map]",VL="[object Set]",KL="[object Array]",GL="[object Function]",YL="[object ArrayBuffer]",Jl="[object Object]",QL="[object Error]",ZL="[object DataView]",JL="[object Uint8Array]",XL="[object Uint8ClampedArray]",eU="[object Uint16Array]",tU="[object Uint32Array]",sU="[object BigUint64Array]",iU="[object Int8Array]",rU="[object Int16Array]",nU="[object Int32Array]",oU="[object BigInt64Array]",aU="[object Float32Array]",cU="[object Float64Array]";function lU(s,e){return s===e||Number.isNaN(s)&&Number.isNaN(e)}function hU(s,e,t){return Do(s,e,void 0,void 0,void 0,void 0,t)}function Do(s,e,t,i,r,n,o){const a=o(s,e,t,i,r,n);if(a!==void 0)return a;if(typeof s==typeof e)switch(typeof s){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return s===e;case"number":return s===e||Object.is(s,e);case"function":return s===e;case"object":return Fo(s,e,n,o)}return Fo(s,e,n,o)}function Fo(s,e,t,i){if(Object.is(s,e))return!0;let r=Tf(s),n=Tf(e);if(r===Mf&&(r=Jl),n===Mf&&(n=Jl),r!==n)return!1;switch(r){case zL:return s.toString()===e.toString();case FL:{const l=s.valueOf(),c=e.valueOf();return lU(l,c)}case qL:case HL:case BL:return Object.is(s.valueOf(),e.valueOf());case UL:return s.source===e.source&&s.flags===e.flags;case GL:return s===e}t=t??new Map;const o=t.get(s),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(s,e),t.set(e,s);try{switch(r){case WL:{if(s.size!==e.size)return!1;for(const[l,c]of s.entries())if(!e.has(l)||!Do(c,e.get(l),l,s,e,t,i))return!1;return!0}case VL:{if(s.size!==e.size)return!1;const l=Array.from(s.values()),c=Array.from(e.values());for(let h=0;h<l.length;h++){const u=l[h],d=c.findIndex(p=>Do(u,p,void 0,s,e,t,i));if(d===-1)return!1;c.splice(d,1)}return!0}case KL:case JL:case XL:case eU:case tU:case sU:case iU:case rU:case nU:case oU:case aU:case cU:{if(typeof _.Buffer<"u"&&_.Buffer.isBuffer(s)!==_.Buffer.isBuffer(e)||s.length!==e.length)return!1;for(let l=0;l<s.length;l++)if(!Do(s[l],e[l],l,s,e,t,i))return!1;return!0}case YL:return s.byteLength!==e.byteLength?!1:Fo(new Uint8Array(s),new Uint8Array(e),t,i);case ZL:return s.byteLength!==e.byteLength||s.byteOffset!==e.byteOffset?!1:Fo(new Uint8Array(s),new Uint8Array(e),t,i);case QL:return s.name===e.name&&s.message===e.message;case Jl:{if(!(Fo(s.constructor,e.constructor,t,i)||$f(s)&&$f(e)))return!1;const l=[...Object.keys(s),...Pf(s)],c=[...Object.keys(e),...Pf(e)];if(l.length!==c.length)return!1;for(let h=0;h<l.length;h++){const u=l[h],d=s[u];if(!Object.hasOwn(e,u))return!1;const p=e[u];if(!Do(d,p,u,s,e,t,i))return!1}return!0}default:return!1}}finally{t.delete(s),t.delete(e)}}function uU(s,e){return hU(s,e,LL)}var dU=Object.defineProperty,Of=Object.getOwnPropertySymbols,pU=Object.prototype.hasOwnProperty,gU=Object.prototype.propertyIsEnumerable,lu=(s,e,t)=>e in s?dU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,xf=(s,e)=>{for(var t in e||(e={}))pU.call(e,t)&&lu(s,t,e[t]);if(Of)for(var t of Of(e))gU.call(e,t)&&lu(s,t,e[t]);return s},Xt=(s,e,t)=>lu(s,typeof e!="symbol"?e+"":e,t);class jr extends PD{constructor(e,t,i,r=ii,n=void 0){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,Xt(this,"map",new Map),Xt(this,"version",mR),Xt(this,"cached",[]),Xt(this,"initialized",!1),Xt(this,"getKey"),Xt(this,"storagePrefix",ii),Xt(this,"recentlyDeleted",[]),Xt(this,"recentlyDeletedLimit",200),Xt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Dt(o)?this.map.set(this.getKey(o),o):Mj(o)?this.map.set(o.id,o):Oj(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Xt(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())}),Xt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Xt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(l=>uU(a[l],o[l]))):this.values)),Xt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const l=xf(xf({},this.getData(o)),a);this.map.set(o,l),await this.persist()}),Xt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Ne(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=j("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:i}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var fU=Object.defineProperty,mU=(s,e,t)=>e in s?fU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,le=(s,e,t)=>mU(s,typeof e!="symbol"?e+"":e,t);class wU{constructor(e,t){this.core=e,this.logger=t,le(this,"name",vR),le(this,"version",IR),le(this,"events",new Kn),le(this,"pairings"),le(this,"initialized",!1),le(this,"storagePrefix",ii),le(this,"ignoredPayloadTypes",[mi]),le(this,"registeredMethods",[]),le(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),le(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),le(this,"create",async i=>{this.isInitialized();const r=eu(),n=await this.core.crypto.setSymKey(r),o=dt(E.FIVE_MINUTES),a={protocol:vb},l={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},c=af({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(lr.create,l),this.core.expirer.set(n,o),await this.pairings.set(n,l),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:c}}),le(this,"pair",async i=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[Js.pairing_started]}});this.isValidPair(i,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:l,methods:c}=of(i.uri);r.props.properties.topic=n,r.addTrace(Js.pairing_uri_validation_success),r.addTrace(Js.pairing_uri_not_expired);let h;if(this.pairings.keys.includes(n)){if(h=this.pairings.get(n),r.addTrace(Js.existing_pairing),h.active)throw r.setError(ui.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(Js.pairing_not_expired)}const u=l||dt(E.FIVE_MINUTES),d={topic:n,relay:a,expiry:u,active:!1,methods:c};this.core.expirer.set(n,u),await this.pairings.set(n,d),r.addTrace(Js.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(lr.create,d),r.addTrace(Js.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(Js.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(ui.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw r.setError(ui.subscribe_pairing_topic_failure),p}return r.addTrace(Js.subscribe_pairing_topic_success),d}),le(this,"activate",async({topic:i})=>{this.isInitialized();const r=dt(E.FIVE_MINUTES);this.core.expirer.set(i,r),await this.pairings.update(i,{active:!0,expiry:r})}),le(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=i;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:l}=or();this.events.once(Ee("pairing_ping",n),({error:c})=>{c?l(c):a()}),await o()}}),le(this,"updateExpiry",async({topic:i,expiry:r})=>{this.isInitialized(),await this.pairings.update(i,{expiry:r})}),le(this,"updateMetadata",async({topic:i,metadata:r})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:r})}),le(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),le(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:r}=i;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Me("USER_DISCONNECTED")),await this.deletePairing(r))}),le(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=i,l=this.core.crypto.keychain.get(r);return af({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:l,relay:n,expiryTimestamp:o,methods:a})}),le(this,"sendRequest",async(i,r,n)=>{const o=Gt(r,n),a=await this.core.crypto.encode(i,o),l=Ao[r].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,l),o.id}),le(this,"sendResult",async(i,r,n)=>{const o=Wi(i,n),a=await this.core.crypto.encode(r,o),l=(await this.core.history.get(r,i)).request.method,c=Ao[l].res;await this.core.relayer.publish(r,a,c),await this.core.history.resolve(o)}),le(this,"sendError",async(i,r,n)=>{const o=ca(i,n),a=await this.core.crypto.encode(r,o),l=(await this.core.history.get(r,i)).request.method,c=Ao[l]?Ao[l].res:Ao.unregistered_method.res;await this.core.relayer.publish(r,a,c),await this.core.history.resolve(o)}),le(this,"deletePairing",async(i,r)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Me("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),r?Promise.resolve():this.core.expirer.del(i)])}),le(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(r=>Ti(r.expiry));await Promise.all(i.map(r=>this.deletePairing(r.topic)))}),le(this,"onRelayEventRequest",async i=>{const{topic:r,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,n);default:return await this.onUnknownRpcMethodRequest(r,n)}}),le(this,"onRelayEventResponse",async i=>{const{topic:r,payload:n}=i,o=(await this.core.history.get(r,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,n);default:return this.onUnknownRpcMethodResponse(o)}}),le(this,"onPairingPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(lr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),le(this,"onPairingPingResponse",(i,r)=>{const{id:n}=r;setTimeout(()=>{vt(r)?this.events.emit(Ee("pairing_ping",n),{}):st(r)&&this.events.emit(Ee("pairing_ping",n),{error:r.error})},500)}),le(this,"onPairingDeleteRequest",async(i,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(lr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),le(this,"onUnknownRpcMethodRequest",async(i,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Me("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),le(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(Me("WC_METHOD_UNSUPPORTED",i))}),le(this,"isValidPair",(i,r)=>{var n;if(!rs(i)){const{message:a}=j("MISSING_OR_INVALID",`pair() params: ${i}`);throw r.setError(ui.malformed_pairing_uri),new Error(a)}if(!Tj(i.uri)){const{message:a}=j("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw r.setError(ui.malformed_pairing_uri),new Error(a)}const o=of(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=j("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(ui.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=j("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(ui.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&E.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(ui.pairing_expired);const{message:a}=j("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),le(this,"isValidPing",async i=>{if(!rs(i)){const{message:n}=j("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),le(this,"isValidDisconnect",async i=>{if(!rs(i)){const{message:n}=j("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),le(this,"isValidPairingTopic",async i=>{if(!at(i,!1)){const{message:r}=j("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(r)}if(!this.pairings.keys.includes(i)){const{message:r}=j("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(r)}if(Ti(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:r}=j("EXPIRED",`pairing topic: ${i}`);throw new Error(r)}}),this.core=e,this.logger=Ne(t,this.name),this.pairings=new jr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return qe(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Et.message,async e=>{const{topic:t,message:i,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==Ke.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(t,i);Vn(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):$r(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(Ss.expired,async e=>{const{topic:t}=Wy(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(lr.expire,{topic:t}))})}}var yU=Object.defineProperty,bU=(s,e,t)=>e in s?yU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Tt=(s,e,t)=>bU(s,typeof e!="symbol"?e+"":e,t);class vU extends _D{constructor(e,t){super(e,t),this.core=e,this.logger=t,Tt(this,"records",new Map),Tt(this,"events",new kt.EventEmitter),Tt(this,"name",ER),Tt(this,"version",AR),Tt(this,"cached",[]),Tt(this,"initialized",!1),Tt(this,"storagePrefix",ii),Tt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Tt(this,"set",(i,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:i,request:{method:r.method,params:r.params||null},chainId:n,expiry:dt(E.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(js.created,o)}),Tt(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const r=await this.getRecord(i.id);typeof r.response>"u"&&(r.response=st(i)?{error:i.error}:{result:i.result},this.records.set(r.id,r),this.persist(),this.events.emit(js.updated,r))}),Tt(this,"get",async(i,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:r}),await this.getRecord(r))),Tt(this,"delete",(i,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===i){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(js.deleted,n)}}),this.persist()}),Tt(this,"exists",async(i,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===i:!1)),Tt(this,"on",(i,r)=>{this.events.on(i,r)}),Tt(this,"once",(i,r)=>{this.events.once(i,r)}),Tt(this,"off",(i,r)=>{this.events.off(i,r)}),Tt(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=Ne(t,this.name)}get context(){return qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:Gt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(js.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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(js.created,e=>{const t=js.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(js.updated,e=>{const t=js.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(js.deleted,e=>{const t=js.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(qs.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{E.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(js.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var IU=Object.defineProperty,EU=(s,e,t)=>e in s?IU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ft=(s,e,t)=>EU(s,typeof e!="symbol"?e+"":e,t);class AU extends MD{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ft(this,"expirations",new Map),Ft(this,"events",new kt.EventEmitter),Ft(this,"name",NR),Ft(this,"version",_R),Ft(this,"cached",[]),Ft(this,"initialized",!1),Ft(this,"storagePrefix",ii),Ft(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ft(this,"has",i=>{try{const r=this.formatTarget(i);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ft(this,"set",(i,r)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(Ss.created,{target:n,expiration:o})}),Ft(this,"get",i=>{this.isInitialized();const r=this.formatTarget(i);return this.getExpiration(r)}),Ft(this,"del",i=>{if(this.isInitialized(),this.has(i)){const r=this.formatTarget(i),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Ss.deleted,{target:r,expiration:n})}}),Ft(this,"on",(i,r)=>{this.events.on(i,r)}),Ft(this,"once",(i,r)=>{this.events.once(i,r)}),Ft(this,"off",(i,r)=>{this.events.off(i,r)}),Ft(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=Ne(t,this.name)}get context(){return qe(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 u3(e);if(typeof e=="number")return d3(e);const{message:t}=j("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Ss.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:i}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;E.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Ss.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(qs.pulse,()=>this.checkExpirations()),this.events.on(Ss.created,e=>{const t=Ss.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Ss.expired,e=>{const t=Ss.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Ss.deleted,e=>{const t=Ss.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var NU=Object.defineProperty,_U=(s,e,t)=>e in s?NU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,nt=(s,e,t)=>_U(s,typeof e!="symbol"?e+"":e,t);class CU extends OD{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,nt(this,"name",CR),nt(this,"abortController"),nt(this,"isDevEnv"),nt(this,"verifyUrlV3",$R),nt(this,"storagePrefix",ii),nt(this,"version",bb),nt(this,"publicKey"),nt(this,"fetchPromise"),nt(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&E.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),nt(this,"register",async r=>{if(!Ia()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=r,l=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const c=Vi(),h=this.startAbortTimer(E.ONE_SECOND*5),u=await new Promise((d,p)=>{const g=()=>{window.removeEventListener("message",y),c.body.removeChild(f),p("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const f=c.createElement("iframe");f.src=l,f.style.display="none",f.addEventListener("error",g,{signal:this.abortController.signal});const y=w=>{if(w.data&&typeof w.data=="string")try{const m=JSON.parse(w.data);if(m.type==="verify_attestation"){if(jn(m.attestation).payload.id!==o)return;clearInterval(h),c.body.removeChild(f),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",y),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};c.body.appendChild(f),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(c){this.logger.warn(c)}return""}),nt(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(jn(n).payload.id!==a)return;const c=await this.isValidJwtAttestation(n);if(c){if(!c.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return c}}if(!o)return;const l=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,l)}),nt(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(E.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),nt(this,"getVerifyUrl",r=>{let n=r||zo;return PR.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${zo}`),n=zo),n}),nt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(E.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),nt(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),nt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),nt(this,"isValidJwtAttestation",async r=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(r,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),nt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),nt(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),nt(this,"validateAttestation",(r,n)=>{const o=wj(r,n.publicKey),a={hasExpired:E.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ne(t,this.name),this.abortController=new AbortController,this.isDevEnv=Fu(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return qe(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),E.toMiliseconds(e))}}var SU=Object.defineProperty,$U=(s,e,t)=>e in s?SU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Df=(s,e,t)=>$U(s,typeof e!="symbol"?e+"":e,t);class PU extends xD{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Df(this,"context",TR),Df(this,"registerDeviceToken",async i=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=i,l=`${MR}/${this.projectId}/clients`;await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=Ne(t,this.context)}}var TU=Object.defineProperty,kf=Object.getOwnPropertySymbols,MU=Object.prototype.hasOwnProperty,OU=Object.prototype.propertyIsEnumerable,hu=(s,e,t)=>e in s?TU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Co=(s,e)=>{for(var t in e||(e={}))MU.call(e,t)&&hu(s,t,e[t]);if(kf)for(var t of kf(e))OU.call(e,t)&&hu(s,t,e[t]);return s},mt=(s,e,t)=>hu(s,typeof e!="symbol"?e+"":e,t);class xU extends DD{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,mt(this,"context",xR),mt(this,"storagePrefix",ii),mt(this,"storageVersion",OR),mt(this,"events",new Map),mt(this,"shouldPersist",!1),mt(this,"init",async()=>{if(!Fu())try{const r={eventId:Og(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:By(this.core.relayer.protocol,this.core.relayer.version,su)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),mt(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:l}}=r,c=Og(),h=this.core.projectId||"",u=Date.now(),d=Co({eventId:c,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:l}},bundleId:h,domain:this.getAppDomain()},this.setMethods(c));return this.telemetryEnabled&&(this.events.set(c,d),this.shouldPersist=!0),d}),mt(this,"getEvent",r=>{const{eventId:n,topic:o}=r;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(l=>l.props.properties.topic===o);if(a)return Co(Co({},a),this.setMethods(a.eventId))}),mt(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),mt(this,"setEventListeners",()=>{this.core.heartbeat.on(qs.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{E.fromMiliseconds(Date.now())-E.fromMiliseconds(r.timestamp)>DR&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),mt(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),mt(this,"addTrace",(r,n)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(n),this.events.set(r,o),this.shouldPersist=!0)}),mt(this,"setError",(r,n)=>{const o=this.events.get(r);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),mt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),mt(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(n=>{this.events.set(n.eventId,Co(Co({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),mt(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[n,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const n of r)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),mt(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${kR}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${su}${n}`,{method:"POST",body:JSON.stringify(r)})}),mt(this,"getAppDomain",()=>qy().url),this.logger=Ne(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var DU=Object.defineProperty,jf=Object.getOwnPropertySymbols,kU=Object.prototype.hasOwnProperty,jU=Object.prototype.propertyIsEnumerable,uu=(s,e,t)=>e in s?DU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Rf=(s,e)=>{for(var t in e||(e={}))kU.call(e,t)&&uu(s,t,e[t]);if(jf)for(var t of jf(e))jU.call(e,t)&&uu(s,t,e[t]);return s},Le=(s,e,t)=>uu(s,typeof e!="symbol"?e+"":e,t);let RU=class xb extends ID{constructor(e){var t;super(e),Le(this,"protocol",yb),Le(this,"version",bb),Le(this,"name",tu),Le(this,"relayUrl"),Le(this,"projectId"),Le(this,"customStoragePrefix"),Le(this,"events",new kt.EventEmitter),Le(this,"logger"),Le(this,"heartbeat"),Le(this,"relayer"),Le(this,"crypto"),Le(this,"storage"),Le(this,"history"),Le(this,"expirer"),Le(this,"pairing"),Le(this,"verify"),Le(this,"echoClient"),Le(this,"linkModeSupportedApps"),Le(this,"eventClient"),Le(this,"initialized",!1),Le(this,"logChunkController"),Le(this,"on",(o,a)=>this.events.on(o,a)),Le(this,"once",(o,a)=>this.events.once(o,a)),Le(this,"off",(o,a)=>this.events.off(o,a)),Le(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),Le(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:l})=>{if(!o||!a)return;const c={topic:o,message:a,publishedAt:Date.now(),transportType:Ke.link_mode};this.relayer.onLinkMessageEvent(c,{sessionExists:l})}),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Ib,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=yi({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:iR.logger,name:tu}),{logger:r,chunkLoggerController:n}=Au({opts:i,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=n,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,a;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((a=this.logChunkController)==null||a.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ne(r,this.name),this.heartbeat=new jm,this.crypto=new hL(this,this.logger,e==null?void 0:e.keychain),this.history=new vU(this,this.logger),this.expirer=new AU(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new uk(Rf(Rf({},rR),e==null?void 0:e.storageOptions)),this.relayer=new RL({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new wU(this,this.logger),this.verify=new CU(this,this.logger,this.storage),this.echoClient=new PU(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new xU(this,this.logger,e==null?void 0:e.telemetryEnabled)}static async init(e){const t=new xb(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(wR,i),t}get context(){return qe(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(mf,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(mf)||[],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}}};const LU=RU,Db="wc",kb=2,jb="client",Qu=`${Db}@${kb}:${jb}:`,Xl={name:jb,logger:"error"},Lf="WALLETCONNECT_DEEPLINK_CHOICE",UU="proposal",Uf="Proposal expired",zU="session",on=E.SEVEN_DAYS,FU="engine",wt={wc_sessionPropose:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1104},res:{ttl:E.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1106},res:{ttl:E.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:E.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1112},res:{ttl:E.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:E.ONE_DAY,prompt:!1,tag:1114},res:{ttl:E.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:E.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:E.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:E.FIVE_MINUTES,prompt:!1,tag:1119}}},eh={min:E.FIVE_MINUTES,max:E.SEVEN_DAYS},Qs={idle:"IDLE",active:"ACTIVE"},zf={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},qU="request",BU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],HU="wc",WU="auth",VU="authKeys",KU="pairingTopics",GU="requests",ol=`${HU}@${1.5}:${WU}:`,gc=`${ol}:PUB_KEY`;var YU=Object.defineProperty,QU=Object.defineProperties,ZU=Object.getOwnPropertyDescriptors,Ff=Object.getOwnPropertySymbols,JU=Object.prototype.hasOwnProperty,XU=Object.prototype.propertyIsEnumerable,du=(s,e,t)=>e in s?YU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,De=(s,e)=>{for(var t in e||(e={}))JU.call(e,t)&&du(s,t,e[t]);if(Ff)for(var t of Ff(e))XU.call(e,t)&&du(s,t,e[t]);return s},Wt=(s,e)=>QU(s,ZU(e)),M=(s,e,t)=>du(s,typeof e!="symbol"?e+"":e,t);class ez extends LD{constructor(e){super(e),M(this,"name",FU),M(this,"events",new Kn),M(this,"initialized",!1),M(this,"requestQueue",{state:Qs.idle,queue:[]}),M(this,"sessionRequestQueue",{state:Qs.idle,queue:[]}),M(this,"requestQueueDelay",E.ONE_SECOND),M(this,"expectedPairingMethodMap",new Map),M(this,"recentlyDeletedMap",new Map),M(this,"recentlyDeletedLimit",200),M(this,"relayMessageCache",[]),M(this,"pendingSessions",new Map),M(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(wt)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},E.toMiliseconds(this.requestQueueDelay)))}),M(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Wt(De({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:l,relays:c}=i;let h=r,u,d=!1;try{if(h){const $=this.client.core.pairing.pairings.get(h);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(${h}) failed`),$}if(!h||!d){const{topic:$,uri:P}=await this.client.core.pairing.create();h=$,u=P}if(!h){const{message:$}=j("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error($)}const p=await this.client.core.crypto.generateKeyPair(),g=wt.wc_sessionPropose.req.ttl||E.FIVE_MINUTES,f=dt(g),y=Wt(De(De({requiredNamespaces:n,optionalNamespaces:o,relays:c??[{protocol:vb}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:f,pairingTopic:h},a&&{sessionProperties:a}),l&&{scopedProperties:l}),{id:qt()}),w=Ee("session_connect",y.id),{reject:m,resolve:b,done:I}=or(g,Uf),N=({id:$})=>{$===y.id&&(this.client.events.off("proposal_expire",N),this.pendingSessions.delete(y.id),this.events.emit(w,{error:{message:Uf,code:0}}))};return this.client.events.on("proposal_expire",N),this.events.once(w,({error:$,session:P})=>{this.client.events.off("proposal_expire",N),$?m($):P&&b(P)}),await this.sendRequest({topic:h,method:"wc_sessionPropose",params:y,throwOnFailedPublish:!0,clientRpcId:y.id}),await this.setProposal(y.id,y),{uri:u,approval:I}}),M(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}}),M(this,"approve",async t=>{var i,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=t==null?void 0:t.id)==null?void 0:i.toString(),trace:[Rs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(C){throw o.setError(tr.no_internet_connection),C}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(C){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(tr.proposal_not_found),C}try{await this.isValidApprove(t)}catch(C){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(tr.session_approve_namespace_validation_failure),C}const{id:a,relayProtocol:l,namespaces:c,sessionProperties:h,scopedProperties:u,sessionConfig:d}=t,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:f,requiredNamespaces:y,optionalNamespaces:w}=p;let m=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});m||(m=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Rs.session_approve_started,properties:{topic:g,trace:[Rs.session_approve_started,Rs.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),I=f.publicKey,N=await this.client.core.crypto.generateSharedKey(b,I),$=De(De(De({relay:{protocol:l??"irn"},namespaces:c,controller:{publicKey:b,metadata:this.client.metadata},expiry:dt(on)},h&&{sessionProperties:h}),u&&{scopedProperties:u}),d&&{sessionConfig:d}),P=Ke.relay;m.addTrace(Rs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(N,{transportType:P})}catch(C){throw m.setError(tr.subscribe_session_topic_failure),C}m.addTrace(Rs.subscribe_session_topic_success);const O=Wt(De({},$),{topic:N,requiredNamespaces:y,optionalNamespaces:w,pairingTopic:g,acknowledged:!1,self:$.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:b,transportType:Ke.relay});await this.client.session.set(N,O),m.addTrace(Rs.store_session);try{m.addTrace(Rs.publishing_session_settle),await this.sendRequest({topic:N,method:"wc_sessionSettle",params:$,throwOnFailedPublish:!0}).catch(C=>{throw m==null||m.setError(tr.session_settle_publish_failure),C}),m.addTrace(Rs.session_settle_publish_success),m.addTrace(Rs.publishing_session_approve),await this.sendResult({id:a,topic:g,result:{relay:{protocol:l??"irn"},responderPublicKey:b},throwOnFailedPublish:!0}).catch(C=>{throw m==null||m.setError(tr.session_approve_publish_failure),C}),m.addTrace(Rs.session_approve_publish_success)}catch(C){throw this.client.logger.error(C),this.client.session.delete(N,Me("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(N),C}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:f.metadata}),await this.client.proposal.delete(a,Me("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(N,dt(on)),{topic:N,acknowledged:()=>Promise.resolve(this.client.session.get(N))}}),M(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:r}=t;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&(await this.sendError({id:i,topic:n,error:r,rpcOpts:wt.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Me("USER_DISCONNECTED")))}),M(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:i,namespaces:r}=t,{done:n,resolve:o,reject:a}=or(),l=qt(),c=gs().toString(),h=this.client.session.get(i).namespaces;return this.events.once(Ee("session_update",l),({error:u})=>{u?a(u):o()}),await this.client.session.update(i,{namespaces:r}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:l,relayRpcId:c}).catch(u=>{this.client.logger.error(u),this.client.session.update(i,{namespaces:h}),a(u)}),{acknowledged:n}}),M(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(l){throw this.client.logger.error("extend() -> isValidExtend() failed"),l}const{topic:i}=t,r=qt(),{done:n,resolve:o,reject:a}=or();return this.events.once(Ee("session_extend",r),({error:l})=>{l?a(l):o()}),await this.setExpiry(i,dt(on)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(l=>{a(l)}),{acknowledged:n}}),M(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:i,request:r,topic:n,expiry:o=wt.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===Ke.relay&&await this.confirmOnlineStateOrThrow();const l=qt(),c=gs().toString(),{done:h,resolve:u,reject:d}=or(o,"Request expired. Please try again.");this.events.once(Ee("session_request",l),({error:w,result:m})=>{w?d(w):u(m)});const p="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:l,relayRpcId:c,topic:n,method:p,params:{request:Wt(De({},r),{expiryTimestamp:dt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:l}),await h();const f={request:Wt(De({},r),{expiryTimestamp:dt(o)}),chainId:i},y=this.shouldSetTVF(p,f);return await Promise.all([new Promise(async w=>{await this.sendRequest(De({clientRpcId:l,relayRpcId:c,topic:n,method:p,params:f,expiry:o,throwOnFailedPublish:!0},y&&{tvf:this.getTVFParams(l,f)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:l}),w()}),new Promise(async w=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const b=await m3(this.client.core.storage,Lf);await p3({id:l,topic:n,wcDeepLink:b})}w()}),h()]).then(w=>w[2])}),M(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:r}=t,{id:n}=r,o=this.client.session.get(i);o.transportType===Ke.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);vt(r)?await this.sendResult({id:n,topic:i,result:r.result,throwOnFailedPublish:!0,appLink:a}):st(r)&&await this.sendError({id:n,topic:i,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),M(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:i}=t;if(this.client.session.keys.includes(i)){const r=qt(),n=gs().toString(),{done:o,resolve:a,reject:l}=or();this.events.once(Ee("session_ping",r),({error:c})=>{c?l(c):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),M(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:r,chainId:n}=t,o=gs().toString(),a=qt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),M(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Me("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:r}=j("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(r)}}),M(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(i=>$j(i,t)))),M(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),M(this,"authenticate",async(t,i)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?Ke.link_mode:Ke.relay;o===Ke.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:l="",uri:c,domain:h,nonce:u,type:d,exp:p,nbf:g,methods:f=[],expiry:y}=t,w=[...t.resources||[]],{topic:m,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:b}});const I=await this.client.core.crypto.generateKeyPair(),N=dc(I);if(await Promise.all([this.client.auth.authKeys.set(gc,{responseTopic:N,publicKey:I}),this.client.auth.pairingTopics.set(N,{topic:N,pairingTopic:m})]),await this.client.core.relayer.subscribe(N,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),f.length>0){const{namespace:A}=xn(a[0]);let z=a4(A,"request",f);uc(w)&&(z=l4(z,w.pop())),w.push(z)}const $=y&&y>wt.wc_sessionAuthenticate.req.ttl?y:wt.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:d??"caip122",chains:a,statement:l,aud:c,domain:h,version:"1",nonce:u,iat:new Date().toISOString(),exp:p,nbf:g,resources:w},requester:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:dt($)},O={eip155:{chains:a,methods:[...new Set(["personal_sign",...f])],events:["chainChanged","accountsChanged"]}},C={requiredNamespaces:{},optionalNamespaces:O,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:dt(wt.wc_sessionPropose.req.ttl),id:qt()},{done:T,resolve:S,reject:R}=or($,"Request expired"),L=qt(),q=Ee("session_connect",C.id),B=Ee("session_request",L),U=async({error:A,session:z})=>{this.events.off(B,H),A?R(A):z&&S({session:z})},H=async A=>{var z,Y,K;if(await this.deletePendingAuthRequest(L,{message:"fulfilled",code:0}),A.error){const He=Me("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return A.error.code===He.code?void 0:(this.events.off(q,U),R(A.error.message))}await this.deleteProposal(C.id),this.events.off(q,U);const{cacaos:be,responder:oe}=A.result,Oe=[],lt=[];for(const He of be){await zg({cacao:He,projectId:this.client.core.projectId})||(this.client.logger.error(He,"Signature verification failed"),R(Me("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Qi}=He,Zi=uc(Qi.resources),so=[Gh(Qi.iss)],cl=Mc(Qi.iss);if(Zi){const Ji=Fg(Zi),ll=qg(Zi);Oe.push(...Ji),so.push(...ll)}for(const Ji of so)lt.push(`${Ji}:${cl}`)}const Be=await this.client.core.crypto.generateSharedKey(I,oe.publicKey);let Qe;Oe.length>0&&(Qe={topic:Be,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:oe,controller:oe.publicKey,expiry:dt(on),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:cf([...new Set(Oe)],[...new Set(lt)]),transportType:o},await this.client.core.relayer.subscribe(Be,{transportType:o}),await this.client.session.set(Be,Qe),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:oe.metadata}),Qe=this.client.session.get(Be)),(z=this.client.metadata.redirect)!=null&&z.linkMode&&(Y=oe.metadata.redirect)!=null&&Y.linkMode&&(K=oe.metadata.redirect)!=null&&K.universal&&i&&(this.client.core.addLinkModeSupportedApp(oe.metadata.redirect.universal),this.client.session.update(Be,{transportType:Ke.link_mode})),S({auths:be,session:Qe})};this.events.once(q,U),this.events.once(B,H);let W;try{if(n){const A=Gt("wc_sessionAuthenticate",P,L);this.client.core.history.set(m,A);const z=await this.client.core.crypto.encode("",A,{type:_a,encoding:Io});W=Ga(i,m,z)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:P,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:L}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:C,expiry:wt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:C.id})])}catch(A){throw this.events.off(q,U),this.events.off(B,H),A}return await this.setProposal(C.id,C),await this.setAuthRequest(L,{request:Wt(De({},P),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:W??b,response:T}}),M(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[sr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw n.setError(No.no_internet_connection),y}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(No.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Ke.relay;a===Ke.relay&&await this.confirmOnlineStateOrThrow();const l=o.requester.publicKey,c=await this.client.core.crypto.generateKeyPair(),h=dc(l),u={type:mi,receiverPublicKey:l,senderPublicKey:c},d=[],p=[];for(const y of r){if(!await zg({cacao:y,projectId:this.client.core.projectId})){n.setError(No.invalid_cacao);const N=Me("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:h,error:N,encodeOpts:u}),new Error(N.message)}n.addTrace(sr.cacaos_verified);const{p:w}=y,m=uc(w.resources),b=[Gh(w.iss)],I=Mc(w.iss);if(m){const N=Fg(m),$=qg(m);d.push(...N),b.push(...$)}for(const N of b)p.push(`${N}:${I}`)}const g=await this.client.core.crypto.generateSharedKey(c,l);n.addTrace(sr.create_authenticated_session_topic);let f;if((d==null?void 0:d.length)>0){f={topic:g,acknowledged:!0,self:{publicKey:c,metadata:this.client.metadata},peer:{publicKey:l,metadata:o.requester.metadata},controller:l,expiry:dt(on),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:cf([...new Set(d)],[...new Set(p)]),transportType:a},n.addTrace(sr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(y){throw n.setError(No.subscribe_authenticated_session_topic_failure),y}n.addTrace(sr.subscribe_authenticated_session_topic_success),await this.client.session.set(g,f),n.addTrace(sr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(sr.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:i,result:{cacaos:r,responder:{publicKey:c,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw n.setError(No.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:f}}),M(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:i,reason:r}=t,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===Ke.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),l=dc(o),c={type:mi,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:l,error:r,encodeOpts:c,rpcOpts:wt.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Me("USER_DISCONNECTED"))}),M(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:r}=t;return eb(i,r)}),M(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),M(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),r=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)===t.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),M(this,"deleteSession",async t=>{var i;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:l}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Me("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(l.publicKey)&&await this.client.core.crypto.deleteKeyPair(l.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Lf).catch(c=>this.client.logger.warn(c)),this.getPendingSessionRequests().forEach(c=>{c.topic===r&&this.deletePendingSessionRequest(c.id,Me("USER_DISCONNECTED"))}),r===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Qs.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),M(this,"deleteProposal",async(t,i)=>{if(i)try{const r=this.client.proposal.get(t),n=this.client.core.eventClient.getEvent({topic:r.pairingTopic});n==null||n.setError(tr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Me("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),M(this,"deletePendingSessionRequest",async(t,i,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==t),r&&(this.sessionRequestQueue.state=Qs.idle,this.client.events.emit("session_request_expire",{id:t}))}),M(this,"deletePendingAuthRequest",async(t,i,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)])}),M(this,"setExpiry",async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))}),M(this,"setProposal",async(t,i)=>{this.client.core.expirer.set(t,dt(wt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),M(this,"setAuthRequest",async(t,i)=>{const{request:r,pairingTopic:n,transportType:o=Ke.relay}=i;this.client.core.expirer.set(t,r.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:t,pairingTopic:n,verifyContext:r.verifyContext,transportType:o})}),M(this,"setPendingSessionRequest",async t=>{const{id:i,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||dt(wt.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:r,params:n,verifyContext:o})}),M(this,"sendRequest",async t=>{const{topic:i,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:l,throwOnFailedPublish:c,appLink:h,tvf:u}=t,d=Gt(r,n,l);let p;const g=!!h;try{const w=g?Io:Ui;p=await this.client.core.crypto.encode(i,d,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),w}let f;if(BU.includes(r)){const w=Xs(JSON.stringify(d)),m=Xs(p);f=await this.client.core.verify.register({id:m,decryptedId:w})}const y=wt[r].req;if(y.attestation=f,o&&(y.ttl=o),a&&(y.id=a),this.client.core.history.set(i,d),g){const w=Ga(h,i,p);await _.global.Linking.openURL(w,this.client.name)}else{const w=wt[r].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=Wt(De({},u),{correlationId:d.id}),c?(w.internal=Wt(De({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,w)):this.client.core.relayer.publish(i,p,w).catch(m=>this.client.logger.error(m))}return d.id}),M(this,"sendResult",async t=>{const{id:i,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:l}=t,c=Wi(i,n);let h;const u=l&&typeof(_.global==null?void 0:_.global.Linking)<"u";try{const g=u?Io:Ui;h=await this.client.core.crypto.encode(r,c,Wt(De({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let d,p;try{d=await this.client.core.history.get(r,i);const g=d.request;try{this.shouldSetTVF(g.method,g.params)&&(p=this.getTVFParams(i,g.params,n))}catch(f){this.client.logger.warn("sendResult() -> getTVFParams() failed",f)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${i}) failed`),g}if(u){const g=Ga(l,r,h);await _.global.Linking.openURL(g,this.client.name)}else{const g=d.request.method,f=wt[g].res;f.tvf=Wt(De({},p),{correlationId:i}),o?(f.internal=Wt(De({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,h,f)):this.client.core.relayer.publish(r,h,f).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(c)}),M(this,"sendError",async t=>{const{id:i,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:l}=t,c=ca(i,n);let h;const u=l&&typeof(_.global==null?void 0:_.global.Linking)<"u";try{const p=u?Io:Ui;h=await this.client.core.crypto.encode(r,c,Wt(De({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),p}let d;try{d=await this.client.core.history.get(r,i)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${r}, ${i}) failed`),p}if(u){const p=Ga(l,r,h);await _.global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,g=a||wt[p].res;this.client.core.relayer.publish(r,h,g)}await this.client.core.history.resolve(c)}),M(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(r=>{let n=!1;Ti(r.expiry)&&(n=!0),this.client.core.crypto.keychain.has(r.topic)||(n=!0),n&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{Ti(r.expiryTimestamp)&&i.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...i.map(r=>this.deleteProposal(r))])}),M(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),M(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),M(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Qs.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=Qs.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Qs.idle}),M(this,"processRequest",async t=>{const{topic:i,payload:r,attestation:n,transportType:o,encryptedId:a}=t,l=r.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:l}))switch(l){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,r);case"wc_sessionPing":return await this.onSessionPingRequest(i,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${l}`)}}),M(this,"onRelayEventResponse",async t=>{const{topic:i,payload:r,transportType:n}=t,o=(await this.client.core.history.get(i,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,r);case"wc_sessionExtend":return this.onSessionExtendResponse(i,r);case"wc_sessionPing":return this.onSessionPingResponse(i,r);case"wc_sessionRequest":return this.onSessionRequestResponse(i,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),M(this,"onRelayEventUnknownPayload",t=>{const{topic:i}=t,{message:r}=j("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),M(this,"shouldIgnorePairingRequest",t=>{const{topic:i,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),M(this,"onSessionProposeRequest",async t=>{const{topic:i,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:l}=r;try{const c=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),c==null||c.setError(ui.proposal_listener_not_found)),this.isValidConnect(De({},r.params));const h=a.expiryTimestamp||dt(wt.wc_sessionPropose.req.ttl),u=De({id:l,pairingTopic:i,expiryTimestamp:h},a);await this.setProposal(l,u);const d=await this.getVerifyContext({attestationId:n,hash:Xs(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});c==null||c.addTrace(Js.emit_session_proposal),this.client.events.emit("session_proposal",{id:l,params:u,verifyContext:d})}catch(c){await this.sendError({id:l,topic:i,error:c,rpcOpts:wt.wc_sessionPropose.autoReject}),this.client.logger.error(c)}}),M(this,"onSessionProposeResponse",async(t,i,r)=>{const{id:n}=i;if(vt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const l=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const c=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:c});const h=await this.client.core.crypto.generateSharedKey(l,c);this.pendingSessions.set(n,{sessionTopic:h,pairingTopic:t,proposalId:n,publicKey:l});const u=await this.client.core.relayer.subscribe(h,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(st(i)){await this.client.proposal.delete(n,Me("USER_DISCONNECTED"));const o=Ee("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),M(this,"onSessionSettleRequest",async(t,i)=>{const{id:r,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:l,namespaces:c,sessionProperties:h,scopedProperties:u,sessionConfig:d}=i.params,p=[...this.pendingSessions.values()].find(y=>y.sessionTopic===t);if(!p)return this.client.logger.error(`Pending session not found for topic ${t}`);const g=this.client.proposal.get(p.proposalId),f=Wt(De(De(De({topic:t,relay:o,expiry:l,namespaces:c,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},h&&{sessionProperties:h}),u&&{scopedProperties:u}),d&&{sessionConfig:d}),{transportType:Ke.relay});await this.client.session.set(f.topic,f),await this.setExpiry(f.topic,f.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:f.peer.metadata}),this.client.events.emit("session_connect",{session:f}),this.events.emit(Ee("session_connect",p.proposalId),{session:f}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(f),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),M(this,"onSessionSettleResponse",async(t,i)=>{const{id:r}=i;vt(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Ee("session_approve",r),{})):st(i)&&(await this.client.session.delete(t,Me("USER_DISCONNECTED")),this.events.emit(Ee("session_approve",r),{error:i.error}))}),M(this,"onSessionUpdateRequest",async(t,i)=>{const{params:r,id:n}=i;try{const o=`${t}_session_update`,a=Eo.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:t,error:Me("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(De({topic:t},r));try{Eo.set(o,n),await this.client.session.update(t,{namespaces:r.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(l){throw Eo.delete(o),l}this.client.events.emit("session_update",{id:n,topic:t,params:r})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}}),M(this,"isRequestOutOfSync",(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3)),M(this,"onSessionUpdateResponse",(t,i)=>{const{id:r}=i,n=Ee("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ee("session_update",r),{}):st(i)&&this.events.emit(Ee("session_update",r),{error:i.error})}),M(this,"onSessionExtendRequest",async(t,i)=>{const{id:r}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,dt(on)),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),M(this,"onSessionExtendResponse",(t,i)=>{const{id:r}=i,n=Ee("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ee("session_extend",r),{}):st(i)&&this.events.emit(Ee("session_extend",r),{error:i.error})}),M(this,"onSessionPingRequest",async(t,i)=>{const{id:r}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),M(this,"onSessionPingResponse",(t,i)=>{const{id:r}=i,n=Ee("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);vt(i)?this.events.emit(Ee("session_ping",r),{}):st(i)&&this.events.emit(Ee("session_ping",r),{error:i.error})},500)}),M(this,"onSessionDeleteRequest",async(t,i)=>{const{id:r}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(Et.publish,async()=>{n(await this.deleteSession({topic:t,id:r}))})}),this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Me("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),M(this,"onSessionRequest",async t=>{var i,r,n;const{topic:o,payload:a,attestation:l,encryptedId:c,transportType:h}=t,{id:u,params:d}=a;try{await this.isValidRequest(De({topic:o},d));const p=this.client.session.get(o),g=await this.getVerifyContext({attestationId:l,hash:Xs(JSON.stringify(Gt("wc_sessionRequest",d,u))),encryptedId:c,metadata:p.peer.metadata,transportType:h}),f={id:u,topic:o,params:d,verifyContext:g};await this.setPendingSessionRequest(f),h===Ke.link_mode&&(i=p.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((r=p.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(p){await this.sendError({id:u,topic:o,error:p}),this.client.logger.error(p)}}),M(this,"onSessionRequestResponse",(t,i)=>{const{id:r}=i,n=Ee("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);vt(i)?this.events.emit(Ee("session_request",r),{result:i.result}):st(i)&&this.events.emit(Ee("session_request",r),{error:i.error})}),M(this,"onSessionEventRequest",async(t,i)=>{const{id:r,params:n}=i;try{const o=`${t}_session_event_${n.event.name}`,a=Eo.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(De({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),Eo.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),M(this,"onSessionAuthenticateResponse",(t,i)=>{const{id:r}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),vt(i)?this.events.emit(Ee("session_request",r),{result:i.result}):st(i)&&this.events.emit(Ee("session_request",r),{error:i.error})}),M(this,"onSessionAuthenticateRequest",async t=>{var i;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:l}=t;try{const{requester:c,authPayload:h,expiryTimestamp:u}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Xs(JSON.stringify(n)),encryptedId:a,metadata:c.metadata,transportType:l}),p={requester:c,pairingTopic:r,id:n.id,authPayload:h,verifyContext:d,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:p,pairingTopic:r,transportType:l}),l===Ke.link_mode&&(i=c.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:d})}catch(c){this.client.logger.error(c);const h=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,l),p={type:mi,receiverPublicKey:h,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:c,encodeOpts:p,rpcOpts:wt.wc_sessionAuthenticate.autoReject,appLink:d})}}),M(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),M(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Qs.idle,this.processSessionRequestQueue()},E.toMiliseconds(this.requestQueueDelay))}),M(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:i})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=Ee("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Ee("session_request",n.request.id),{error:i})})}),M(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Qs.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Qs.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}}),M(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),M(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:Gt("wc_sessionPropose",Wt(De({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id)})}),M(this,"isValidConnect",async t=>{if(!rs(t)){const{message:c}=j("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(c)}const{pairingTopic:i,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:l}=t;if(Dt(i)||await this.isValidPairingTopic(i),!zj(l)){const{message:c}=j("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(c)}if(!Dt(r)&&ra(r)!==0&&this.validateNamespaces(r,"requiredNamespaces"),!Dt(n)&&ra(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Dt(o)||this.validateSessionProps(o,"sessionProperties"),!Dt(a)){this.validateSessionProps(a,"scopedProperties");const c=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(h=>c.includes(h)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(c)}`)}}),M(this,"validateNamespaces",(t,i)=>{const r=Uj(t,"connect()",i);if(r)throw new Error(r.message)}),M(this,"isValidApprove",async t=>{if(!rs(t))throw new Error(j("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:r,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const l=this.client.proposal.get(i),c=Kl(r,"approve()");if(c)throw new Error(c.message);const h=uf(l.requiredNamespaces,r,"approve()");if(h)throw new Error(h.message);if(!at(n,!0)){const{message:u}=j("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(Dt(o)||this.validateSessionProps(o,"sessionProperties"),!Dt(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(d=>u.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),M(this,"isValidReject",async t=>{if(!rs(t)){const{message:n}=j("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:r}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!qj(r)){const{message:n}=j("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),M(this,"isValidSessionSettleRequest",t=>{if(!rs(t)){const{message:c}=j("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(c)}const{relay:i,controller:r,namespaces:n,expiry:o}=t;if(!wb(i)){const{message:c}=j("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}const a=xj(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const l=Kl(n,"onSessionSettleRequest()");if(l)throw new Error(l.message);if(Ti(o)){const{message:c}=j("EXPIRED","onSessionSettleRequest()");throw new Error(c)}}),M(this,"isValidUpdate",async t=>{if(!rs(t)){const{message:l}=j("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(l)}const{topic:i,namespaces:r}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=Kl(r,"update()");if(o)throw new Error(o.message);const a=uf(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),M(this,"isValidExtend",async t=>{if(!rs(t)){const{message:r}=j("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),M(this,"isValidRequest",async t=>{if(!rs(t)){const{message:l}=j("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(l)}const{topic:i,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!hf(a,n)){const{message:l}=j("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(l)}if(!Bj(r)){const{message:l}=j("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(l)}if(!Vj(a,n,r.method)){const{message:l}=j("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(l)}if(o&&!Qj(o,eh)){const{message:l}=j("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${eh.min} and ${eh.max}`);throw new Error(l)}}),M(this,"isValidRespond",async t=>{var i;if(!rs(t)){const{message:o}=j("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(i=t==null?void 0:t.response)!=null&&i.id&&this.cleanupAfterResponse(t),o}if(!Hj(n)){const{message:o}=j("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),M(this,"isValidPing",async t=>{if(!rs(t)){const{message:r}=j("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),M(this,"isValidEmit",async t=>{if(!rs(t)){const{message:a}=j("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:i,event:r,chainId:n}=t;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!hf(o,n)){const{message:a}=j("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Wj(r)){const{message:a}=j("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Kj(o,n,r.name)){const{message:a}=j("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),M(this,"isValidDisconnect",async t=>{if(!rs(t)){const{message:r}=j("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),M(this,"isValidAuthenticate",t=>{const{chains:i,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!at(r,!1))throw new Error("uri is required parameter");if(!at(n,!1))throw new Error("domain is required parameter");if(!at(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(l=>xn(l).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=xn(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),M(this,"getVerifyContext",async t=>{const{attestationId:i,hash:r,encryptedId:n,metadata:o,transportType:a}=t,l={verified:{verifyUrl:o.verifyUrl||zo,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Ke.link_mode){const h=this.getAppLinkIfEnabled(o,a);return l.verified.validation=h&&new URL(h).origin===new URL(o.url).origin?"VALID":"INVALID",l}const c=await this.client.core.verify.resolve({attestationId:i,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});c&&(l.verified.origin=c.origin,l.verified.isScam=c.isScam,l.verified.validation=c.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(c){this.client.logger.warn(c)}return this.client.logger.debug(`Verify context: ${JSON.stringify(l)}`),l}),M(this,"validateSessionProps",(t,i)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=j("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),M(this,"getPendingAuthRequest",t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0}),M(this,"addToRecentlyDeleted",(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=n)break;this.recentlyDeletedMap.delete(o)}}}),M(this,"checkRecentlyDeleted",t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:r}=j("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(r)}}),M(this,"isLinkModeEnabled",(t,i)=>{var r,n,o,a,l,c,h,u,d;return!t||i!==Ke.link_mode?!1:((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((c=(l=this.client.metadata)==null?void 0:l.redirect)==null?void 0:c.universal)!==""&&((h=t==null?void 0:t.redirect)==null?void 0:h.universal)!==void 0&&((u=t==null?void 0:t.redirect)==null?void 0:u.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(_.global==null?void 0:_.global.Linking)<"u"}),M(this,"getAppLinkIfEnabled",(t,i)=>{var r;return this.isLinkModeEnabled(t,i)?(r=t==null?void 0:t.redirect)==null?void 0:r.universal:void 0}),M(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Mg(t,"topic")||"",r=decodeURIComponent(Mg(t,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:Ke.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:r,sessionExists:n})}),M(this,"registerLinkModeListeners",async()=>{var t;if(Fu()||Yi()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=_.global==null?void 0:_.global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await i.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),M(this,"shouldSetTVF",(t,i)=>{if(!i||t!=="wc_sessionRequest")return!1;const{request:r}=i;return Object.keys(zf).includes(r.method)}),M(this,"getTVFParams",(t,i,r)=>{var n,o;try{const a=i.request.method,l=this.extractTxHashesFromResult(a,r);return Wt(De({correlationId:t,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:l})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),M(this,"isValidContractData",t=>{var i;if(!t)return!1;try{const r=(t==null?void 0:t.data)||((i=t==null?void 0:t[0])==null?void 0:i.data);if(!r.startsWith("0x"))return!1;const n=r.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),M(this,"extractTxHashesFromResult",(t,i)=>{try{const r=zf[t];if(typeof i=="string")return[i];const n=i[r.key];if(_r(n))return t==="solana_signAllTransactions"?n.map(o=>K3(o)):n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,r]of Object.entries(t))for(const n of r)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Et.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(gc)?this.client.auth.authKeys.get(gc):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===Ke.link_mode?Io:Ui});Vn(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:Xs(i)})):$r(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,i)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Ss.expired,async e=>{const{topic:t,id:i}=Wy(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,j("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,j("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(lr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(lr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!at(e,!1)){const{message:t}=j("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=j("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Ti(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=j("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!at(e,!1)){const{message:t}=j("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=j("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Ti(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=j("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=j("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(at(e,!1)){const{message:t}=j("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=j("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!Fj(e)){const{message:t}=j("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=j("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Ti(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=j("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class tz extends jr{constructor(e,t){super(e,t,UU,Qu),this.core=e,this.logger=t}}let sz=class extends jr{constructor(e,t){super(e,t,zU,Qu),this.core=e,this.logger=t}};class iz extends jr{constructor(e,t){super(e,t,qU,Qu,i=>i.id),this.core=e,this.logger=t}}class rz extends jr{constructor(e,t){super(e,t,VU,ol,()=>gc),this.core=e,this.logger=t}}class nz extends jr{constructor(e,t){super(e,t,KU,ol),this.core=e,this.logger=t}}class oz extends jr{constructor(e,t){super(e,t,GU,ol,i=>i.id),this.core=e,this.logger=t}}var az=Object.defineProperty,cz=(s,e,t)=>e in s?az(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,th=(s,e,t)=>cz(s,typeof e!="symbol"?e+"":e,t);class lz{constructor(e,t){this.core=e,this.logger=t,th(this,"authKeys"),th(this,"pairingTopics"),th(this,"requests"),this.authKeys=new rz(this.core,this.logger),this.pairingTopics=new nz(this.core,this.logger),this.requests=new oz(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var hz=Object.defineProperty,uz=(s,e,t)=>e in s?hz(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,he=(s,e,t)=>uz(s,typeof e!="symbol"?e+"":e,t);let dz=class Rb extends RD{constructor(e){super(e),he(this,"protocol",Db),he(this,"version",kb),he(this,"name",Xl.name),he(this,"metadata"),he(this,"core"),he(this,"logger"),he(this,"events",new kt.EventEmitter),he(this,"engine"),he(this,"session"),he(this,"proposal"),he(this,"pendingRequest"),he(this,"auth"),he(this,"signConfig"),he(this,"on",(i,r)=>this.events.on(i,r)),he(this,"once",(i,r)=>this.events.once(i,r)),he(this,"off",(i,r)=>this.events.off(i,r)),he(this,"removeListener",(i,r)=>this.events.removeListener(i,r)),he(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),he(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"update",async i=>{try{return await this.engine.update(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"request",async i=>{try{return await this.engine.request(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"find",i=>{try{return this.engine.find(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),he(this,"authenticate",async(i,r)=>{try{return await this.engine.authenticate(i,r)}catch(n){throw this.logger.error(n.message),n}}),he(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),he(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||Xl.name,this.metadata=(e==null?void 0:e.metadata)||qy(),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Wn(yi({level:(e==null?void 0:e.logger)||Xl.logger}));this.core=(e==null?void 0:e.core)||new LU(e),this.logger=Ne(t,this.name),this.session=new sz(this.core,this.logger),this.proposal=new tz(this.core,this.logger),this.pendingRequest=new iz(this.core,this.logger),this.engine=new ez(this),this.auth=new lz(this.core,this.logger)}static async init(e){const t=new Rb(e);return await t.initialize(),t}get context(){return qe(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()},E.toMiliseconds(E.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const qf="error",pz="wss://relay.walletconnect.org",gz="wc",fz="universal_provider",Qa=`${gz}@2:${fz}:`,Lb="https://rpc.walletconnect.org/v1/",An="generic",mz=`${Lb}bundler`,Ms={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function wz(){}function Zu(s){return s==null||typeof s!="object"&&typeof s!="function"}function Ju(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)}function yz(s){if(Zu(s))return s;if(Array.isArray(s)||Ju(s)||s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer)return s.slice(0);const e=Object.getPrototypeOf(s),t=e.constructor;if(s instanceof Date||s instanceof Map||s instanceof Set)return new t(s);if(s instanceof RegExp){const i=new t(s);return i.lastIndex=s.lastIndex,i}if(s instanceof DataView)return new t(s.buffer.slice(0));if(s instanceof Error){const i=new t(s.message);return i.stack=s.stack,i.name=s.name,i.cause=s.cause,i}if(typeof File<"u"&&s instanceof File)return new t([s],s.name,{type:s.type,lastModified:s.lastModified});if(typeof s=="object"){const i=Object.create(e);return Object.assign(i,s)}return s}function Bf(s){return typeof s=="object"&&s!==null}function Ub(s){return Object.getOwnPropertySymbols(s).filter(e=>Object.prototype.propertyIsEnumerable.call(s,e))}function zb(s){return s==null?s===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(s)}const bz="[object RegExp]",Fb="[object String]",qb="[object Number]",Bb="[object Boolean]",Hb="[object Arguments]",vz="[object Symbol]",Iz="[object Date]",Ez="[object Map]",Az="[object Set]",Nz="[object Array]",_z="[object ArrayBuffer]",Cz="[object Object]",Sz="[object DataView]",$z="[object Uint8Array]",Pz="[object Uint8ClampedArray]",Tz="[object Uint16Array]",Mz="[object Uint32Array]",Oz="[object Int8Array]",xz="[object Int16Array]",Dz="[object Int32Array]",kz="[object Float32Array]",jz="[object Float64Array]";function Rz(s,e){return Pn(s,void 0,s,new Map,e)}function Pn(s,e,t,i=new Map,r=void 0){const n=r==null?void 0:r(s,e,t,i);if(n!=null)return n;if(Zu(s))return s;if(i.has(s))return i.get(s);if(Array.isArray(s)){const o=new Array(s.length);i.set(s,o);for(let a=0;a<s.length;a++)o[a]=Pn(s[a],a,t,i,r);return Object.hasOwn(s,"index")&&(o.index=s.index),Object.hasOwn(s,"input")&&(o.input=s.input),o}if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp){const o=new RegExp(s.source,s.flags);return o.lastIndex=s.lastIndex,o}if(s instanceof Map){const o=new Map;i.set(s,o);for(const[a,l]of s)o.set(a,Pn(l,a,t,i,r));return o}if(s instanceof Set){const o=new Set;i.set(s,o);for(const a of s)o.add(Pn(a,void 0,t,i,r));return o}if(typeof _.Buffer<"u"&&_.Buffer.isBuffer(s))return s.subarray();if(Ju(s)){const o=new(Object.getPrototypeOf(s)).constructor(s.length);i.set(s,o);for(let a=0;a<s.length;a++)o[a]=Pn(s[a],a,t,i,r);return o}if(s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer)return s.slice(0);if(s instanceof DataView){const o=new DataView(s.buffer.slice(0),s.byteOffset,s.byteLength);return i.set(s,o),hr(o,s,t,i,r),o}if(typeof File<"u"&&s instanceof File){const o=new File([s],s.name,{type:s.type});return i.set(s,o),hr(o,s,t,i,r),o}if(s instanceof Blob){const o=new Blob([s],{type:s.type});return i.set(s,o),hr(o,s,t,i,r),o}if(s instanceof Error){const o=new s.constructor;return i.set(s,o),o.message=s.message,o.name=s.name,o.stack=s.stack,o.cause=s.cause,hr(o,s,t,i,r),o}if(typeof s=="object"&&Lz(s)){const o=Object.create(Object.getPrototypeOf(s));return i.set(s,o),hr(o,s,t,i,r),o}return s}function hr(s,e,t=s,i,r){const n=[...Object.keys(e),...Ub(e)];for(let o=0;o<n.length;o++){const a=n[o],l=Object.getOwnPropertyDescriptor(s,a);(l==null||l.writable)&&(s[a]=Pn(e[a],a,t,i,r))}}function Lz(s){switch(zb(s)){case Hb:case Nz:case _z:case Sz:case Bb:case Iz:case kz:case jz:case Oz:case xz:case Dz:case Ez:case qb:case Cz:case bz:case Az:case Fb:case vz:case $z:case Pz:case Tz:case Mz:return!0;default:return!1}}function Uz(s,e){return Rz(s,(t,i,r,n)=>{if(typeof s=="object")switch(Object.prototype.toString.call(s)){case qb:case Fb:case Bb:{const o=new s.constructor(s==null?void 0:s.valueOf());return hr(o,s),o}case Hb:{const o={};return hr(o,s),o.length=s.length,o[Symbol.iterator]=s[Symbol.iterator],o}default:return}})}function Hf(s){return Uz(s)}function Wf(s){return s!==null&&typeof s=="object"&&zb(s)==="[object Arguments]"}function zz(s){return Ju(s)}function Fz(s){var t;if(typeof s!="object"||s==null)return!1;if(Object.getPrototypeOf(s)===null)return!0;if(Object.prototype.toString.call(s)!=="[object Object]"){const i=s[Symbol.toStringTag];return i==null||!((t=Object.getOwnPropertyDescriptor(s,Symbol.toStringTag))!=null&&t.writable)?!1:s.toString()===`[object ${i}]`}let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}function qz(s,...e){const t=e.slice(0,-1),i=e[e.length-1];let r=s;for(let n=0;n<t.length;n++){const o=t[n];r=pu(r,o,i,new Map)}return r}function pu(s,e,t,i){if(Zu(s)&&(s=Object(s)),e==null||typeof e!="object")return s;if(i.has(e))return yz(i.get(e));if(i.set(e,s),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const r=[...Object.keys(e),...Ub(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],l=s[o];if(Wf(a)&&(a={...a}),Wf(l)&&(l={...l}),typeof _.Buffer<"u"&&_.Buffer.isBuffer(a)&&(a=Hf(a)),Array.isArray(a))if(typeof l=="object"&&l!=null){const h=[],u=Reflect.ownKeys(l);for(let d=0;d<u.length;d++){const p=u[d];h[p]=l[p]}l=h}else l=[];const c=t(l,a,o,s,e,i);c!=null?s[o]=c:Array.isArray(a)||Bf(l)&&Bf(a)?s[o]=pu(l,a,t,i):l==null&&Fz(a)?s[o]=pu({},a,t,i):l==null&&zz(a)?s[o]=Hf(a):(l===void 0||a!==void 0)&&(s[o]=a)}return s}function Bz(s,...e){return qz(s,...e,wz)}var Hz=Object.defineProperty,Wz=Object.defineProperties,Vz=Object.getOwnPropertyDescriptors,Vf=Object.getOwnPropertySymbols,Kz=Object.prototype.hasOwnProperty,Gz=Object.prototype.propertyIsEnumerable,Kf=(s,e,t)=>e in s?Hz(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Za=(s,e)=>{for(var t in e||(e={}))Kz.call(e,t)&&Kf(s,t,e[t]);if(Vf)for(var t of Vf(e))Gz.call(e,t)&&Kf(s,t,e[t]);return s},Yz=(s,e)=>Wz(s,Vz(e));function ys(s,e,t){var i;const r=xn(s);return((i=e.rpcMap)==null?void 0:i[r.reference])||`${Lb}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Rr(s){return s.includes(":")?s.split(":")[1]:s}function Wb(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function Qz(s,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(s));if(!t.length)return[];const i=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;i.push(...n)}),i}function sh(s={},e={}){const t=Gf(s),i=Gf(e);return Bz(t,i)}function Gf(s){var e,t,i,r;const n={};if(!ra(s))return n;for(const[o,a]of Object.entries(s)){const l=Gu(o)?[o]:a.chains,c=a.methods||[],h=a.events||[],u=a.rpcMap||{},d=xo(o);n[d]=Yz(Za(Za({},n[d]),a),{chains:hc(l,(e=n[d])==null?void 0:e.chains),methods:hc(c,(t=n[d])==null?void 0:t.methods),events:hc(h,(i=n[d])==null?void 0:i.events),rpcMap:Za(Za({},u),(r=n[d])==null?void 0:r.rpcMap)})}return n}function Zz(s){return s.includes(":")?s.split(":")[2]:s}function Yf(s){const e={};for(const[t,i]of Object.entries(s)){const r=i.methods||[],n=i.events||[],o=i.accounts||[],a=Gu(t)?[t]:i.chains?i.chains:Wb(i.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function ih(s){return typeof s=="number"?s:s.includes("0x")?parseInt(s,16):(s=s.includes(":")?s.split(":")[1]:s,isNaN(Number(s))?s:Number(s))}const Vb={},ye=s=>Vb[s],rh=(s,e)=>{Vb[s]=e};var Jz=Object.defineProperty,Xz=(s,e,t)=>e in s?Jz(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,an=(s,e,t)=>Xz(s,typeof e!="symbol"?e+"":e,t);class e8{constructor(e){an(this,"name","polkadot"),an(this,"client"),an(this,"httpProviders"),an(this,"events"),an(this,"namespace"),an(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Rr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var t8=Object.defineProperty,s8=Object.defineProperties,i8=Object.getOwnPropertyDescriptors,Qf=Object.getOwnPropertySymbols,r8=Object.prototype.hasOwnProperty,n8=Object.prototype.propertyIsEnumerable,gu=(s,e,t)=>e in s?t8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Zf=(s,e)=>{for(var t in e||(e={}))r8.call(e,t)&&gu(s,t,e[t]);if(Qf)for(var t of Qf(e))n8.call(e,t)&&gu(s,t,e[t]);return s},Jf=(s,e)=>s8(s,i8(e)),cn=(s,e,t)=>gu(s,typeof e!="symbol"?e+"":e,t);class o8{constructor(e){cn(this,"name","eip155"),cn(this,"client"),cn(this,"chainId"),cn(this,"namespace"),cn(this,"httpProviders"),cn(this,"events"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(Ms.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,t){const i=t||ys(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=parseInt(Rr(t));e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let r=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const n=parseInt(r,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:r}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,r;const n=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0];if(!n)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const o=this.client.session.get(e.topic),a=((r=o==null?void 0:o.sessionProperties)==null?void 0:r.capabilities)||{};if(a!=null&&a[n])return a==null?void 0:a[n];const l=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Jf(Zf({},o.sessionProperties||{}),{capabilities:Jf(Zf({},a||{}),{[n]:l})})})}catch(c){console.warn("Failed to update session with capabilities",c)}return l}async getCallStatus(e){var t,i;const r=this.client.session.get(e.topic),n=(t=r.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from bundler",l,a)}}const o=(i=r.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Gt("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${mz}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var a8=Object.defineProperty,c8=(s,e,t)=>e in s?a8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ln=(s,e,t)=>c8(s,typeof e!="symbol"?e+"":e,t);class l8{constructor(e){ln(this,"name","solana"),ln(this,"client"),ln(this,"httpProviders"),ln(this,"events"),ln(this,"namespace"),ln(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Rr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var h8=Object.defineProperty,u8=(s,e,t)=>e in s?h8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,hn=(s,e,t)=>u8(s,typeof e!="symbol"?e+"":e,t);class d8{constructor(e){hn(this,"name","cosmos"),hn(this,"client"),hn(this,"httpProviders"),hn(this,"events"),hn(this,"namespace"),hn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Rr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var p8=Object.defineProperty,g8=(s,e,t)=>e in s?p8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,un=(s,e,t)=>g8(s,typeof e!="symbol"?e+"":e,t);class f8{constructor(e){un(this,"name","algorand"),un(this,"client"),un(this,"httpProviders"),un(this,"events"),un(this,"namespace"),un(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){if(!this.httpProviders[e]){const i=t||ys(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(Ms.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new Ye(new tt(i,ye("disableProviderPing")))}}var m8=Object.defineProperty,w8=(s,e,t)=>e in s?m8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,dn=(s,e,t)=>w8(s,typeof e!="symbol"?e+"":e,t);class y8{constructor(e){dn(this,"name","cip34"),dn(this,"client"),dn(this,"httpProviders"),dn(this,"events"),dn(this,"namespace"),dn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),r=Rr(t);e[r]=this.createHttpProvider(r,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var b8=Object.defineProperty,v8=(s,e,t)=>e in s?b8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,pn=(s,e,t)=>v8(s,typeof e!="symbol"?e+"":e,t);class I8{constructor(e){pn(this,"name","elrond"),pn(this,"client"),pn(this,"httpProviders"),pn(this,"events"),pn(this,"namespace"),pn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Rr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var E8=Object.defineProperty,A8=(s,e,t)=>e in s?E8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,gn=(s,e,t)=>A8(s,typeof e!="symbol"?e+"":e,t);class N8{constructor(e){gn(this,"name","multiversx"),gn(this,"client"),gn(this,"httpProviders"),gn(this,"events"),gn(this,"namespace"),gn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Rr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var _8=Object.defineProperty,C8=(s,e,t)=>e in s?_8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fn=(s,e,t)=>C8(s,typeof e!="symbol"?e+"":e,t);class S8{constructor(e){fn(this,"name","near"),fn(this,"client"),fn(this,"httpProviders"),fn(this,"events"),fn(this,"namespace"),fn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||ys(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Ms.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace);return typeof i>"u"?void 0:new Ye(new tt(i,ye("disableProviderPing")))}}var $8=Object.defineProperty,P8=(s,e,t)=>e in s?$8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,mn=(s,e,t)=>P8(s,typeof e!="symbol"?e+"":e,t);class T8{constructor(e){mn(this,"name","tezos"),mn(this,"client"),mn(this,"httpProviders"),mn(this,"events"),mn(this,"namespace"),mn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||ys(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Ms.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace);return typeof i>"u"?void 0:new Ye(new tt(i))}}var M8=Object.defineProperty,O8=(s,e,t)=>e in s?M8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,wn=(s,e,t)=>O8(s,typeof e!="symbol"?e+"":e,t);class x8{constructor(e){wn(this,"name",An),wn(this,"client"),wn(this,"httpProviders"),wn(this,"events"),wn(this,"namespace"),wn(this,"chainId"),this.namespace=e.namespace,this.events=ye("events"),this.client=ye("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Ms.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(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=xn(r);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||ys(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ye(new tt(i,ye("disableProviderPing")))}}var D8=Object.defineProperty,k8=Object.defineProperties,j8=Object.getOwnPropertyDescriptors,Xf=Object.getOwnPropertySymbols,R8=Object.prototype.hasOwnProperty,L8=Object.prototype.propertyIsEnumerable,fu=(s,e,t)=>e in s?D8(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ja=(s,e)=>{for(var t in e||(e={}))R8.call(e,t)&&fu(s,t,e[t]);if(Xf)for(var t of Xf(e))L8.call(e,t)&&fu(s,t,e[t]);return s},nh=(s,e)=>k8(s,j8(e)),Ns=(s,e,t)=>fu(s,typeof e!="symbol"?e+"":e,t);let U8=class Kb{constructor(e){Ns(this,"client"),Ns(this,"namespaces"),Ns(this,"optionalNamespaces"),Ns(this,"sessionProperties"),Ns(this,"scopedProperties"),Ns(this,"events",new Kn),Ns(this,"rpcProviders",{}),Ns(this,"session"),Ns(this,"providerOpts"),Ns(this,"logger"),Ns(this,"uri"),Ns(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Wn(yi({level:(e==null?void 0:e.logger)||qf})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Kb(e);return await t.initialize(),t}async request(e,t,i){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Ja({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,r){const n=new Date().getTime();this.request(e,i,r).then(o=>t(null,Wi(n,o))).catch(o=>t(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:Me("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,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:r}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await r();if(this.session=n.session,this.session){const o=Yf(this.session.namespaces);this.namespaces=sh(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await i();this.session=r;const n=Yf(r.namespaces);return this.namespaces=sh(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,r]=this.validateChain(e),n=this.getProvider(i);n.name===An?n.setDefaultChain(`${i}:${r}`,t):n.setDefaultChain(r,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(_r(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}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,t;if(this.client=this.providerOpts.client||await dz.init({core:this.providerOpts.core,logger:this.providerOpts.logger||qf,relayUrl:this.providerOpts.relayUrl||pz,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>xo(t)))];rh("client",this.client),rh("events",this.events),rh("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=Qz(t,this.session),r=Wb(i),n=sh(this.namespaces,this.optionalNamespaces),o=nh(Ja({},n[t]),{accounts:i,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new o8({namespace:o});break;case"algorand":this.rpcProviders[t]=new f8({namespace:o});break;case"solana":this.rpcProviders[t]=new l8({namespace:o});break;case"cosmos":this.rpcProviders[t]=new d8({namespace:o});break;case"polkadot":this.rpcProviders[t]=new e8({namespace:o});break;case"cip34":this.rpcProviders[t]=new y8({namespace:o});break;case"elrond":this.rpcProviders[t]=new I8({namespace:o});break;case"multiversx":this.rpcProviders[t]=new N8({namespace:o});break;case"near":this.rpcProviders[t]=new S8({namespace:o});break;case"tezos":this.rpcProviders[t]=new T8({namespace:o});break;default:this.rpcProviders[An]?this.rpcProviders[An].updateNamespace(o):this.rpcProviders[An]=new x8({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:i}=e;i===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:i,topic:r}=e;if(r!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&_r(o)&&this.events.emit("accountsChanged",o.map(Zz))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,l=xo(o),c=ih(o)!==ih(a)?`${l}:${ih(a)}`:o;this.onChainChanged(c)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i,r;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=t,o=(r=this.client)==null?void 0:r.session.get(e);this.session=nh(Ja({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",nh(Ja({},Me("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Ms.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[An]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t,optionalNamespaces:i,sessionProperties:r,scopedProperties:n}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>xo(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const r=xo(Object.keys(this.namespaces)[0]),n=this.rpcProviders[r].getDefaultChain();return[r,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,r]=this.validateChain(e);r&&(t||this.getProvider(i).setDefaultChain(r),this.namespaces[i]?this.namespaces[i].defaultChain=r:this.namespaces[`${i}:${r}`]?this.namespaces[`${i}:${r}`].defaultChain=r:this.namespaces[`${i}:${r}`]={defaultChain:r},this.events.emit("chainChanged",r),await this.persist("namespaces",this.namespaces))}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,t){var i;const r=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${Qa}/${e}${r}`,t)}async getFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${Qa}/${e}${i}`)}async deleteFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${Qa}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const i of t)i.startsWith(Qa)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const _i={EIP155:"eip155",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED"},Dc={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","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:{[Q.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Q.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Q.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[Q.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[Q.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[Q.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[Q.CONNECTOR_ID.INJECTED]:"Browser Wallet",[Q.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[Q.CONNECTOR_ID.COINBASE]:"Coinbase",[Q.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[Q.CONNECTOR_ID.LEDGER]:"Ledger",[Q.CONNECTOR_ID.SAFE]:"Safe"}},Gb={getCaipTokens(s){if(!s)return;const e={};return Object.entries(s).forEach(([t,i])=>{e[`${_i.EIP155}:${t}`]=i}),e},isLowerCaseMatch(s,e){return(s==null?void 0:s.toLowerCase())===(e==null?void 0:e.toLowerCase())}},Xa={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 ${z8()?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},SOCIALS_TIMEOUT:{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 z8(){return typeof window<"u"}const F8={createLogger(s,e="error"){const t=yi({level:e}),{logger:i}=Au({opts:t});return i.error=(...r)=>{for(const n of r)if(n instanceof Error){s(n,...r);return}s(void 0,...r)},i}},q8="rpc.walletconnect.org";function B8(s,e){const t=new URL("https://rpc.walletconnect.org/v1/");return t.searchParams.set("chainId",s),t.searchParams.set("projectId",e),t.toString()}const oh=["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"],Nn={extendRpcUrlWithProjectId(s,e){let t=!1;try{t=new URL(s).host===q8}catch{t=!1}if(t){const i=new URL(s);return i.searchParams.has("projectId")||i.searchParams.set("projectId",e),i.toString()}return s},isCaipNetwork(s){return"chainNamespace"in s&&"caipNetworkId"in s},getChainNamespace(s){return this.isCaipNetwork(s)?s.chainNamespace:Q.CHAIN.EVM},getCaipNetworkId(s){return this.isCaipNetwork(s)?s.caipNetworkId:`${Q.CHAIN.EVM}:${s.id}`},getDefaultRpcUrl(s,e,t){var r,n,o;const i=(o=(n=(r=s.rpcUrls)==null?void 0:r.default)==null?void 0:n.http)==null?void 0:o[0];return oh.includes(e)?B8(e,t):i||""},extendCaipNetwork(s,{customNetworkImageUrls:e,projectId:t,customRpcUrls:i}){var d,p,g,f,y;const r=this.getChainNamespace(s),n=this.getCaipNetworkId(s),o=(d=s.rpcUrls.default.http)==null?void 0:d[0],a=this.getDefaultRpcUrl(s,n,t),l=((f=(g=(p=s==null?void 0:s.rpcUrls)==null?void 0:p.chainDefault)==null?void 0:g.http)==null?void 0:f[0])||o,c=((y=i==null?void 0:i[n])==null?void 0:y.map(w=>w.url))||[],h=[...c,a],u=[...c];return l&&!u.includes(l)&&u.push(l),{...s,chainNamespace:r,caipNetworkId:n,assets:{imageId:Dc.NetworkImageIds[s.id],imageUrl:e==null?void 0:e[s.id]},rpcUrls:{...s.rpcUrls,default:{http:h},chainDefault:{http:u}}}},extendCaipNetworks(s,{customNetworkImageUrls:e,projectId:t,customRpcUrls:i}){return s.map(r=>Nn.extendCaipNetwork(r,{customNetworkImageUrls:e,customRpcUrls:i,projectId:t}))},getViemTransport(s,e,t){const i=[];if(t==null||t.forEach(r=>{i.push(hl(r.url,r.config))}),oh.includes(s.caipNetworkId)){const r=this.getDefaultRpcUrl(s,s.caipNetworkId,e);i.push(hl(r,{fetchOptions:{headers:{"Content-Type":"text/plain"}}}))}return ad(i)},extendWagmiTransports(s,e,t){if(oh.includes(s.caipNetworkId)){const i=this.getDefaultRpcUrl(s,s.caipNetworkId,e);return ad([t,hl(i)])}return t},getUnsupportedNetwork(s){return{id:s.split(":")[1],caipNetworkId:s,name:Q.UNSUPPORTED_NETWORK_NAME,chainNamespace:s.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(s){var l;const e=G.getActiveCaipNetworkId(),t=v.getAllRequestedCaipNetworks(),i=Array.from(((l=v.state.chains)==null?void 0:l.keys())||[]),r=e==null?void 0:e.split(":")[0],n=r?i.includes(r):!1,o=t==null?void 0:t.find(c=>c.caipNetworkId===e);return n&&!o&&e?this.getUnsupportedNetwork(e):o||s||(t==null?void 0:t[0])}},kc={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0},es=Xe({providers:{...kc},providerIds:{...kc}}),Je={state:es,subscribeKey(s,e){return vs(es,s,e)},subscribe(s){return Yt(es,()=>{s(es)})},subscribeProviders(s){return Yt(es.providers,()=>s(es.providers))},setProvider(s,e){e&&(es.providers[s]=Ir(e))},getProvider(s){return es.providers[s]},setProviderId(s,e){e&&(es.providerIds[s]=e)},getProviderId(s){if(s)return es.providerIds[s]},reset(){es.providers={...kc},es.providerIds={...kc}},resetChain(s){es.providers[s]=void 0,es.providerIds[s]=void 0}},H8={VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},mu={filterOutDuplicatesByRDNS(s){const e=D.state.enableEIP6963?te.state.connectors:[],t=G.getRecentWallets(),i=e.map(a=>{var l;return(l=a.info)==null?void 0:l.rdns}).filter(Boolean),r=t.map(a=>a.rdns).filter(Boolean),n=i.concat(r);if(n.includes("io.metamask.mobile")&&se.isMobile()){const a=n.indexOf("io.metamask.mobile");n[a]="io.metamask"}return s.filter(a=>!n.includes(String(a==null?void 0:a.rdns)))},filterOutDuplicatesByIds(s){const e=te.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),t=G.getRecentWallets(),i=e.map(a=>a.explorerId),r=t.map(a=>a.id),n=i.concat(r);return s.filter(a=>!n.includes(a==null?void 0:a.id))},filterOutDuplicateWallets(s){const e=this.filterOutDuplicatesByRDNS(s);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(s){const{connectors:e}=te.state,t=e.filter(n=>n.type==="ANNOUNCED").reduce((n,o)=>{var a;return(a=o.info)!=null&&a.rdns&&(n[o.info.rdns]=!0),n},{});return s.map(n=>({...n,installed:!!n.rdns&&!!t[n.rdns??""]})).sort((n,o)=>Number(o.installed)-Number(n.installed))},getConnectOrderMethod(s,e){var l;const t=(s==null?void 0:s.connectMethodsOrder)||((l=D.state.features)==null?void 0:l.connectMethodsOrder),i=e||te.state.connectors;if(t)return t;const{injected:r,announced:n}=fc.getConnectorsByType(i,ie.state.recommended,ie.state.featured),o=r.filter(fc.showConnector),a=n.filter(fc.showConnector);return o.length||a.length?["wallet","email","social"]:H8.DEFAULT_CONNECT_METHOD_ORDER}},fc={getConnectorsByType(s,e,t){const{customWallets:i}=D.state,r=G.getRecentWallets(),n=mu.filterOutDuplicateWallets(e),o=mu.filterOutDuplicateWallets(t),a=s.filter(u=>u.type==="MULTI_CHAIN"),l=s.filter(u=>u.type==="ANNOUNCED"),c=s.filter(u=>u.type==="INJECTED"),h=s.filter(u=>u.type==="EXTERNAL");return{custom:i,recent:r,external:h,multiChain:a,announced:l,injected:c,recommended:n,featured:o}},showConnector(s){var r;const e=(r=s.info)==null?void 0:r.rdns,t=!!e&&ie.state.excludedWallets.some(n=>n.rdns===e),i=!!s.name&&ie.state.excludedWallets.some(n=>Gb.isLowerCaseMatch(n.name,s.name));return!(s.type==="INJECTED"&&(!se.isMobile()&&s.name==="Browser Wallet"||!e&&!Ue.checkInstalled()||t||i)||s.type==="ANNOUNCED"&&(t||i))},getIsConnectedWithWC(){return Array.from(v.state.chains.values()).some(t=>te.getConnectorId(t.namespace)===Q.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:s,featured:e,custom:t,recent:i,announced:r,injected:n,multiChain:o,external:a,overriddenConnectors:l=(c=>(c=D.state.features)==null?void 0:c.connectorTypeOrder)()??[]}){const h=fc.getIsConnectedWithWC(),p=[{type:"walletConnect",isEnabled:D.state.enableWalletConnect&&!h},{type:"recent",isEnabled:i.length>0},{type:"injected",isEnabled:[...n,...r,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:t&&t.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:s.length>0}].filter(w=>w.isEnabled),g=new Set(p.map(w=>w.type)),f=l.filter(w=>g.has(w)).map(w=>({type:w,isEnabled:!0})),y=p.filter(({type:w})=>!f.some(({type:b})=>b===w));return Array.from(new Set([...f,...y].map(({type:w})=>w)))}};/**
23
23
  * @license
24
24
  * Copyright 2019 Google LLC
25
25
  * SPDX-License-Identifier: BSD-3-Clause
@@ -913,7 +913,7 @@ ${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+_.Buffer.from(F3(t)).toS
913
913
  .wui-color-fg-350 {
914
914
  background-color: var(--wui-color-fg-350);
915
915
  }
916
- `,ec={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};function $a(s){return{formatters:void 0,fees:void 0,serializers:void 0,...s}}const yu=$a({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"}),bu=$a({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"}),l6=$a({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"});$a({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});$a({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 h6={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"]},iv={getMethodsByChainNamespace(s){return h6[s]||[]},createDefaultNamespace(s){return{methods:this.getMethodsByChainNamespace(s),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(s,e){if(!e)return{...s};const t={...s},i=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>i.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>i.add(r)),e.events&&Object.keys(e.events).forEach(r=>i.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[n]=r.split(":");n&&i.add(n)}),i.forEach(r=>{t[r]||(t[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,n])=>{t[r]&&(t[r].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([r,n])=>{t[r]&&(t[r].chains=n)}),e.events&&Object.entries(e.events).forEach(([r,n])=>{t[r]&&(t[r].events=n)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,l]=n.split(":");!a||!l||!t[a]||(t[a].rpcMap||(t[a].rpcMap={}),r.has(a)||(t[a].rpcMap={},r.add(a)),t[a].rpcMap[l]=o)})}return t},createNamespaces(s,e){const t=s.reduce((i,r)=>{const{id:n,chainNamespace:o,rpcUrls:a}=r,l=a.default.http[0];i[o]||(i[o]=this.createDefaultNamespace(o));const c=`${o}:${n}`,h=i[o];switch(h.chains.push(c),c){case yu.caipNetworkId:h.chains.push(yu.deprecatedCaipNetworkId);break;case bu.caipNetworkId:h.chains.push(bu.deprecatedCaipNetworkId);break}return h!=null&&h.rpcMap&&l&&(h.rpcMap[n]=l),i},{});return this.applyNamespaceOverrides(t,e)},resolveReownName:async s=>{var i;const e=await Sy.resolveName(s);return((i=(Object.values(e==null?void 0:e.addresses)||[])[0])==null?void 0:i.address)||!1},getChainsFromNamespaces(s={}){return Object.values(s).flatMap(e=>{const t=e.chains||[],i=e.accounts.map(r=>{const[n,o]=r.split(":");return`${n}:${o}`});return Array.from(new Set([...t,...i]))})},isSessionEventData(s){return typeof s=="object"&&s!==null&&"id"in s&&"topic"in s&&"params"in s&&typeof s.params=="object"&&s.params!==null&&"chainId"in s.params&&"event"in s.params&&typeof s.params.event=="object"&&s.params.event!==null}};class rv{constructor({provider:e,caipNetworks:t,namespace:i}){this.id=Q.CONNECTOR_ID.WALLET_CONNECT,this.name=Dc.ConnectorNamesMap[Q.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Dc.ConnectorImageIds[Q.CONNECTOR_ID.WALLET_CONNECT],this.caipNetworks=t,this.provider=e,this.chain=i}get chains(){return this.caipNetworks}async connectWalletConnect(){if(!await this.authenticate()){const t=D.state.universalProviderConfigOverride,i=iv.createNamespaces(this.caipNetworks,t);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(t=>t.caipNetworkId);return Lo.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:u6})}}const u6=["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 d6{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,e&&this.construct(e)}construct(e){this.caipNetworks=e.networks,this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.caipNetworks||[]}setAuthProvider(e){this.addConnector({id:Q.CONNECTOR_ID.AUTH,type:"AUTH",name:Q.CONNECTOR_NAMES.AUTH,provider:e,imageId:Dc.ConnectorImageIds[Q.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(i=>t.has(i.id)?!1:(t.add(i.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,t){Z.setStatus(e,t)}on(e,t){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(t)}off(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,t){const i=this.eventListeners.get(e);i&&i.forEach(r=>r(t))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:t,providerType:i}=e;if(!e.provider)return;const r="provider"in e.provider?e.provider.provider:e.provider;if(i==="WALLET_CONNECT"){r.setDefaultChain(t.caipNetworkId);return}if(r&&i==="AUTH"){const n=r;await n.switchNetwork(t.caipNetworkId);const o=await n.getUser({chainId:t.caipNetworkId,preferredAccountType:D.state.defaultAccountTypes[t.chainNamespace]});this.emit("switchNetwork",o)}}getWalletConnectConnector(){const e=this.connectors.find(t=>t instanceof rv);if(!e)throw new Error("WalletConnectConnector not found");return e}}class p6 extends d6{setUniversalProvider(e){this.addConnector(new rv({provider:e,caipNetworks:this.caipNetworks||[],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}){var r,n,o,a;const t=this.provider,i=((a=(o=(n=(r=t==null?void 0:t.session)==null?void 0:r.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(l=>{const[,,c]=l.split(":");return c}).filter((l,c,h)=>h.indexOf(l)===c))||[];return Promise.resolve({accounts:i.map(l=>se.createAccount(e,l,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var n,o,a,l,c;if(!(e.caipNetwork&&os.BALANCE_SUPPORTED_CHAINS.includes((n=e.caipNetwork)==null?void 0:n.chainNamespace))||(o=e.caipNetwork)!=null&&o.testnet)return{balance:"0.00",symbol:((a=e.caipNetwork)==null?void 0:a.nativeCurrency.symbol)||""};if(Z.state.balanceLoading&&e.chainId===((l=v.state.activeCaipNetwork)==null?void 0:l.id))return{balance:Z.state.balance||"0.00",symbol:Z.state.balanceSymbol||""};const r=(await Z.fetchTokenBalance()).find(h=>{var u,d;return h.chainId===`${(u=e.caipNetwork)==null?void 0:u.chainNamespace}:${e.chainId}`&&h.symbol===((d=e.caipNetwork)==null?void 0:d.nativeCurrency.symbol)});return{balance:(r==null?void 0:r.quantity.numeric)||"0.00",symbol:(r==null?void 0:r.symbol)||((c=e.caipNetwork)==null?void 0:c.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,l;const{provider:t,message:i,address:r}=e;if(!t)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return((o=v.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===Q.CHAIN.SOLANA?n=(await t.request({method:"solana_signMessage",params:{message:zy.encode(new TextEncoder().encode(i)),pubkey:r}},(a=v.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:n=await t.request({method:"personal_sign",params:[i,r]},(l=v.state.activeCaipNetwork)==null?void 0:l.caipNetworkId),{signature:n}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async getProfile(){return Promise.resolve({profileImage:"",profileName:""})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}async getEnsAddress(){return Promise.resolve({address:!1})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){var r,n,o,a,l,c;const{caipNetwork:t}=e,i=this.getWalletConnectConnector();if(t.chainNamespace===Q.CHAIN.EVM)try{await((r=i.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:ad(t.id)}]}))}catch(h){if(h.code===ec.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||h.code===ec.ERROR_INVALID_CHAIN_ID||h.code===ec.ERROR_CODE_DEFAULT||((o=(n=h==null?void 0:h.data)==null?void 0:n.originalError)==null?void 0:o.code)===ec.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((c=i.provider)==null?void 0:c.request({method:"wallet_addEthereumChain",params:[{chainId:ad(t.id),rpcUrls:[(a=t==null?void 0:t.rpcUrls.chainDefault)==null?void 0:a.http],chainName:t.name,nativeCurrency:t.nativeCurrency,blockExplorerUrls:[(l=t.blockExplorers)==null?void 0:l.default.url]}]}))}catch{throw new Error("Chain is not supported")}}i.provider.setDefaultChain(t.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(i=>i.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}class g6{constructor(e){var t;this.hasSwitchedToPreferredAccountTypeOnConnect=!1,this.chainNamespaces=[],this.reportedAlertErrors={},this.getCaipNetwork=i=>{var r,n;if(i){const o=(r=v.getNetworkData(i))==null?void 0:r.caipNetwork;return o||((n=v.getRequestedCaipNetworks(i).filter(a=>a.chainNamespace===i))==null?void 0:n[0])}return v.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const i=this.getCaipNetwork();if(i)return i.id},this.getCaipNetworks=i=>v.getRequestedCaipNetworks(i),this.getActiveChainNamespace=()=>v.state.activeChain,this.setRequestedCaipNetworks=(i,r)=>{v.setRequestedCaipNetworks(i,r)},this.getApprovedCaipNetworkIds=()=>v.getAllApprovedCaipNetworkIds(),this.getCaipAddress=i=>v.state.activeChain===i||!i?v.state.activeCaipAddress:v.getAccountProp("caipAddress",i),this.setClientId=i=>{X.setClientId(i)},this.getProvider=i=>Je.getProvider(i),this.getProviderType=i=>Je.getProviderId(i),this.getPreferredAccountType=()=>Z.state.preferredAccountType,this.setCaipAddress=(i,r)=>{Z.setCaipAddress(i,r)},this.setBalance=(i,r,n)=>{Z.setBalance(i,r,n)},this.setProfileName=(i,r)=>{Z.setProfileName(i,r)},this.setProfileImage=(i,r)=>{Z.setProfileImage(i,r)},this.setUser=(i,r)=>{Z.setUser(i,r),D.state.enableEmbedded&&ct.close()},this.resetAccount=i=>{Z.resetAccount(i)},this.setCaipNetwork=i=>{v.setActiveCaipNetwork(i)},this.setCaipNetworkOfNamespace=(i,r)=>{v.setChainNetworkData(r,{caipNetwork:i})},this.setAllAccounts=(i,r)=>{Z.setAllAccounts(i,r),D.setHasMultipleAddresses((i==null?void 0:i.length)>1)},this.setStatus=(i,r)=>{Z.setStatus(i,r),te.isConnected()?G.setConnectionStatus("connected"):G.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=i=>v.getAccountProp("address",i),this.setConnectors=i=>{const r=[...te.getConnectors(),...i];te.setConnectors(r)},this.fetchIdentity=i=>X.fetchIdentity(i),this.getReownName=i=>Sy.getNamesForAddress(i),this.getConnectors=()=>te.getConnectors(),this.getConnectorImage=i=>Ny.getConnectorImage(i),this.setConnectedWalletInfo=(i,r)=>{const n=Je.getProviderId(r),o=i?{...i,type:n}:void 0;Z.setConnectedWalletInfo(o,r)},this.getIsConnectedState=()=>!!v.state.activeCaipAddress,this.addAddressLabel=(i,r,n)=>{Z.addAddressLabel(i,r,n)},this.removeAddressLabel=(i,r)=>{Z.removeAddressLabel(i,r)},this.getAddress=i=>v.state.activeChain===i||!i?Z.state.address:v.getAccountProp("address",i),this.setApprovedCaipNetworksData=i=>v.setApprovedCaipNetworksData(i),this.resetNetwork=i=>{v.resetNetwork(i)},this.addConnector=i=>{te.addConnector(i)},this.resetWcConnection=()=>{Ue.resetWcConnection()},this.setAddressExplorerUrl=(i,r)=>{Z.setAddressExplorerUrl(i,r)},this.setSmartAccountDeployed=(i,r)=>{Z.setSmartAccountDeployed(i,r)},this.setSmartAccountEnabledNetworks=(i,r)=>{v.setSmartAccountEnabledNetworks(i,r)},this.setPreferredAccountType=(i,r)=>{Z.setPreferredAccountType(i,r)},this.setEIP6963Enabled=i=>{D.setEIP6963Enabled(i)},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=[...new Set((t=this.caipNetworks)==null?void 0:t.map(i=>i.chainNamespace))],this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.initialize(e),this.sendInitializeEvent(e)}async initialize(e){this.initControllers(e),await this.initChainAdapters(),await this.injectModalUi(),await this.syncExistingConnection(),fi.set({initialized:!0})}sendInitializeEvent(e){var i;const{...t}=e;delete t.adapters,ze.sendEvent({type:"track",event:"INITIALIZE",properties:{...t,networks:e.networks.map(r=>r.id),siweConfig:{options:((i=e.siweConfig)==null?void 0:i.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&Vt.setThemeMode(e.themeMode),e.themeVariables&&Vt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");v.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&v.setActiveCaipNetwork(t)}initializeConnectionController(e){Ue.setWcBasic(e.basic??!1)}initializeConnectorController(){te.initialize(this.chainNamespaces)}initializeOptionsController(e){var r;D.setDebug(e.debug!==!1),D.setEnableWalletConnect(e.enableWalletConnect!==!1),D.setEnableWalletGuide(e.enableWalletGuide!==!1),D.setEnableWallets(e.enableWallets!==!1),D.setEIP6963Enabled(e.enableEIP6963!==!1),D.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),D.setEnableAuthLogger(e.enableAuthLogger!==!1),D.setCustomRpcUrls(e.customRpcUrls),D.setSdkVersion(e.sdkVersion),D.setProjectId(e.projectId),D.setEnableEmbedded(e.enableEmbedded),D.setAllWallets(e.allWallets),D.setIncludeWalletIds(e.includeWalletIds),D.setExcludeWalletIds(e.excludeWalletIds),D.setFeaturedWalletIds(e.featuredWalletIds),D.setTokens(e.tokens),D.setTermsConditionsUrl(e.termsConditionsUrl),D.setPrivacyPolicyUrl(e.privacyPolicyUrl),D.setCustomWallets(e.customWallets),D.setFeatures(e.features),D.setAllowUnsupportedChain(e.allowUnsupportedChain),D.setDefaultAccountTypes(e.defaultAccountTypes),D.setUniversalProviderConfigOverride(e.universalProviderConfigOverride);const t=this.getDefaultMetaData();if(!e.metadata&&t&&(e.metadata=t),D.setMetadata(e.metadata),D.setDisableAppend(e.disableAppend),D.setEnableEmbedded(e.enableEmbedded),D.setSIWX(e.siwx),!e.projectId){ac.open(Xa.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((r=e.adapters)==null?void 0:r.find(n=>n.namespace===Q.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");D.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,t,i,r;return typeof window<"u"&&typeof document<"u"?{name:((t=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:t.textContent)||"",description:((i=document.querySelector('meta[property="og:description"]'))==null?void 0:i.content)||"",url:window.location.origin,icons:[((r=document.querySelector('link[rel~="icon"]'))==null?void 0:r.href)||""]}:null}setUnsupportedNetwork(e){const t=this.getActiveChainNamespace();if(t){const i=Nn.getUnsupportedNetwork(`${t}:${e}`);v.setActiveCaipNetwork(i)}}getDefaultNetwork(){return Nn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return Nn.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return Nn.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const t=e.networks.find(r=>{var n;return r.id===((n=e.defaultNetwork)==null?void 0:n.id)});return t?Nn.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var n;const e=v.state.activeChain,t=this.getAdapter(e),i=(n=this.getCaipNetwork(e))==null?void 0:n.id;if(!t)throw new Error("Adapter not found");const r=await t.connectWalletConnect(i);this.close(),this.setClientId((r==null?void 0:r.clientId)||null),G.setConnectedNamespaces([...v.state.chains.keys()]),this.chainNamespaces.forEach(o=>{te.setConnectorId(_i.CONNECTOR_TYPE_WALLET_CONNECT,o)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:t,type:i,provider:r,chain:n,caipNetwork:o})=>{var p,g,f,y,w,m,b;const a=v.state.activeChain,l=n||a,c=this.getAdapter(l);if(n&&n!==a&&!o){const I=(p=this.caipNetworks)==null?void 0:p.find(N=>N.chainNamespace===n);I&&this.setCaipNetwork(I)}if(!c)throw new Error("Adapter not found");const h=this.getCaipNetwork(l),u=await c.connect({id:e,info:t,type:i,provider:r,chainId:(o==null?void 0:o.id)||(h==null?void 0:h.id),rpcUrl:((y=(f=(g=o==null?void 0:o.rpcUrls)==null?void 0:g.default)==null?void 0:f.http)==null?void 0:y[0])||((b=(m=(w=h==null?void 0:h.rpcUrls)==null?void 0:w.default)==null?void 0:m.http)==null?void 0:b[0])});if(!u)return;G.addConnectedNamespace(l),this.syncProvider({...u,chainNamespace:l}),await this.syncAccount({...u,chainNamespace:l});const{accounts:d}=await c.getAccounts({namespace:l,id:e});this.setAllAccounts(d,l)},reconnectExternal:async({id:e,info:t,type:i,provider:r})=>{var a;const n=v.state.activeChain,o=this.getAdapter(n);o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:t,type:i,provider:r,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),G.addConnectedNamespace(n))},disconnect:async e=>{const t=e||v.state.activeChain,i=this.getAdapter(t),r=Je.getProvider(t),n=Je.getProviderId(t);await(i==null?void 0:i.disconnect({provider:r,providerType:n})),G.removeConnectedNamespace(t),Je.resetChain(t),this.setUser(void 0,t),this.setStatus("disconnected",t),this.hasSwitchedToPreferredAccountTypeOnConnect=!1},checkInstalled:e=>e?e.some(t=>{var i;return!!((i=window.ethereum)!=null&&i[String(t)])}):!!window.ethereum,signMessage:async e=>{const t=this.getAdapter(v.state.activeChain),i=await(t==null?void 0:t.signMessage({message:e,address:Z.state.address,provider:Je.getProvider(v.state.activeChain)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{if(e.chainNamespace===Q.CHAIN.EVM){const t=this.getAdapter(v.state.activeChain),i=Je.getProvider(v.state.activeChain),r=await(t==null?void 0:t.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}));return(r==null?void 0:r.hash)||""}return""},estimateGas:async e=>{if(e.chainNamespace===Q.CHAIN.EVM){const t=this.getAdapter(v.state.activeChain),i=Je.getProvider(v.state.activeChain),r=this.getCaipNetwork();if(!r)throw new Error("CaipNetwork is undefined");const n=await(t==null?void 0:t.estimateGas({...e,provider:i,caipNetwork:r}));return(n==null?void 0:n.gas)||0n}return 0n},getEnsAvatar:async()=>{var i;const e=this.getAdapter(v.state.activeChain),t=await(e==null?void 0:e.getProfile({address:Z.state.address,chainId:Number((i=this.getCaipNetwork())==null?void 0:i.id)}));return(t==null?void 0:t.profileImage)||!1},getEnsAddress:async e=>{const t=this.getAdapter(v.state.activeChain),i=this.getCaipNetwork();if(!i)return!1;const r=await(t==null?void 0:t.getEnsAddress({name:e,caipNetwork:i}));return(r==null?void 0:r.address)||!1},writeContract:async e=>{const t=this.getAdapter(v.state.activeChain),i=this.getCaipNetwork(),r=this.getCaipAddress(),n=Je.getProvider(v.state.activeChain);if(!i||!r)throw new Error("CaipNetwork or CaipAddress is undefined");const o=await(t==null?void 0:t.writeContract({...e,caipNetwork:i,provider:n,caipAddress:r}));return o==null?void 0:o.hash},parseUnits:(e,t)=>{const i=this.getAdapter(v.state.activeChain);return(i==null?void 0:i.parseUnits({value:e,decimals:t}))??0n},formatUnits:(e,t)=>{const i=this.getAdapter(v.state.activeChain);return(i==null?void 0:i.formatUnits({value:e,decimals:t}))??"0"},getCapabilities:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.getCapabilities(e))},grantPermissions:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.grantPermissions(e))},revokePermissions:async e=>{const t=this.getAdapter(v.state.activeChain);return t!=null&&t.revokePermissions?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.walletGetAssets(e))??{}}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Ue.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){var t,i,r,n,o;if(Je.getProviderId(v.state.activeChain)===_i.CONNECTOR_TYPE_WALLET_CONNECT){const a=(i=(t=this.universalProvider)==null?void 0:t.session)==null?void 0:i.namespaces;return{supportsAllNetworks:((o=(n=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:n.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const t=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=Je.getProvider(t),n=Je.getProviderId(t);if(e.chainNamespace===v.state.activeChain){const o=this.getAdapter(t);await(o==null?void 0:o.switchNetwork({caipNetwork:e,provider:r,providerType:n}))}else if(this.setCaipNetwork(e),n===_i.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(t);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(t=>{const i=t.chains||[],r=t.accounts.map(n=>{const{chainId:o,chainNamespace:a}=Ii.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...i,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((t,i)=>{var n;const r=e==null?void 0:e.find(o=>o.namespace===i);return r?(t[i]=r,t[i].namespace=i,t[i].construct({namespace:i,projectId:(n=this.options)==null?void 0:n.projectId,networks:this.caipNetworks})):t[i]=new p6({namespace:i,networks:this.caipNetworks}),t},{})}async initChainAdapter(e){var t;this.onConnectors(e),this.listenAdapter(e),(t=this.chainAdapters)==null||t[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){const t=this.getAdapter(e);t==null||t.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const t=this.getAdapter(e);if(!t)return;const i=G.getConnectionStatus();i==="connected"?this.setStatus("connecting",e):i==="disconnected"?(G.clearAddressCache(),this.setStatus(i,e)):this.setStatus(i,e),t.on("switchNetwork",({address:r,chainId:n})=>{var c;const o=(c=this.caipNetworks)==null?void 0:c.find(h=>h.id===n||h.caipNetworkId===n),a=v.state.activeChain===e,l=v.getAccountProp("address",e);if(o){const h=a&&r?r:l;h&&this.syncAccount({address:h,chainId:n,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),t.on("disconnect",this.disconnect.bind(this,e)),t.on("pendingTransactions",()=>{const r=Z.state.address,n=v.state.activeCaipNetwork;!r||!(n!=null&&n.id)||this.updateNativeBalance(r,n.id,n.chainNamespace)}),t.on("accountChanged",({address:r,chainId:n})=>{var a,l;const o=v.state.activeChain===e;o&&n?this.syncAccount({address:r,chainId:n,chainNamespace:e}):o&&((a=v.state.activeCaipNetwork)!=null&&a.id)?this.syncAccount({address:r,chainId:(l=v.state.activeCaipNetwork)==null?void 0:l.id,chainNamespace:e}):this.syncAccountInfo(r,n,e)})}async createUniversalProviderForAdapter(e){var t,i,r;await this.getUniversalProvider(),this.universalProvider&&((r=(i=(t=this.chainAdapters)==null?void 0:t[e])==null?void 0:i.setUniversalProvider)==null||r.call(i,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{const t=te.getConnectorId(e);switch(this.setStatus("connecting",e),t){case Q.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case Q.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(t){console.warn("AppKit couldn't sync existing connection",t),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){var o,a,l;const t=this.getAdapter(e),i=te.getConnectorId(e),r=this.getCaipNetwork(e),n=te.getConnectors(e).find(c=>c.id===i);try{if(!t||!n)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(r!=null&&r.id))throw new Error("CaipNetwork not found");const c=await(t==null?void 0:t.syncConnection({namespace:e,id:n.id,chainId:r.id,rpcUrl:(l=(a=(o=r==null?void 0:r.rpcUrls)==null?void 0:o.default)==null?void 0:a.http)==null?void 0:l[0]}));if(c){const h=await(t==null?void 0:t.getAccounts({namespace:e,id:n.id}));h&&h.accounts.length>0?this.setAllAccounts(h.accounts,e):this.setAllAccounts([se.createAccount(e,c.address,"eoa")],e),this.syncProvider({...c,chainNamespace:e}),await this.syncAccount({...c,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async t=>{var a,l,c,h,u;const i=this.getAdapter(t),r=((h=(c=(l=(a=this.universalProvider)==null?void 0:a.session)==null?void 0:l.namespaces)==null?void 0:c[t])==null?void 0:h.accounts)||[],n=(u=v.state.activeCaipNetwork)==null?void 0:u.id,o=r.find(d=>{const{chainId:p}=Ii.parseCaipAddress(d);return p===(n==null?void 0:n.toString())})||r[0];if(o){const d=Ii.validateCaipAddress(o),{chainId:p,address:g}=Ii.parseCaipAddress(d);if(Je.setProviderId(t,_i.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&v.state.activeCaipNetwork&&(i==null?void 0:i.namespace)!==Q.CHAIN.EVM){const f=i==null?void 0:i.getWalletConnectProvider({caipNetworks:this.caipNetworks,provider:this.universalProvider,activeCaipNetwork:v.state.activeCaipNetwork});Je.setProvider(t,f)}else Je.setProvider(t,this.universalProvider);te.setConnectorId(Q.CONNECTOR_ID.WALLET_CONNECT,t),G.addConnectedNamespace(t),this.syncWalletConnectAccounts(t),await this.syncAccount({address:g,chainId:p,chainNamespace:t})}else this.setStatus("disconnected",t);await v.setApprovedCaipNetworksData(t)});await Promise.all(e)}syncWalletConnectAccounts(e){var i,r,n,o,a;const t=(a=(o=(n=(r=(i=this.universalProvider)==null?void 0:i.session)==null?void 0:r.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(l=>{const{address:c}=Ii.parseCaipAddress(l);return c}).filter((l,c,h)=>h.indexOf(l)===c);t&&this.setAllAccounts(t.map(l=>se.createAccount(e,l,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:i,chainNamespace:r}){Je.setProviderId(r,e),Je.setProvider(r,t),te.setConnectorId(i,r)}async syncAccount(e){var u,d,p,g,f,y;const t=e.chainNamespace===v.state.activeChain,i=v.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:n,chainNamespace:o}=e,{chainId:a}=G.getActiveNetworkProps(),l=n||a,c=((u=v.state.activeCaipNetwork)==null?void 0:u.name)===Q.UNSUPPORTED_NETWORK_NAME,h=v.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(c&&!h)&&l){let w=(d=this.caipNetworks)==null?void 0:d.find(I=>I.id.toString()===l.toString()),m=(p=this.caipNetworks)==null?void 0:p.find(I=>I.chainNamespace===o);if(!h&&!w&&!m){const I=this.getApprovedCaipNetworkIds()||[],N=I.find(P=>{var O;return((O=Ii.parseCaipNetworkId(P))==null?void 0:O.chainId)===l.toString()}),$=I.find(P=>{var O;return((O=Ii.parseCaipNetworkId(P))==null?void 0:O.chainNamespace)===o});w=(g=this.caipNetworks)==null?void 0:g.find(P=>P.caipNetworkId===N),m=(f=this.caipNetworks)==null?void 0:f.find(P=>P.caipNetworkId===$||"deprecatedCaipNetworkId"in P&&P.deprecatedCaipNetworkId===$)}const b=w||m;(b==null?void 0:b.chainNamespace)===v.state.activeChain?D.state.enableNetworkSwitch&&!D.state.allowUnsupportedChain&&((y=v.state.activeCaipNetwork)==null?void 0:y.name)===Q.UNSUPPORTED_NETWORK_NAME?v.showUnsupportedChainUI():this.setCaipNetwork(b):t||i&&this.setCaipNetworkOfNamespace(i,o),this.syncConnectedWalletInfo(o),Gb.isLowerCaseMatch(r,Z.state.address)||this.syncAccountInfo(r,b==null?void 0:b.id,o),t?await this.syncBalance({address:r,chainId:b==null?void 0:b.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:i==null?void 0:i.id,chainNamespace:o})}}async syncAccountInfo(e,t,i){const r=this.getCaipAddress(i),n=t||(r==null?void 0:r.split(":")[1]);if(!n)return;const o=`${i}:${n}:${e}`;this.setCaipAddress(o,i),await this.syncIdentity({address:e,chainId:n,chainNamespace:i})}async syncReownName(e,t){try{const i=await this.getReownName(e);if(i[0]){const r=i[0];this.setProfileName(r.name,t)}else this.setProfileName(null,t)}catch{this.setProfileName(null,t)}}syncConnectedWalletInfo(e){var r;const t=te.getConnectorId(e),i=Je.getProviderId(e);if(i===_i.CONNECTOR_TYPE_ANNOUNCED||i===_i.CONNECTOR_TYPE_INJECTED){if(t){const n=this.getConnectors().find(o=>o.id===t);if(n){const{info:o,name:a,imageUrl:l}=n,c=l||this.getConnectorImage(n);this.setConnectedWalletInfo({name:a,icon:c,...o},e)}}}else if(i===_i.CONNECTOR_TYPE_WALLET_CONNECT){const n=Je.getProvider(e);n!=null&&n.session&&this.setConnectedWalletInfo({...n.session.peer.metadata,name:n.session.peer.metadata.name,icon:(r=n.session.peer.metadata.icons)==null?void 0:r[0]},e)}else if(t)if(t===Q.CONNECTOR_ID.COINBASE){const n=this.getConnectors().find(o=>o.id===Q.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(n)},e)}else this.setConnectedWalletInfo({name:t},e)}async syncBalance(e){!Iy.getNetworksByNamespace(this.caipNetworks,e.chainNamespace).find(i=>{var r;return i.id.toString()===((r=e.chainId)==null?void 0:r.toString())})||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async updateNativeBalance(e,t,i){const r=this.getAdapter(i);if(r){const n=await r.getBalance({address:e,chainId:t,caipNetwork:this.getCaipNetwork(i),tokens:this.options.tokens});this.setBalance(n.balance,n.symbol,i)}}async initializeUniversalAdapter(){var i,r,n,o,a,l,c,h,u,d;const e=F8.createLogger((p,...g)=>{p&&this.handleAlertError(p),console.error(...g)}),t={projectId:(i=this.options)==null?void 0:i.projectId,metadata:{name:(r=this.options)!=null&&r.metadata?(n=this.options)==null?void 0:n.metadata.name:"",description:(o=this.options)!=null&&o.metadata?(a=this.options)==null?void 0:a.metadata.description:"",url:(l=this.options)!=null&&l.metadata?(c=this.options)==null?void 0:c.metadata.url:"",icons:(h=this.options)!=null&&h.metadata?(u=this.options)==null?void 0:u.metadata.icons:[""]},logger:e};D.setManualWCControl(!!((d=this.options)!=null&&d.manualWCControl)),this.universalProvider=this.options.universalProvider??await U8.init(t),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{Ue.setUri(e)}),this.universalProvider.on("connect",Ue.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),Ue.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{var r;const t=(r=this.caipNetworks)==null?void 0:r.find(n=>n.id==e),i=this.getCaipNetwork();if(!t){this.setUnsupportedNetwork(e);return}(i==null?void 0:i.id)!==(t==null?void 0:t.id)&&this.setCaipNetwork(t)}),this.universalProvider.on("session_event",e=>{if(iv.isSessionEventData(e)){const{name:t,data:i}=e.params.event;t==="accountsChanged"&&Array.isArray(i)&&se.isCaipAddress(i[0])&&this.syncAccount(Ii.parseCaipAddress(i[0]))}}))}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&se.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){ze.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 t=Object.entries(Xa.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[i,r]=t??[],{message:n,alertErrorKey:o}=r??{};if(i&&n&&!this.reportedAlertErrors[i]){const a=Xa.ALERT_ERRORS[o];a&&(ac.open(a,"error"),this.reportedAlertErrors[i]=!0)}}getAdapter(e){var t;if(e)return(t=this.chainAdapters)==null?void 0:t[e]}createAdapter(e){var r;if(!e)return;const t=e.namespace;if(!t)return;this.createClients();const i=e;i.namespace=t,i.construct({namespace:t,projectId:(r=this.options)==null?void 0:r.projectId,networks:this.caipNetworks}),this.chainNamespaces.includes(t)||this.chainNamespaces.push(t),this.chainAdapters&&(this.chainAdapters[t]=i)}async open(e){await this.injectModalUi(),e!=null&&e.uri&&Ue.setUri(e.uri),await ct.open(e)}async close(){await this.injectModalUi(),ct.close()}setLoading(e,t){ct.setLoading(e,t)}async disconnect(e){await Ue.disconnect(e)}getError(){return""}getChainId(){var e;return(e=v.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e){var i;const t=(i=this.caipNetworks)==null?void 0:i.find(r=>r.id===e.id);if(!t){ac.open(Xa.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await v.switchActiveNetwork(t)}getWalletProvider(){return v.state.activeChain?Je.state.providers[v.state.activeChain]:null}getWalletProviderType(){return Je.getProviderId(v.state.activeChain)}subscribeProviders(e){return Je.subscribeProviders(e)}getThemeMode(){return Vt.state.themeMode}getThemeVariables(){return Vt.state.themeVariables}setThemeMode(e){Vt.setThemeMode(e),sv(Vt.state.themeMode)}setTermsConditionsUrl(e){D.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){D.setPrivacyPolicyUrl(e)}setThemeVariables(e){Vt.setThemeVariables(e),c6(Vt.state.themeVariables)}subscribeTheme(e){return Vt.subscribe(e)}getWalletInfo(){return Z.state.connectedWalletInfo}getAccount(e){const t=te.getAuthConnector(e),i=v.getAccountData(e);if(i)return{allAccounts:i.allAccounts,caipAddress:i.caipAddress,address:se.getPlainAddress(i.caipAddress),isConnected:!!i.caipAddress,status:i.status,embeddedWalletInfo:t?{user:i.user,authProvider:i.socialProvider||"email",accountType:i.preferredAccountType,isSmartAccountDeployed:!!i.smartAccountDeployed}:void 0}}subscribeAccount(e,t){const i=()=>{const r=this.getAccount(t);r&&e(r)};t?v.subscribeChainProp("accountState",i,t):v.subscribe(i),te.subscribe(i)}subscribeNetwork(e){return v.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t==null?void 0:t.id,caipNetworkId:t==null?void 0:t.caipNetworkId})})}subscribeWalletInfo(e){return Z.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){Z.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){v.subscribeKey("activeCaipNetwork",e)}getState(){return fi.state}subscribeState(e){return fi.subscribe(e)}showErrorMessage(e){xt.showError(e)}showSuccessMessage(e){xt.showSuccess(e)}getEvent(){return{...ze.state}}subscribeEvents(e){return ze.subscribe(e)}replace(e){Se.replace(e)}redirect(e){Se.push(e)}popTransactionStack(e){Se.popTransactionStack(e)}isOpen(){return ct.state.open}isTransactionStackEmpty(){return Se.state.transactionStack.length===0}isTransactionShouldReplaceView(){var e;return(e=Se.state.transactionStack[Se.state.transactionStack.length-1])==null?void 0:e.replace}static getInstance(){return this.instance}updateFeatures(e){D.setFeatures(e)}updateOptions(e){const i={...D.state||{},...e};D.setOptions(i)}setConnectMethodsOrder(e){D.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){D.setWalletFeaturesOrder(e)}setCollapseWallets(e){D.setCollapseWallets(e)}setSocialsOrder(e){D.setSocialsOrder(e)}getConnectMethodsOrder(){return mu.getConnectOrderMethod(D.state.features,te.getConnectors())}removeAdapter(e){var n;const t=this.getIsConnectedState(),i=this.getAdapter(e);if(!i||!this.chainAdapters||t)return;const r=(n=this.caipNetworks)==null?void 0:n.filter(o=>o.chainNamespace!==e);v.removeAdapter(e),te.removeAdapter(e),this.chainNamespaces=this.chainNamespaces.filter(o=>o!==e),this.caipNetworks=r,i.removeAllEventListeners(),Reflect.deleteProperty(this.chainAdapters,e)}addAdapter(e,t){const i=e.namespace;if(!this.connectionControllerClient||!this.networkControllerClient||!this.chainAdapters||!i)return;const r=this.extendCaipNetworks({...this.options,networks:t});this.caipNetworks=[...this.caipNetworks||[],...r],this.createAdapter(e),this.initChainAdapter(i),v.addAdapter(e,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient},r)}addNetwork(e,t){var r;if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const i=this.extendCaipNetwork(t,this.options);v.addNetwork(i),this.caipNetworks&&!((r=this.caipNetworks)!=null&&r.find(n=>n.id===i.id))&&this.caipNetworks.push(i)}removeNetwork(e,t){var n;if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);if(!((n=this.caipNetworks)==null?void 0:n.find(o=>o.id===t)))throw new Error(`Network with ID ${t} not found`);if(!this.caipNetworks)return;const r=this.caipNetworks.filter(o=>o.chainNamespace===e&&o.id!==t);if(!(r!=null&&r.length))throw new Error("Cannot remove last network for a namespace");v.removeNetwork(e,t),this.caipNetworks=[...r]}}let hm=!1;class f6 extends g6{async open(e){te.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&Ue.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!hm&&se.isClient()){if(await Vo(()=>import("./basic-BCJkH5GS.js"),__vite__mapDeps([12,13,1,2,14,5,6,7,8,9,10])),await Vo(()=>import("./w3m-modal-DI_ypCY0.js"),__vite__mapDeps([15,13,1,2,5,6,7,8,9,10])),!document.querySelector("w3m-modal")){const t=document.createElement("w3m-modal");!D.state.disableAppend&&!D.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",t)}hm=!0}}}const m6="1.7.2";function w6(s){return new f6({...s,basic:!0,sdkVersion:`html-core-${m6}`})}function y6(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<s.length;c++){const h=s.charAt(c),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=c}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,u=0,d=0;const p=c.length;for(;d!==p&&c[d]===0;)d++,h++;const g=(p-d)*n+1>>>0,f=new Uint8Array(g);for(;d!==p;){let m=c[d],b=0;for(let I=g-1;(m!==0||b<u)&&I!==-1;I--,b++)m+=256*f[I]>>>0,f[I]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");u=b,d++}let y=g-u;for(;y!==g&&f[y]===0;)y++;let w=i.repeat(h);for(;y<g;++y)w+=s.charAt(f[y]);return w}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;c[h]===i;)u++,h++;const p=(c.length-h)*r+1>>>0,g=new Uint8Array(p);for(;h<c.length;){const m=c.charCodeAt(h);if(m>255)return;let b=e[m];if(b===255)return;let I=0;for(let N=p-1;(b!==0||I<d)&&N!==-1;N--,I++)b+=t*g[N]>>>0,g[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=I,h++}let f=p-d;for(;f!==p&&g[f]===0;)f++;const y=new Uint8Array(u+(p-f));let w=u;for(;f!==p;)y[w++]=g[f++];return y}function l(c){const h=a(c);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:l}}var b6="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const uh=y6(b6);class Tn extends Error{constructor(){super(),Object.setPrototypeOf(this,Tn.prototype)}}class um extends Error{constructor(e){super(`WalletConnect Adapter - Method ${e} is not supported by the wallet`),this.name="WalletConnectFeatureNotSupportedError"}}function v6(s){let e=[s];return s===pt.Mainnet||s===pt.Deprecated_Mainnet?(e=[pt.Mainnet,pt.Deprecated_Mainnet],s===pt.Deprecated_Mainnet&&console.warn(Rc.mainnet)):(s===pt.Deprecated_Devnet||s===pt.Devnet)&&(e=[pt.Devnet,pt.Deprecated_Devnet],console.warn(Rc.devnet)),e}const Rc={mainnet:`You are using a deprecated chain ID for Solana Mainnet, please use ${pt.Mainnet} instead.`,devnet:`You are using a deprecated chain ID for Solana Devnet, please use ${pt.Devnet} instead.`,wallet:"The connected wallet is using a deprecated chain ID for Solana. Please, contact them to upgrade. You can learn more at https://github.com/ChainAgnostic/namespaces/blob/main/solana/caip10.md#chain-ids"};function dm(s,e){var i;const t=(i=s.namespaces.solana)==null?void 0:i.accounts.map(r=>`solana:${r.split(":")[1]}`);if(e===pt.Mainnet)return t!=null&&t.find(r=>r===pt.Mainnet)?pt.Mainnet:(console.warn(Rc.wallet),pt.Deprecated_Mainnet);if(e===pt.Devnet)return t!=null&&t.find(r=>r===pt.Devnet)?pt.Devnet:(console.warn(Rc.wallet),pt.Deprecated_Devnet);throw Error("WalletConnect Solana Adapter: Unable to get a default chain from the session.")}function I6(s){return{optionalNamespaces:{solana:{chains:v6(s),methods:[$s.signTransaction,$s.signMessage],events:[]}}}}class sd extends Error{constructor(){super("QR Code Modal was closed by user"),Object.setPrototypeOf(this,sd.prototype),this.name="QRCodeModalError"}}class E6{constructor(e){Nt(this,"_UniversalProvider");Nt(this,"_session");Nt(this,"_modal");Nt(this,"_projectId");Nt(this,"_network");Nt(this,"_ConnectQueueResolver");if(this.initClient(e.options),this._network=e.network,!e.options.projectId)throw Error("WalletConnect Adapter: Project ID is undefined");this._projectId=e.options.projectId}async connect(){var r,n,o,a,l,c;if(this._UniversalProvider||await new Promise(h=>{this._ConnectQueueResolver=h}),!this._UniversalProvider)throw new Error("WalletConnect Adapter - Universal Provider was undefined while calling 'connect()'");if(this._UniversalProvider.session){this._session=this._UniversalProvider.session;const h=dm(this._session,this._network);return this._network=h,this._UniversalProvider.setDefaultChain(h),{publicKey:this.publicKey}}await this.initModal();const e=I6(this._network);(r=this._modal)==null||r.open();const t=new AbortController,i=t.signal;(n=this._modal)==null||n.subscribeState(h=>{h.open||t.abort(new sd)});try{const h=await Promise.race([(o=this._UniversalProvider)==null?void 0:o.connect(e),new Promise((d,p)=>{i.addEventListener("abort",()=>{p(i.reason)})})]);if((a=this._modal)==null||a.close(),this._session=h,!h)throw new Fc;const u=dm(h,this._network);return this._network=u,(l=this._UniversalProvider)==null||l.setDefaultChain(u),{publicKey:this.publicKey}}catch(h){throw(c=this._modal)==null||c.close(),h}}async disconnect(){var e;if((e=this._UniversalProvider)!=null&&e.session){if(await this.initModal(),!this._modal)throw Error("WalletConnect Adapter -Modal is undefined: unable to disconnect");await this.client.disconnect(),this._session=void 0}else throw new Tn}get client(){if(this._UniversalProvider)return this._UniversalProvider;throw new Tn}get session(){if(!this._session)throw new Tn;return this._session}get publicKey(){var e,t,i;if((e=this._UniversalProvider)!=null&&e.session&&this._session){const{address:r}=EI(((i=(t=this._session)==null?void 0:t.namespaces.solana)==null?void 0:i.accounts[0])??"");return new ei(r)}throw new Tn}async signTransaction(e){this.checkIfWalletSupportsMethod($s.signTransaction);const t=pi(e),i=t?{}:e,{signature:r,transaction:n}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:$s.signTransaction,params:{...i,transaction:this.serialize(e)}}});return n?this.deserialize(n,t):(e.addSignature(this.publicKey,_.Buffer.from(uh.decode(r))),e)}async signMessage(e){this.checkIfWalletSupportsMethod($s.signMessage);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:$s.signMessage,params:{pubkey:this.publicKey.toString(),message:uh.encode(e)}}});return uh.decode(t)}async signAndSendTransaction(e){this.checkIfWalletSupportsMethod($s.signAndSendTransaction);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:$s.signAndSendTransaction,params:{transaction:this.serialize(e)}}});return t}async signAllTransactions(e){try{this.checkIfWalletSupportsMethod($s.signAllTransactions);const t=e.map(r=>this.serialize(r)),{transactions:i}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:$s.signAllTransactions,params:{transactions:t}}});return e.map((r,n)=>pi(r)?this.deserialize(i[n]??"",!0):this.deserialize(i[n]??""))}catch(t){if(t instanceof um){const i=e.map(n=>this.signTransaction(n));return await Promise.all(i)}throw t}}async initClient(e){const t=await Bx.init(e);this._UniversalProvider=t,this._ConnectQueueResolver&&this._ConnectQueueResolver(!0)}async initModal(){if(!this._modal){if(!this._UniversalProvider)throw new Error("WalletConnect Adapter - cannot init modal when Universal Provider is undefined");this._modal=w6({projectId:this._projectId,universalProvider:this._UniversalProvider,networks:[yu,bu,l6],manualWCControl:!0})}}serialize(e){return _.Buffer.from(e.serialize({verifySignatures:!1})).toString("base64")}deserialize(e,t=!1){return t?dh.deserialize(_.Buffer.from(e,"base64")):ph.from(_.Buffer.from(e,"base64"))}checkIfWalletSupportsMethod(e){var t;if(!((t=this.session.namespaces.solana)!=null&&t.methods.includes(e)))throw new um(e)}}const A6="WalletConnect";class N6 extends Nu{constructor(t){super();Nt(this,"name",A6);Nt(this,"url","https://walletconnect.org");Nt(this,"icon","data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjE4NSIgdmlld0JveD0iMCAwIDMwMCAxODUiIHdpZHRoPSIzMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTYxLjQzODU0MjkgMzYuMjU2MjYxMmM0OC45MTEyMjQxLTQ3Ljg4ODE2NjMgMTI4LjIxMTk4NzEtNDcuODg4MTY2MyAxNzcuMTIzMjA5MSAwbDUuODg2NTQ1IDUuNzYzNDE3NGMyLjQ0NTU2MSAyLjM5NDQwODEgMi40NDU1NjEgNi4yNzY1MTEyIDAgOC42NzA5MjA0bC0yMC4xMzY2OTUgMTkuNzE1NTAzYy0xLjIyMjc4MSAxLjE5NzIwNTEtMy4yMDUzIDEuMTk3MjA1MS00LjQyODA4MSAwbC04LjEwMDU4NC03LjkzMTE0NzljLTM0LjEyMTY5Mi0zMy40MDc5ODE3LTg5LjQ0Mzg4Ni0zMy40MDc5ODE3LTEyMy41NjU1Nzg4IDBsLTguNjc1MDU2MiA4LjQ5MzYwNTFjLTEuMjIyNzgxNiAxLjE5NzIwNDEtMy4yMDUzMDEgMS4xOTcyMDQxLTQuNDI4MDgwNiAwbC0yMC4xMzY2OTQ5LTE5LjcxNTUwMzFjLTIuNDQ1NTYxMi0yLjM5NDQwOTItMi40NDU1NjEyLTYuMjc2NTEyMiAwLTguNjcwOTIwNHptMjE4Ljc2Nzc5NjEgNDAuNzczNzQ0OSAxNy45MjE2OTcgMTcuNTQ2ODk3YzIuNDQ1NTQ5IDIuMzk0Mzk2OSAyLjQ0NTU2MyA2LjI3NjQ3NjkuMDAwMDMxIDguNjcwODg5OWwtODAuODEwMTcxIDc5LjEyMTEzNGMtMi40NDU1NDQgMi4zOTQ0MjYtNi40MTA1ODIgMi4zOTQ0NTMtOC44NTYxNi4wMDAwNjItLjAwMDAxLS4wMDAwMS0uMDAwMDIyLS4wMDAwMjItLjAwMDAzMi0uMDAwMDMybC01Ny4zNTQxNDMtNTYuMTU0NTcyYy0uNjExMzktLjU5ODYwMi0xLjYwMjY1LS41OTg2MDItMi4yMTQwNCAwLS4wMDAwMDQuMDAwMDA0LS4wMDAwMDcuMDAwMDA4LS4wMDAwMTEuMDAwMDExbC01Ny4zNTI5MjEyIDU2LjE1NDUzMWMtMi40NDU1MzY4IDIuMzk0NDMyLTYuNDEwNTc1NSAyLjM5NDQ3Mi04Ljg1NjE2MTIuMDAwMDg3LS4wMDAwMTQzLS4wMDAwMTQtLjAwMDAyOTYtLjAwMDAyOC0uMDAwMDQ0OS0uMDAwMDQ0bC04MC44MTI0MTk0My03OS4xMjIxODVjLTIuNDQ1NTYwMjEtMi4zOTQ0MDgtMi40NDU1NjAyMS02LjI3NjUxMTUgMC04LjY3MDkxOTdsMTcuOTIxNzI5NjMtMTcuNTQ2ODY3M2MyLjQ0NTU2MDItMi4zOTQ0MDgyIDYuNDEwNTk4OS0yLjM5NDQwODIgOC44NTYxNjAyIDBsNTcuMzU0OTc3NSA1Ni4xNTUzNTdjLjYxMTM5MDguNTk4NjAyIDEuNjAyNjQ5LjU5ODYwMiAyLjIxNDAzOTggMCAuMDAwMDA5Mi0uMDAwMDA5LjAwMDAxNzQtLjAwMDAxNy4wMDAwMjY1LS4wMDAwMjRsNTcuMzUyMTAzMS01Ni4xNTUzMzNjMi40NDU1MDUtMi4zOTQ0NjMzIDYuNDEwNTQ0LTIuMzk0NTUzMSA4Ljg1NjE2MS0uMDAwMi4wMDAwMzQuMDAwMDMzNi4wMDAwNjguMDAwMDY3My4wMDAxMDEuMDAwMTAxbDU3LjM1NDkwMiA1Ni4xNTU0MzJjLjYxMTM5LjU5ODYwMSAxLjYwMjY1LjU5ODYwMSAyLjIxNDA0IDBsNTcuMzUzOTc1LTU2LjE1NDMyNDljMi40NDU1NjEtMi4zOTQ0MDkyIDYuNDEwNTk5LTIuMzk0NDA5MiA4Ljg1NjE2IDB6IiBmaWxsPSIjM2I5OWZjIi8+PC9zdmc+");Nt(this,"supportedTransactionVersions",new Set(["legacy",0]));Nt(this,"_publicKey");Nt(this,"_connecting");Nt(this,"_wallet");Nt(this,"_config");Nt(this,"_readyState");Nt(this,"_onDisconnect");this._publicKey=null,this._connecting=!1,this._config=t,this._wallet=null,this._readyState=typeof window>"u"?ne.Unsupported:ne.Loadable,this._onDisconnect=this.disconnect.bind(this)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Loadable)throw new Ki;this._connecting=!0,this._wallet=new E6({network:this._config.network===Ko.Mainnet?Ic.Mainnet:Ic.Devnet,options:this._config.options});const{publicKey:t}=await this._wallet.connect();this._publicKey=t,this.emit("connect",t),this._wallet.client.on("session_delete",this._onDisconnect)}catch(t){throw t.constructor.name==="QRCodeModalError"||t instanceof Error&&t.name==="QRCodeModalError"?new _v:(this._connecting=!1,t)}finally{this._connecting=!1}}async disconnect(){const t=this._wallet;if(t){t.client.off("session_delete",this._onDisconnect),this._publicKey=null;try{t.client.session&&await t.disconnect()}catch(i){console.error("WalletConnectWalletAdapter: disconnect error",i),this.emit("error",new la(i==null?void 0:i.message,i))}}this.emit("disconnect")}async signTransaction(t){try{const i=this._wallet;if(!i)throw new Fe;try{return await i.signTransaction(t)}catch(r){throw new et(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signMessage(t){try{const i=this._wallet;if(!i)throw new Fe;try{return await i.signMessage(t)}catch(r){throw new ha(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signAndSendTransaction(t){try{const i=this._wallet;if(!i)throw new Fe;try{return await i.signAndSendTransaction(t)}catch(r){throw new et(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signAllTransactions(t){try{const i=this._wallet;if(!i)throw new Fe;try{return await i.signAllTransactions(t)}catch(r){throw new et(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}}const _6={icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgdmlld0JveD0iMCAwIDI1NiAyNTYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8yMDM1XzExMDYpIj4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IiM1NEZGRjUiLz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjBfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTEzLjQ4MDYgMTk4LjYwNUMtMjkuMzI3NiAzMTkuMDQzIDE5OS42NjEgMjg1LjAyNyAzMTkuNTA3IDI1Mi45NjRDNDQyLjE2NSAyMTIuMjU5IDM1Ny4zODYgMzIuODI2OSAyNjkuNDE1IDI4Ljg1NThDMTgxLjQ0MyAyNC44ODQ3IDI4MC4zMjIgMTExLjgyNCAyMDUuNTk1IDEzNi42NTZDMTMwLjg2OCAxNjEuNDg3IDY2Ljk5MDcgNDguMDU4MyAxMy40ODA2IDE5OC42MDVaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjxnIGZpbHRlcj0idXJsKCNmaWx0ZXIxX2ZfMjAzNV8xMTA2KSI+CjxwYXRoIGQ9Ik04NS41MTE4IC00NS44MjI1QzYzLjA1NjIgLTEwNy4xNzYgLTE2LjkxODkgLTIzLjk5NTMgLTU0LjA5OTUgMjUuMjY0M0MtODkuNTY1MiA3OC44NDc5IDMuMDA5MzcgMTI1LjE1MiAzOS4zMjA4IDEwMC4wMzdDNzUuNjMyMyA3NC45MjI3IDcuNzc0NDggNzAuMDM2MyAyOS4zNzA4IDM3LjM3ODVDNTAuOTY3MSA0LjcyMDc2IDExMy41ODEgMzAuODY5NSA4NS41MTE4IC00NS44MjI1WiIgZmlsbD0iIzAwRkZGMCIgZmlsbC1vcGFjaXR5PSIwLjY3Ii8+CjwvZz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjJfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTk2LjQ3OTYgMjI1LjQyNEM2NS44NTAyIDEyMi4zNjMgLTY2LjA4MTggMTc2LjYzNyAtMTI4LjIxOSAyMTYuNjU3Qy0xODcuOTkgMjY0LjA0MiAtNDYuMDcxMSA0MDAuMzQ4IDEyLjg3MjUgMzkzLjM3NkM3MS44MTYxIDM4Ni40MDMgLTM0LjQxMTggMzI3LjA2NSAxLjk4NzAyIDI5OC4xN0MzOC4zODU4IDI2OS4yNzYgMTM0Ljc2NiAzNTQuMjQ5IDk2LjQ3OTYgMjI1LjQyNFoiIGZpbGw9IiM5RDgxRkYiLz4KPC9nPgo8ZyBmaWx0ZXI9InVybCgjZmlsdGVyM19mXzIwMzVfMTEwNikiPgo8cGF0aCBkPSJNMjgyLjEyIC0xMDcuMzUzQzIxNi4wNDcgLTE4Ni4wMzEgMTIxLjQ2MyAtMTIwLjk3IDgyLjQyOTYgLTc4LjYwNDdDNDguMjczOSAtMzAuNjQ0NiAyMjQuMjc1IDU3LjIzMTIgMjczLjEyMSA0Mi4xNzE0QzMyMS45NjggMjcuMTExNSAyMDYuNTEyIC00LjA1MDM4IDIyNy4yOTcgLTMzLjI4NzlDMjQ4LjA4MiAtNjIuNTI1NSAzNjQuNzEyIC05LjAwNTY2IDI4Mi4xMiAtMTA3LjM1M1oiIGZpbGw9IiM0RDk0RkYiLz4KPC9nPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkzLjE4OSAxNTIuODM2SDEzNi42NzRMODcuMjA4NiAxMDMuMDUxTDEzNy4zMSA1My4yNjYzTDE1MC45NTUgNDBIMTA1LjgxOUw0OC4zMzU5IDk3Ljc3NzNDNDUuNDM0OSAxMDAuNjg5IDQ1LjQ0OTggMTA1LjQwMiA0OC4zNjU2IDEwOC4yOTlMOTMuMTg5IDE1Mi44MzZaTTExOS4zMyAxMDMuMTY4SDExOC45OTVMMTE5LjMyNiAxMDMuMTY0TDExOS4zMyAxMDMuMTY4Wk0xMTkuMzMgMTAzLjE2OEwxNjguNzkxIDE1Mi45NDlMMTE4LjY5IDIwMi43MzRMMTA1LjA0NSAyMTZIMTUwLjE4TDIwNy42NjQgMTU4LjIyNkMyMTAuNTY1IDE1NS4zMTQgMjEwLjU1IDE1MC42MDIgMjA3LjYzNCAxNDcuNzA1TDE2Mi44MTEgMTAzLjE2OEgxMTkuMzNaIiBmaWxsPSJibGFjayIvPgo8L2c+CjxkZWZzPgo8ZmlsdGVyIGlkPSJmaWx0ZXIwX2ZfMjAzNV8xMTA2IiB4PSItOTAuMjQxMSIgeT0iLTY5LjczNjkiIHdpZHRoPSI1NjkuNTU4IiBoZWlnaHQ9IjQ1MS40MzEiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyMV9mXzIwMzVfMTEwNiIgeD0iLTE2MC41MTEiIHk9Ii0xNjUuOTg3IiB3aWR0aD0iMzUxLjU5NiIgaGVpZ2h0PSIzNzEuNTA3IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxmaWx0ZXIgaWQ9ImZpbHRlcjJfZl8yMDM1XzExMDYiIHg9Ii0yNDEuMDc4IiB5PSI2Ny42NDIiIHdpZHRoPSI0NDQuODUxIiBoZWlnaHQ9IjQyNC40NTIiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyM19mXzIwMzVfMTEwNiIgeD0iLTIwLjM5NjgiIHk9Ii0yNDIuNzU4IiB3aWR0aD0iNDMwLjE5MSIgaGVpZ2h0PSIzODUuMTA1IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxjbGlwUGF0aCBpZD0iY2xpcDBfMjAzNV8xMTA2Ij4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==",name:"Bitget Wallet"},C6=[_6],S6=s=>C6.find(e=>e.name.toLocaleLowerCase().includes(s.name.toLocaleLowerCase()))||s,$6=(s,e,t)=>e[s]||t[s],pm=(s,e)=>$6(s,S6(e),e);class Ci extends lv{constructor(e,t){super(),this.adapter=e,this.connection=t}getAdapter(){return this.adapter}getName(){return pm("name",this.adapter)}getUrl(){return this.adapter.url}async connect(){if(this.isConnected())return this.getAddresses();const e=await new Promise((t,i)=>{this.adapter.on("connect",()=>{this.adapter.off("connect"),this.adapter.off("error"),t(this.getAddresses())}),this.adapter.on("error",r=>{this.adapter.off("connect"),this.adapter.off("error"),i(r)}),this.adapter.connect().catch(i)});return this.emit("connect"),this.adapter.on("disconnect",()=>this.emit("disconnect")),e}getNetworkInfo(){return{}}isConnected(){return this.adapter.connected}async disconnect(){this.isConnected()&&(await new Promise((e,t)=>{this.adapter.on("disconnect",()=>{this.adapter.off("disconnect"),this.adapter.off("error"),e(void 0)}),this.adapter.on("error",i=>{this.adapter.off("disconnect"),this.adapter.off("error"),t(i)}),this.adapter.disconnect().catch(t)}),this.adapter.removeAllListeners(),this.emit("disconnect"))}getChainId(){return id}getAddress(){var e;return(e=this.adapter.publicKey)==null?void 0:e.toString()}getAddresses(){const e=this.getAddress();return e?[e]:[]}setMainAddress(){throw new Error("Not supported")}getBalance(){throw new Error("Not supported")}async signTransaction(e){if(!this.adapter.signTransaction||!this.adapter.signAllTransactions)throw new Error("Not supported");return Array.isArray(e)?this.adapter.signAllTransactions(e):this.adapter.signTransaction(e)}async sendTransaction(e){var n;const{transaction:t}=e,i=Array.isArray(t)?t:[t];if(i.length===0)throw new Error("Empty transactions array");const r=[];for(const o of i){const a=await this.adapter.sendTransaction(o,this.connection,{...e.options});r.push(a)}return await this.connection.confirmTransaction(r[0],(n=e.options)==null?void 0:n.commitment),{id:r[0],data:r.length===1?r[0]:r}}async signAndSendTransaction(e){return this.sendTransaction(e)}signMessage(e){if(!this.adapter.signMessage)throw new Error("Not supported");return this.adapter.signMessage(e)}getIcon(){return pm("icon",this.adapter)}getWalletState(){const e=this.adapter.readyState;if(!(e in rd))throw new Error(`Unknown wallet state ${e}`);return rd[e]}getFeatures(){const e=[Pa.SendTransaction,Pa.SignAndSendTransaction];return this.adapter.signTransaction&&this.adapter.signAllTransactions&&e.push(Pa.SignTransaction),this.adapter.signMessage&&e.push(Pa.SignMessage),e}supportsChain(e){return e===id}}function P6(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<s.length;c++){const h=s.charAt(c),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=c}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,u=0,d=0;const p=c.length;for(;d!==p&&c[d]===0;)d++,h++;const g=(p-d)*n+1>>>0,f=new Uint8Array(g);for(;d!==p;){let m=c[d],b=0;for(let I=g-1;(m!==0||b<u)&&I!==-1;I--,b++)m+=256*f[I]>>>0,f[I]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");u=b,d++}let y=g-u;for(;y!==g&&f[y]===0;)y++;let w=i.repeat(h);for(;y<g;++y)w+=s.charAt(f[y]);return w}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;c[h]===i;)u++,h++;const p=(c.length-h)*r+1>>>0,g=new Uint8Array(p);for(;h<c.length;){const m=c.charCodeAt(h);if(m>255)return;let b=e[m];if(b===255)return;let I=0;for(let N=p-1;(b!==0||I<d)&&N!==-1;N--,I++)b+=t*g[N]>>>0,g[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=I,h++}let f=p-d;for(;f!==p&&g[f]===0;)f++;const y=new Uint8Array(u+(p-f));let w=u;for(;f!==p;)y[w++]=g[f++];return y}function l(c){const h=a(c);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:l}}var T6="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const M6=P6(T6);var V=function(s,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!i:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(s):i?i.value:e.get(s)},ot=function(s,e,t,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(s,t):r?r.value=t:e.set(s,t),t},Ot,ns,fr,mr,ar,ko,Lc,me,Uc,vu,yc,Iu,Wo,Eu,gm,fm,mm,wm;class O6 extends xm{get name(){return V(this,me,"f").name}get url(){return"https://github.com/solana-labs/wallet-standard"}get icon(){return V(this,me,"f").icon}get readyState(){return V(this,Uc,"f")}get publicKey(){return V(this,fr,"f")}get connecting(){return V(this,mr,"f")}get supportedTransactionVersions(){return V(this,Lc,"f")}get wallet(){return V(this,me,"f")}get standard(){return!0}constructor({wallet:e}){super(),Ot.add(this),ns.set(this,void 0),fr.set(this,void 0),mr.set(this,void 0),ar.set(this,void 0),ko.set(this,void 0),Lc.set(this,void 0),me.set(this,void 0),Uc.set(this,typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.Installed),Eu.set(this,t=>{if("accounts"in t){const i=V(this,me,"f").accounts[0];V(this,ns,"f")&&!V(this,ar,"f")&&i!==V(this,ns,"f")&&(i?V(this,Ot,"m",yc).call(this,i):(this.emit("error",new Om),V(this,Ot,"m",Iu).call(this)))}"features"in t&&V(this,Ot,"m",Wo).call(this)}),ot(this,me,e,"f"),ot(this,ns,null,"f"),ot(this,fr,null,"f"),ot(this,mr,!1,"f"),ot(this,ar,!1,"f"),ot(this,ko,V(this,me,"f").features[km].on("change",V(this,Eu,"f")),"f"),V(this,Ot,"m",Wo).call(this)}destroy(){ot(this,ns,null,"f"),ot(this,fr,null,"f"),ot(this,mr,!1,"f"),ot(this,ar,!1,"f");const e=V(this,ko,"f");e&&(ot(this,ko,null,"f"),e())}async autoConnect(){return V(this,Ot,"m",vu).call(this,{silent:!0})}async connect(){return V(this,Ot,"m",vu).call(this)}async disconnect(){if(hd in V(this,me,"f").features)try{ot(this,ar,!0,"f"),await V(this,me,"f").features[hd].disconnect()}catch(e){this.emit("error",new la(e==null?void 0:e.message,e))}finally{ot(this,ar,!1,"f")}V(this,Ot,"m",Iu).call(this)}async sendTransaction(e,t,i={}){try{const r=V(this,ns,"f");if(!r)throw new Fe;let n;if(Oi in V(this,me,"f").features)if(r.features.includes(Oi))n=Oi;else if(Mt in V(this,me,"f").features&&r.features.includes(Mt))n=Mt;else throw new Ps;else if(Mt in V(this,me,"f").features){if(!r.features.includes(Mt))throw new Ps;n=Mt}else throw new Cn;const o=Wv(t.rpcEndpoint);if(!r.chains.includes(o))throw new ur;try{const{signers:a,...l}=i;let c;if(pi(e)?(a!=null&&a.length&&e.sign(a),c=e.serialize()):(e=await this.prepareTransaction(e,t,l),a!=null&&a.length&&e.partialSign(...a),c=new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))),n===Oi){const[h]=await V(this,me,"f").features[Oi].signAndSendTransaction({account:r,chain:o,transaction:c,options:{preflightCommitment:pl(l.preflightCommitment||t.commitment),skipPreflight:l.skipPreflight,maxRetries:l.maxRetries,minContextSlot:l.minContextSlot}});return M6.encode(h.signature)}else{const[h]=await V(this,me,"f").features[Mt].signTransaction({account:r,chain:o,transaction:c,options:{preflightCommitment:pl(l.preflightCommitment||t.commitment),minContextSlot:l.minContextSlot}});return await t.sendRawTransaction(h.signedTransaction,{...l,preflightCommitment:pl(l.preflightCommitment||t.commitment)})}}catch(a){throw a instanceof jt?a:new ur(a==null?void 0:a.message,a)}}catch(r){throw this.emit("error",r),r}}}ns=new WeakMap,fr=new WeakMap,mr=new WeakMap,ar=new WeakMap,ko=new WeakMap,Lc=new WeakMap,me=new WeakMap,Uc=new WeakMap,Eu=new WeakMap,Ot=new WeakSet,vu=async function(e){try{if(this.connected||this.connecting)return;if(V(this,Uc,"f")!==ne.Installed)throw new Ki;if(ot(this,mr,!0,"f"),!V(this,me,"f").accounts.length)try{await V(this,me,"f").features[Dm].connect(e)}catch(i){throw new Fc(i==null?void 0:i.message,i)}const t=V(this,me,"f").accounts[0];if(!t)throw new Ps;V(this,Ot,"m",yc).call(this,t)}catch(t){throw this.emit("error",t),t}finally{ot(this,mr,!1,"f")}},yc=function(e){let t;try{t=new ei(e.address)}catch(i){throw new Pr(i==null?void 0:i.message,i)}ot(this,ns,e,"f"),ot(this,fr,t,"f"),V(this,Ot,"m",Wo).call(this),this.emit("connect",t)},Iu=function(){ot(this,ns,null,"f"),ot(this,fr,null,"f"),V(this,Ot,"m",Wo).call(this),this.emit("disconnect")},Wo=function(){var t,i;const e=Oi in V(this,me,"f").features?V(this,me,"f").features[Oi].supportedTransactionVersions:V(this,me,"f").features[Mt].supportedTransactionVersions;ot(this,Lc,gv(e,["legacy"])?null:new Set(e),"f"),Mt in V(this,me,"f").features&&((t=V(this,ns,"f"))!=null&&t.features.includes(Mt))?(this.signTransaction=V(this,Ot,"m",gm),this.signAllTransactions=V(this,Ot,"m",fm)):(delete this.signTransaction,delete this.signAllTransactions),io in V(this,me,"f").features&&((i=V(this,ns,"f"))!=null&&i.features.includes(io))?this.signMessage=V(this,Ot,"m",mm):delete this.signMessage,ul in V(this,me,"f").features?this.signIn=V(this,Ot,"m",wm):delete this.signIn},gm=async function(e){try{const t=V(this,ns,"f");if(!t)throw new Fe;if(!(Mt in V(this,me,"f").features))throw new Cn;if(!t.features.includes(Mt))throw new Ps;try{const r=(await V(this,me,"f").features[Mt].signTransaction({account:t,transaction:pi(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return pi(e)?dh.deserialize(r):ph.from(r)}catch(i){throw i instanceof jt?i:new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},fm=async function(e){try{const t=V(this,ns,"f");if(!t)throw new Fe;if(!(Mt in V(this,me,"f").features))throw new Cn;if(!t.features.includes(Mt))throw new Ps;try{const i=await V(this,me,"f").features[Mt].signTransaction(...e.map(r=>({account:t,transaction:pi(r)?r.serialize():new Uint8Array(r.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((r,n)=>{const o=i[n].signedTransaction;return pi(r)?dh.deserialize(o):ph.from(o)})}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},mm=async function(e){try{const t=V(this,ns,"f");if(!t)throw new Fe;if(!(io in V(this,me,"f").features))throw new Cn;if(!t.features.includes(io))throw new Ps;try{return(await V(this,me,"f").features[io].signMessage({account:t,message:e}))[0].signature}catch(i){throw new ha(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},wm=async function(e={}){try{if(!(ul in V(this,me,"f").features))throw new Cn;let t;try{[t]=await V(this,me,"f").features[ul].signIn(e)}catch(i){throw new ld(i==null?void 0:i.message,i)}if(!t)throw new ld;return V(this,Ot,"m",yc).call(this,t.account),t}catch(t){throw this.emit("error",t),t}};function x6(s){return fv().get().filter(Cv).map(e=>new Ci(new O6({wallet:e}),s))}function D6(s){return s.includes("rpcpool.com")?"triton":s.includes("helius-rpc.com")?"helius":s.includes("rpc.ankr.com")?"ankr":"unknown"}async function k6(s,e,t,i){const r=i.transaction.transaction,n=o=>o.programId.toString()!=="ComputeBudget111111111111111111111111111111";if(fh(r)){const o=(await Promise.all(r.message.addressTableLookups.map(l=>s.getAddressLookupTable(l.accountKey)))).map(l=>l.value).filter(l=>l!==null),a=hv.decompile(r.message,{addressLookupTableAccounts:o});a.recentBlockhash=e,r.message.recentBlockhash=e,a.instructions=a.instructions.filter(n),a.instructions.push(...await ym(s,r)),r.message=a.compileToV0Message(o),r.sign(i.transaction.signers??[])}else r.recentBlockhash=e,r.lastValidBlockHeight=t,r.instructions=r.instructions.filter(n),r.add(...await ym(s,r)),i.transaction.signers&&r.partialSign(...i.transaction.signers);return r}async function ym(s,e,t){var w,m;let i=2e5,r=0;e:for(;;){if(fh(e)&&!e.message.recentBlockhash){const{blockhash:I}=await s.getLatestBlockhash(t);e.message.recentBlockhash=I}const b=await(fh(e)?s.simulateTransaction(e,{commitment:t,replaceRecentBlockhash:!0}):s.simulateTransaction(e));if(b.value.err){if(j6(b.value)){if(r<5){r++,await gh(1e3);continue e}}else if(r<3){r++,await gh(1e3);continue e}throw new Error(`Simulation failed: ${JSON.stringify(b.value.err)}
916
+ `,ec={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};function $a(s){return{formatters:void 0,fees:void 0,serializers:void 0,...s}}const yu=$a({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"}),bu=$a({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"}),l6=$a({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"});$a({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});$a({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 h6={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"]},iv={getMethodsByChainNamespace(s){return h6[s]||[]},createDefaultNamespace(s){return{methods:this.getMethodsByChainNamespace(s),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(s,e){if(!e)return{...s};const t={...s},i=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>i.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>i.add(r)),e.events&&Object.keys(e.events).forEach(r=>i.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[n]=r.split(":");n&&i.add(n)}),i.forEach(r=>{t[r]||(t[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,n])=>{t[r]&&(t[r].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([r,n])=>{t[r]&&(t[r].chains=n)}),e.events&&Object.entries(e.events).forEach(([r,n])=>{t[r]&&(t[r].events=n)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,l]=n.split(":");!a||!l||!t[a]||(t[a].rpcMap||(t[a].rpcMap={}),r.has(a)||(t[a].rpcMap={},r.add(a)),t[a].rpcMap[l]=o)})}return t},createNamespaces(s,e){const t=s.reduce((i,r)=>{const{id:n,chainNamespace:o,rpcUrls:a}=r,l=a.default.http[0];i[o]||(i[o]=this.createDefaultNamespace(o));const c=`${o}:${n}`,h=i[o];switch(h.chains.push(c),c){case yu.caipNetworkId:h.chains.push(yu.deprecatedCaipNetworkId);break;case bu.caipNetworkId:h.chains.push(bu.deprecatedCaipNetworkId);break}return h!=null&&h.rpcMap&&l&&(h.rpcMap[n]=l),i},{});return this.applyNamespaceOverrides(t,e)},resolveReownName:async s=>{var i;const e=await Sy.resolveName(s);return((i=(Object.values(e==null?void 0:e.addresses)||[])[0])==null?void 0:i.address)||!1},getChainsFromNamespaces(s={}){return Object.values(s).flatMap(e=>{const t=e.chains||[],i=e.accounts.map(r=>{const[n,o]=r.split(":");return`${n}:${o}`});return Array.from(new Set([...t,...i]))})},isSessionEventData(s){return typeof s=="object"&&s!==null&&"id"in s&&"topic"in s&&"params"in s&&typeof s.params=="object"&&s.params!==null&&"chainId"in s.params&&"event"in s.params&&typeof s.params.event=="object"&&s.params.event!==null}};class rv{constructor({provider:e,caipNetworks:t,namespace:i}){this.id=Q.CONNECTOR_ID.WALLET_CONNECT,this.name=Dc.ConnectorNamesMap[Q.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Dc.ConnectorImageIds[Q.CONNECTOR_ID.WALLET_CONNECT],this.caipNetworks=t,this.provider=e,this.chain=i}get chains(){return this.caipNetworks}async connectWalletConnect(){if(!await this.authenticate()){const t=D.state.universalProviderConfigOverride,i=iv.createNamespaces(this.caipNetworks,t);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(t=>t.caipNetworkId);return Lo.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:u6})}}const u6=["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 d6{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,e&&this.construct(e)}construct(e){this.caipNetworks=e.networks,this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.caipNetworks||[]}setAuthProvider(e){this.addConnector({id:Q.CONNECTOR_ID.AUTH,type:"AUTH",name:Q.CONNECTOR_NAMES.AUTH,provider:e,imageId:Dc.ConnectorImageIds[Q.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(i=>t.has(i.id)?!1:(t.add(i.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,t){Z.setStatus(e,t)}on(e,t){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(t)}off(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,t){const i=this.eventListeners.get(e);i&&i.forEach(r=>r(t))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:t,providerType:i}=e;if(!e.provider)return;const r="provider"in e.provider?e.provider.provider:e.provider;if(i==="WALLET_CONNECT"){r.setDefaultChain(t.caipNetworkId);return}if(r&&i==="AUTH"){const n=r;await n.switchNetwork(t.caipNetworkId);const o=await n.getUser({chainId:t.caipNetworkId,preferredAccountType:D.state.defaultAccountTypes[t.chainNamespace]});this.emit("switchNetwork",o)}}getWalletConnectConnector(){const e=this.connectors.find(t=>t instanceof rv);if(!e)throw new Error("WalletConnectConnector not found");return e}}class p6 extends d6{setUniversalProvider(e){this.addConnector(new rv({provider:e,caipNetworks:this.caipNetworks||[],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}){var r,n,o,a;const t=this.provider,i=((a=(o=(n=(r=t==null?void 0:t.session)==null?void 0:r.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(l=>{const[,,c]=l.split(":");return c}).filter((l,c,h)=>h.indexOf(l)===c))||[];return Promise.resolve({accounts:i.map(l=>se.createAccount(e,l,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var n,o,a,l,c;if(!(e.caipNetwork&&os.BALANCE_SUPPORTED_CHAINS.includes((n=e.caipNetwork)==null?void 0:n.chainNamespace))||(o=e.caipNetwork)!=null&&o.testnet)return{balance:"0.00",symbol:((a=e.caipNetwork)==null?void 0:a.nativeCurrency.symbol)||""};if(Z.state.balanceLoading&&e.chainId===((l=v.state.activeCaipNetwork)==null?void 0:l.id))return{balance:Z.state.balance||"0.00",symbol:Z.state.balanceSymbol||""};const r=(await Z.fetchTokenBalance()).find(h=>{var u,d;return h.chainId===`${(u=e.caipNetwork)==null?void 0:u.chainNamespace}:${e.chainId}`&&h.symbol===((d=e.caipNetwork)==null?void 0:d.nativeCurrency.symbol)});return{balance:(r==null?void 0:r.quantity.numeric)||"0.00",symbol:(r==null?void 0:r.symbol)||((c=e.caipNetwork)==null?void 0:c.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,l;const{provider:t,message:i,address:r}=e;if(!t)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return((o=v.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===Q.CHAIN.SOLANA?n=(await t.request({method:"solana_signMessage",params:{message:zy.encode(new TextEncoder().encode(i)),pubkey:r}},(a=v.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:n=await t.request({method:"personal_sign",params:[i,r]},(l=v.state.activeCaipNetwork)==null?void 0:l.caipNetworkId),{signature:n}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async getProfile(){return Promise.resolve({profileImage:"",profileName:""})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}async getEnsAddress(){return Promise.resolve({address:!1})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){var r,n,o,a,l,c;const{caipNetwork:t}=e,i=this.getWalletConnectConnector();if(t.chainNamespace===Q.CHAIN.EVM)try{await((r=i.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:cd(t.id)}]}))}catch(h){if(h.code===ec.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||h.code===ec.ERROR_INVALID_CHAIN_ID||h.code===ec.ERROR_CODE_DEFAULT||((o=(n=h==null?void 0:h.data)==null?void 0:n.originalError)==null?void 0:o.code)===ec.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((c=i.provider)==null?void 0:c.request({method:"wallet_addEthereumChain",params:[{chainId:cd(t.id),rpcUrls:[(a=t==null?void 0:t.rpcUrls.chainDefault)==null?void 0:a.http],chainName:t.name,nativeCurrency:t.nativeCurrency,blockExplorerUrls:[(l=t.blockExplorers)==null?void 0:l.default.url]}]}))}catch{throw new Error("Chain is not supported")}}i.provider.setDefaultChain(t.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(i=>i.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}class g6{constructor(e){var t;this.hasSwitchedToPreferredAccountTypeOnConnect=!1,this.chainNamespaces=[],this.reportedAlertErrors={},this.getCaipNetwork=i=>{var r,n;if(i){const o=(r=v.getNetworkData(i))==null?void 0:r.caipNetwork;return o||((n=v.getRequestedCaipNetworks(i).filter(a=>a.chainNamespace===i))==null?void 0:n[0])}return v.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const i=this.getCaipNetwork();if(i)return i.id},this.getCaipNetworks=i=>v.getRequestedCaipNetworks(i),this.getActiveChainNamespace=()=>v.state.activeChain,this.setRequestedCaipNetworks=(i,r)=>{v.setRequestedCaipNetworks(i,r)},this.getApprovedCaipNetworkIds=()=>v.getAllApprovedCaipNetworkIds(),this.getCaipAddress=i=>v.state.activeChain===i||!i?v.state.activeCaipAddress:v.getAccountProp("caipAddress",i),this.setClientId=i=>{X.setClientId(i)},this.getProvider=i=>Je.getProvider(i),this.getProviderType=i=>Je.getProviderId(i),this.getPreferredAccountType=()=>Z.state.preferredAccountType,this.setCaipAddress=(i,r)=>{Z.setCaipAddress(i,r)},this.setBalance=(i,r,n)=>{Z.setBalance(i,r,n)},this.setProfileName=(i,r)=>{Z.setProfileName(i,r)},this.setProfileImage=(i,r)=>{Z.setProfileImage(i,r)},this.setUser=(i,r)=>{Z.setUser(i,r),D.state.enableEmbedded&&ct.close()},this.resetAccount=i=>{Z.resetAccount(i)},this.setCaipNetwork=i=>{v.setActiveCaipNetwork(i)},this.setCaipNetworkOfNamespace=(i,r)=>{v.setChainNetworkData(r,{caipNetwork:i})},this.setAllAccounts=(i,r)=>{Z.setAllAccounts(i,r),D.setHasMultipleAddresses((i==null?void 0:i.length)>1)},this.setStatus=(i,r)=>{Z.setStatus(i,r),te.isConnected()?G.setConnectionStatus("connected"):G.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=i=>v.getAccountProp("address",i),this.setConnectors=i=>{const r=[...te.getConnectors(),...i];te.setConnectors(r)},this.fetchIdentity=i=>X.fetchIdentity(i),this.getReownName=i=>Sy.getNamesForAddress(i),this.getConnectors=()=>te.getConnectors(),this.getConnectorImage=i=>Ny.getConnectorImage(i),this.setConnectedWalletInfo=(i,r)=>{const n=Je.getProviderId(r),o=i?{...i,type:n}:void 0;Z.setConnectedWalletInfo(o,r)},this.getIsConnectedState=()=>!!v.state.activeCaipAddress,this.addAddressLabel=(i,r,n)=>{Z.addAddressLabel(i,r,n)},this.removeAddressLabel=(i,r)=>{Z.removeAddressLabel(i,r)},this.getAddress=i=>v.state.activeChain===i||!i?Z.state.address:v.getAccountProp("address",i),this.setApprovedCaipNetworksData=i=>v.setApprovedCaipNetworksData(i),this.resetNetwork=i=>{v.resetNetwork(i)},this.addConnector=i=>{te.addConnector(i)},this.resetWcConnection=()=>{Ue.resetWcConnection()},this.setAddressExplorerUrl=(i,r)=>{Z.setAddressExplorerUrl(i,r)},this.setSmartAccountDeployed=(i,r)=>{Z.setSmartAccountDeployed(i,r)},this.setSmartAccountEnabledNetworks=(i,r)=>{v.setSmartAccountEnabledNetworks(i,r)},this.setPreferredAccountType=(i,r)=>{Z.setPreferredAccountType(i,r)},this.setEIP6963Enabled=i=>{D.setEIP6963Enabled(i)},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=[...new Set((t=this.caipNetworks)==null?void 0:t.map(i=>i.chainNamespace))],this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.initialize(e),this.sendInitializeEvent(e)}async initialize(e){this.initControllers(e),await this.initChainAdapters(),await this.injectModalUi(),await this.syncExistingConnection(),fi.set({initialized:!0})}sendInitializeEvent(e){var i;const{...t}=e;delete t.adapters,ze.sendEvent({type:"track",event:"INITIALIZE",properties:{...t,networks:e.networks.map(r=>r.id),siweConfig:{options:((i=e.siweConfig)==null?void 0:i.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&Vt.setThemeMode(e.themeMode),e.themeVariables&&Vt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");v.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&v.setActiveCaipNetwork(t)}initializeConnectionController(e){Ue.setWcBasic(e.basic??!1)}initializeConnectorController(){te.initialize(this.chainNamespaces)}initializeOptionsController(e){var r;D.setDebug(e.debug!==!1),D.setEnableWalletConnect(e.enableWalletConnect!==!1),D.setEnableWalletGuide(e.enableWalletGuide!==!1),D.setEnableWallets(e.enableWallets!==!1),D.setEIP6963Enabled(e.enableEIP6963!==!1),D.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),D.setEnableAuthLogger(e.enableAuthLogger!==!1),D.setCustomRpcUrls(e.customRpcUrls),D.setSdkVersion(e.sdkVersion),D.setProjectId(e.projectId),D.setEnableEmbedded(e.enableEmbedded),D.setAllWallets(e.allWallets),D.setIncludeWalletIds(e.includeWalletIds),D.setExcludeWalletIds(e.excludeWalletIds),D.setFeaturedWalletIds(e.featuredWalletIds),D.setTokens(e.tokens),D.setTermsConditionsUrl(e.termsConditionsUrl),D.setPrivacyPolicyUrl(e.privacyPolicyUrl),D.setCustomWallets(e.customWallets),D.setFeatures(e.features),D.setAllowUnsupportedChain(e.allowUnsupportedChain),D.setDefaultAccountTypes(e.defaultAccountTypes),D.setUniversalProviderConfigOverride(e.universalProviderConfigOverride);const t=this.getDefaultMetaData();if(!e.metadata&&t&&(e.metadata=t),D.setMetadata(e.metadata),D.setDisableAppend(e.disableAppend),D.setEnableEmbedded(e.enableEmbedded),D.setSIWX(e.siwx),!e.projectId){ac.open(Xa.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((r=e.adapters)==null?void 0:r.find(n=>n.namespace===Q.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");D.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,t,i,r;return typeof window<"u"&&typeof document<"u"?{name:((t=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:t.textContent)||"",description:((i=document.querySelector('meta[property="og:description"]'))==null?void 0:i.content)||"",url:window.location.origin,icons:[((r=document.querySelector('link[rel~="icon"]'))==null?void 0:r.href)||""]}:null}setUnsupportedNetwork(e){const t=this.getActiveChainNamespace();if(t){const i=Nn.getUnsupportedNetwork(`${t}:${e}`);v.setActiveCaipNetwork(i)}}getDefaultNetwork(){return Nn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return Nn.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return Nn.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const t=e.networks.find(r=>{var n;return r.id===((n=e.defaultNetwork)==null?void 0:n.id)});return t?Nn.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var n;const e=v.state.activeChain,t=this.getAdapter(e),i=(n=this.getCaipNetwork(e))==null?void 0:n.id;if(!t)throw new Error("Adapter not found");const r=await t.connectWalletConnect(i);this.close(),this.setClientId((r==null?void 0:r.clientId)||null),G.setConnectedNamespaces([...v.state.chains.keys()]),this.chainNamespaces.forEach(o=>{te.setConnectorId(_i.CONNECTOR_TYPE_WALLET_CONNECT,o)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:t,type:i,provider:r,chain:n,caipNetwork:o})=>{var p,g,f,y,w,m,b;const a=v.state.activeChain,l=n||a,c=this.getAdapter(l);if(n&&n!==a&&!o){const I=(p=this.caipNetworks)==null?void 0:p.find(N=>N.chainNamespace===n);I&&this.setCaipNetwork(I)}if(!c)throw new Error("Adapter not found");const h=this.getCaipNetwork(l),u=await c.connect({id:e,info:t,type:i,provider:r,chainId:(o==null?void 0:o.id)||(h==null?void 0:h.id),rpcUrl:((y=(f=(g=o==null?void 0:o.rpcUrls)==null?void 0:g.default)==null?void 0:f.http)==null?void 0:y[0])||((b=(m=(w=h==null?void 0:h.rpcUrls)==null?void 0:w.default)==null?void 0:m.http)==null?void 0:b[0])});if(!u)return;G.addConnectedNamespace(l),this.syncProvider({...u,chainNamespace:l}),await this.syncAccount({...u,chainNamespace:l});const{accounts:d}=await c.getAccounts({namespace:l,id:e});this.setAllAccounts(d,l)},reconnectExternal:async({id:e,info:t,type:i,provider:r})=>{var a;const n=v.state.activeChain,o=this.getAdapter(n);o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:t,type:i,provider:r,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),G.addConnectedNamespace(n))},disconnect:async e=>{const t=e||v.state.activeChain,i=this.getAdapter(t),r=Je.getProvider(t),n=Je.getProviderId(t);await(i==null?void 0:i.disconnect({provider:r,providerType:n})),G.removeConnectedNamespace(t),Je.resetChain(t),this.setUser(void 0,t),this.setStatus("disconnected",t),this.hasSwitchedToPreferredAccountTypeOnConnect=!1},checkInstalled:e=>e?e.some(t=>{var i;return!!((i=window.ethereum)!=null&&i[String(t)])}):!!window.ethereum,signMessage:async e=>{const t=this.getAdapter(v.state.activeChain),i=await(t==null?void 0:t.signMessage({message:e,address:Z.state.address,provider:Je.getProvider(v.state.activeChain)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{if(e.chainNamespace===Q.CHAIN.EVM){const t=this.getAdapter(v.state.activeChain),i=Je.getProvider(v.state.activeChain),r=await(t==null?void 0:t.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}));return(r==null?void 0:r.hash)||""}return""},estimateGas:async e=>{if(e.chainNamespace===Q.CHAIN.EVM){const t=this.getAdapter(v.state.activeChain),i=Je.getProvider(v.state.activeChain),r=this.getCaipNetwork();if(!r)throw new Error("CaipNetwork is undefined");const n=await(t==null?void 0:t.estimateGas({...e,provider:i,caipNetwork:r}));return(n==null?void 0:n.gas)||0n}return 0n},getEnsAvatar:async()=>{var i;const e=this.getAdapter(v.state.activeChain),t=await(e==null?void 0:e.getProfile({address:Z.state.address,chainId:Number((i=this.getCaipNetwork())==null?void 0:i.id)}));return(t==null?void 0:t.profileImage)||!1},getEnsAddress:async e=>{const t=this.getAdapter(v.state.activeChain),i=this.getCaipNetwork();if(!i)return!1;const r=await(t==null?void 0:t.getEnsAddress({name:e,caipNetwork:i}));return(r==null?void 0:r.address)||!1},writeContract:async e=>{const t=this.getAdapter(v.state.activeChain),i=this.getCaipNetwork(),r=this.getCaipAddress(),n=Je.getProvider(v.state.activeChain);if(!i||!r)throw new Error("CaipNetwork or CaipAddress is undefined");const o=await(t==null?void 0:t.writeContract({...e,caipNetwork:i,provider:n,caipAddress:r}));return o==null?void 0:o.hash},parseUnits:(e,t)=>{const i=this.getAdapter(v.state.activeChain);return(i==null?void 0:i.parseUnits({value:e,decimals:t}))??0n},formatUnits:(e,t)=>{const i=this.getAdapter(v.state.activeChain);return(i==null?void 0:i.formatUnits({value:e,decimals:t}))??"0"},getCapabilities:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.getCapabilities(e))},grantPermissions:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.grantPermissions(e))},revokePermissions:async e=>{const t=this.getAdapter(v.state.activeChain);return t!=null&&t.revokePermissions?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.walletGetAssets(e))??{}}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Ue.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){var t,i,r,n,o;if(Je.getProviderId(v.state.activeChain)===_i.CONNECTOR_TYPE_WALLET_CONNECT){const a=(i=(t=this.universalProvider)==null?void 0:t.session)==null?void 0:i.namespaces;return{supportsAllNetworks:((o=(n=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:n.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const t=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=Je.getProvider(t),n=Je.getProviderId(t);if(e.chainNamespace===v.state.activeChain){const o=this.getAdapter(t);await(o==null?void 0:o.switchNetwork({caipNetwork:e,provider:r,providerType:n}))}else if(this.setCaipNetwork(e),n===_i.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(t);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(t=>{const i=t.chains||[],r=t.accounts.map(n=>{const{chainId:o,chainNamespace:a}=Ii.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...i,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((t,i)=>{var n;const r=e==null?void 0:e.find(o=>o.namespace===i);return r?(t[i]=r,t[i].namespace=i,t[i].construct({namespace:i,projectId:(n=this.options)==null?void 0:n.projectId,networks:this.caipNetworks})):t[i]=new p6({namespace:i,networks:this.caipNetworks}),t},{})}async initChainAdapter(e){var t;this.onConnectors(e),this.listenAdapter(e),(t=this.chainAdapters)==null||t[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){const t=this.getAdapter(e);t==null||t.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const t=this.getAdapter(e);if(!t)return;const i=G.getConnectionStatus();i==="connected"?this.setStatus("connecting",e):i==="disconnected"?(G.clearAddressCache(),this.setStatus(i,e)):this.setStatus(i,e),t.on("switchNetwork",({address:r,chainId:n})=>{var c;const o=(c=this.caipNetworks)==null?void 0:c.find(h=>h.id===n||h.caipNetworkId===n),a=v.state.activeChain===e,l=v.getAccountProp("address",e);if(o){const h=a&&r?r:l;h&&this.syncAccount({address:h,chainId:n,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),t.on("disconnect",this.disconnect.bind(this,e)),t.on("pendingTransactions",()=>{const r=Z.state.address,n=v.state.activeCaipNetwork;!r||!(n!=null&&n.id)||this.updateNativeBalance(r,n.id,n.chainNamespace)}),t.on("accountChanged",({address:r,chainId:n})=>{var a,l;const o=v.state.activeChain===e;o&&n?this.syncAccount({address:r,chainId:n,chainNamespace:e}):o&&((a=v.state.activeCaipNetwork)!=null&&a.id)?this.syncAccount({address:r,chainId:(l=v.state.activeCaipNetwork)==null?void 0:l.id,chainNamespace:e}):this.syncAccountInfo(r,n,e)})}async createUniversalProviderForAdapter(e){var t,i,r;await this.getUniversalProvider(),this.universalProvider&&((r=(i=(t=this.chainAdapters)==null?void 0:t[e])==null?void 0:i.setUniversalProvider)==null||r.call(i,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{const t=te.getConnectorId(e);switch(this.setStatus("connecting",e),t){case Q.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case Q.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(t){console.warn("AppKit couldn't sync existing connection",t),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){var o,a,l;const t=this.getAdapter(e),i=te.getConnectorId(e),r=this.getCaipNetwork(e),n=te.getConnectors(e).find(c=>c.id===i);try{if(!t||!n)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(r!=null&&r.id))throw new Error("CaipNetwork not found");const c=await(t==null?void 0:t.syncConnection({namespace:e,id:n.id,chainId:r.id,rpcUrl:(l=(a=(o=r==null?void 0:r.rpcUrls)==null?void 0:o.default)==null?void 0:a.http)==null?void 0:l[0]}));if(c){const h=await(t==null?void 0:t.getAccounts({namespace:e,id:n.id}));h&&h.accounts.length>0?this.setAllAccounts(h.accounts,e):this.setAllAccounts([se.createAccount(e,c.address,"eoa")],e),this.syncProvider({...c,chainNamespace:e}),await this.syncAccount({...c,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async t=>{var a,l,c,h,u;const i=this.getAdapter(t),r=((h=(c=(l=(a=this.universalProvider)==null?void 0:a.session)==null?void 0:l.namespaces)==null?void 0:c[t])==null?void 0:h.accounts)||[],n=(u=v.state.activeCaipNetwork)==null?void 0:u.id,o=r.find(d=>{const{chainId:p}=Ii.parseCaipAddress(d);return p===(n==null?void 0:n.toString())})||r[0];if(o){const d=Ii.validateCaipAddress(o),{chainId:p,address:g}=Ii.parseCaipAddress(d);if(Je.setProviderId(t,_i.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&v.state.activeCaipNetwork&&(i==null?void 0:i.namespace)!==Q.CHAIN.EVM){const f=i==null?void 0:i.getWalletConnectProvider({caipNetworks:this.caipNetworks,provider:this.universalProvider,activeCaipNetwork:v.state.activeCaipNetwork});Je.setProvider(t,f)}else Je.setProvider(t,this.universalProvider);te.setConnectorId(Q.CONNECTOR_ID.WALLET_CONNECT,t),G.addConnectedNamespace(t),this.syncWalletConnectAccounts(t),await this.syncAccount({address:g,chainId:p,chainNamespace:t})}else this.setStatus("disconnected",t);await v.setApprovedCaipNetworksData(t)});await Promise.all(e)}syncWalletConnectAccounts(e){var i,r,n,o,a;const t=(a=(o=(n=(r=(i=this.universalProvider)==null?void 0:i.session)==null?void 0:r.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(l=>{const{address:c}=Ii.parseCaipAddress(l);return c}).filter((l,c,h)=>h.indexOf(l)===c);t&&this.setAllAccounts(t.map(l=>se.createAccount(e,l,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:i,chainNamespace:r}){Je.setProviderId(r,e),Je.setProvider(r,t),te.setConnectorId(i,r)}async syncAccount(e){var u,d,p,g,f,y;const t=e.chainNamespace===v.state.activeChain,i=v.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:n,chainNamespace:o}=e,{chainId:a}=G.getActiveNetworkProps(),l=n||a,c=((u=v.state.activeCaipNetwork)==null?void 0:u.name)===Q.UNSUPPORTED_NETWORK_NAME,h=v.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(c&&!h)&&l){let w=(d=this.caipNetworks)==null?void 0:d.find(I=>I.id.toString()===l.toString()),m=(p=this.caipNetworks)==null?void 0:p.find(I=>I.chainNamespace===o);if(!h&&!w&&!m){const I=this.getApprovedCaipNetworkIds()||[],N=I.find(P=>{var O;return((O=Ii.parseCaipNetworkId(P))==null?void 0:O.chainId)===l.toString()}),$=I.find(P=>{var O;return((O=Ii.parseCaipNetworkId(P))==null?void 0:O.chainNamespace)===o});w=(g=this.caipNetworks)==null?void 0:g.find(P=>P.caipNetworkId===N),m=(f=this.caipNetworks)==null?void 0:f.find(P=>P.caipNetworkId===$||"deprecatedCaipNetworkId"in P&&P.deprecatedCaipNetworkId===$)}const b=w||m;(b==null?void 0:b.chainNamespace)===v.state.activeChain?D.state.enableNetworkSwitch&&!D.state.allowUnsupportedChain&&((y=v.state.activeCaipNetwork)==null?void 0:y.name)===Q.UNSUPPORTED_NETWORK_NAME?v.showUnsupportedChainUI():this.setCaipNetwork(b):t||i&&this.setCaipNetworkOfNamespace(i,o),this.syncConnectedWalletInfo(o),Gb.isLowerCaseMatch(r,Z.state.address)||this.syncAccountInfo(r,b==null?void 0:b.id,o),t?await this.syncBalance({address:r,chainId:b==null?void 0:b.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:i==null?void 0:i.id,chainNamespace:o})}}async syncAccountInfo(e,t,i){const r=this.getCaipAddress(i),n=t||(r==null?void 0:r.split(":")[1]);if(!n)return;const o=`${i}:${n}:${e}`;this.setCaipAddress(o,i),await this.syncIdentity({address:e,chainId:n,chainNamespace:i})}async syncReownName(e,t){try{const i=await this.getReownName(e);if(i[0]){const r=i[0];this.setProfileName(r.name,t)}else this.setProfileName(null,t)}catch{this.setProfileName(null,t)}}syncConnectedWalletInfo(e){var r;const t=te.getConnectorId(e),i=Je.getProviderId(e);if(i===_i.CONNECTOR_TYPE_ANNOUNCED||i===_i.CONNECTOR_TYPE_INJECTED){if(t){const n=this.getConnectors().find(o=>o.id===t);if(n){const{info:o,name:a,imageUrl:l}=n,c=l||this.getConnectorImage(n);this.setConnectedWalletInfo({name:a,icon:c,...o},e)}}}else if(i===_i.CONNECTOR_TYPE_WALLET_CONNECT){const n=Je.getProvider(e);n!=null&&n.session&&this.setConnectedWalletInfo({...n.session.peer.metadata,name:n.session.peer.metadata.name,icon:(r=n.session.peer.metadata.icons)==null?void 0:r[0]},e)}else if(t)if(t===Q.CONNECTOR_ID.COINBASE){const n=this.getConnectors().find(o=>o.id===Q.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(n)},e)}else this.setConnectedWalletInfo({name:t},e)}async syncBalance(e){!Iy.getNetworksByNamespace(this.caipNetworks,e.chainNamespace).find(i=>{var r;return i.id.toString()===((r=e.chainId)==null?void 0:r.toString())})||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async updateNativeBalance(e,t,i){const r=this.getAdapter(i);if(r){const n=await r.getBalance({address:e,chainId:t,caipNetwork:this.getCaipNetwork(i),tokens:this.options.tokens});this.setBalance(n.balance,n.symbol,i)}}async initializeUniversalAdapter(){var i,r,n,o,a,l,c,h,u,d;const e=F8.createLogger((p,...g)=>{p&&this.handleAlertError(p),console.error(...g)}),t={projectId:(i=this.options)==null?void 0:i.projectId,metadata:{name:(r=this.options)!=null&&r.metadata?(n=this.options)==null?void 0:n.metadata.name:"",description:(o=this.options)!=null&&o.metadata?(a=this.options)==null?void 0:a.metadata.description:"",url:(l=this.options)!=null&&l.metadata?(c=this.options)==null?void 0:c.metadata.url:"",icons:(h=this.options)!=null&&h.metadata?(u=this.options)==null?void 0:u.metadata.icons:[""]},logger:e};D.setManualWCControl(!!((d=this.options)!=null&&d.manualWCControl)),this.universalProvider=this.options.universalProvider??await U8.init(t),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{Ue.setUri(e)}),this.universalProvider.on("connect",Ue.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),Ue.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{var r;const t=(r=this.caipNetworks)==null?void 0:r.find(n=>n.id==e),i=this.getCaipNetwork();if(!t){this.setUnsupportedNetwork(e);return}(i==null?void 0:i.id)!==(t==null?void 0:t.id)&&this.setCaipNetwork(t)}),this.universalProvider.on("session_event",e=>{if(iv.isSessionEventData(e)){const{name:t,data:i}=e.params.event;t==="accountsChanged"&&Array.isArray(i)&&se.isCaipAddress(i[0])&&this.syncAccount(Ii.parseCaipAddress(i[0]))}}))}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&se.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){ze.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 t=Object.entries(Xa.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[i,r]=t??[],{message:n,alertErrorKey:o}=r??{};if(i&&n&&!this.reportedAlertErrors[i]){const a=Xa.ALERT_ERRORS[o];a&&(ac.open(a,"error"),this.reportedAlertErrors[i]=!0)}}getAdapter(e){var t;if(e)return(t=this.chainAdapters)==null?void 0:t[e]}createAdapter(e){var r;if(!e)return;const t=e.namespace;if(!t)return;this.createClients();const i=e;i.namespace=t,i.construct({namespace:t,projectId:(r=this.options)==null?void 0:r.projectId,networks:this.caipNetworks}),this.chainNamespaces.includes(t)||this.chainNamespaces.push(t),this.chainAdapters&&(this.chainAdapters[t]=i)}async open(e){await this.injectModalUi(),e!=null&&e.uri&&Ue.setUri(e.uri),await ct.open(e)}async close(){await this.injectModalUi(),ct.close()}setLoading(e,t){ct.setLoading(e,t)}async disconnect(e){await Ue.disconnect(e)}getError(){return""}getChainId(){var e;return(e=v.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e){var i;const t=(i=this.caipNetworks)==null?void 0:i.find(r=>r.id===e.id);if(!t){ac.open(Xa.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await v.switchActiveNetwork(t)}getWalletProvider(){return v.state.activeChain?Je.state.providers[v.state.activeChain]:null}getWalletProviderType(){return Je.getProviderId(v.state.activeChain)}subscribeProviders(e){return Je.subscribeProviders(e)}getThemeMode(){return Vt.state.themeMode}getThemeVariables(){return Vt.state.themeVariables}setThemeMode(e){Vt.setThemeMode(e),sv(Vt.state.themeMode)}setTermsConditionsUrl(e){D.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){D.setPrivacyPolicyUrl(e)}setThemeVariables(e){Vt.setThemeVariables(e),c6(Vt.state.themeVariables)}subscribeTheme(e){return Vt.subscribe(e)}getWalletInfo(){return Z.state.connectedWalletInfo}getAccount(e){const t=te.getAuthConnector(e),i=v.getAccountData(e);if(i)return{allAccounts:i.allAccounts,caipAddress:i.caipAddress,address:se.getPlainAddress(i.caipAddress),isConnected:!!i.caipAddress,status:i.status,embeddedWalletInfo:t?{user:i.user,authProvider:i.socialProvider||"email",accountType:i.preferredAccountType,isSmartAccountDeployed:!!i.smartAccountDeployed}:void 0}}subscribeAccount(e,t){const i=()=>{const r=this.getAccount(t);r&&e(r)};t?v.subscribeChainProp("accountState",i,t):v.subscribe(i),te.subscribe(i)}subscribeNetwork(e){return v.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t==null?void 0:t.id,caipNetworkId:t==null?void 0:t.caipNetworkId})})}subscribeWalletInfo(e){return Z.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){Z.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){v.subscribeKey("activeCaipNetwork",e)}getState(){return fi.state}subscribeState(e){return fi.subscribe(e)}showErrorMessage(e){xt.showError(e)}showSuccessMessage(e){xt.showSuccess(e)}getEvent(){return{...ze.state}}subscribeEvents(e){return ze.subscribe(e)}replace(e){Se.replace(e)}redirect(e){Se.push(e)}popTransactionStack(e){Se.popTransactionStack(e)}isOpen(){return ct.state.open}isTransactionStackEmpty(){return Se.state.transactionStack.length===0}isTransactionShouldReplaceView(){var e;return(e=Se.state.transactionStack[Se.state.transactionStack.length-1])==null?void 0:e.replace}static getInstance(){return this.instance}updateFeatures(e){D.setFeatures(e)}updateOptions(e){const i={...D.state||{},...e};D.setOptions(i)}setConnectMethodsOrder(e){D.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){D.setWalletFeaturesOrder(e)}setCollapseWallets(e){D.setCollapseWallets(e)}setSocialsOrder(e){D.setSocialsOrder(e)}getConnectMethodsOrder(){return mu.getConnectOrderMethod(D.state.features,te.getConnectors())}removeAdapter(e){var n;const t=this.getIsConnectedState(),i=this.getAdapter(e);if(!i||!this.chainAdapters||t)return;const r=(n=this.caipNetworks)==null?void 0:n.filter(o=>o.chainNamespace!==e);v.removeAdapter(e),te.removeAdapter(e),this.chainNamespaces=this.chainNamespaces.filter(o=>o!==e),this.caipNetworks=r,i.removeAllEventListeners(),Reflect.deleteProperty(this.chainAdapters,e)}addAdapter(e,t){const i=e.namespace;if(!this.connectionControllerClient||!this.networkControllerClient||!this.chainAdapters||!i)return;const r=this.extendCaipNetworks({...this.options,networks:t});this.caipNetworks=[...this.caipNetworks||[],...r],this.createAdapter(e),this.initChainAdapter(i),v.addAdapter(e,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient},r)}addNetwork(e,t){var r;if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const i=this.extendCaipNetwork(t,this.options);v.addNetwork(i),this.caipNetworks&&!((r=this.caipNetworks)!=null&&r.find(n=>n.id===i.id))&&this.caipNetworks.push(i)}removeNetwork(e,t){var n;if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);if(!((n=this.caipNetworks)==null?void 0:n.find(o=>o.id===t)))throw new Error(`Network with ID ${t} not found`);if(!this.caipNetworks)return;const r=this.caipNetworks.filter(o=>o.chainNamespace===e&&o.id!==t);if(!(r!=null&&r.length))throw new Error("Cannot remove last network for a namespace");v.removeNetwork(e,t),this.caipNetworks=[...r]}}let hm=!1;class f6 extends g6{async open(e){te.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&Ue.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!hm&&se.isClient()){if(await Vo(()=>import("./basic-C5fzEsEe.js"),__vite__mapDeps([12,13,1,2,14,7,8,9,10,3,4])),await Vo(()=>import("./w3m-modal-DpvEw1mA.js"),__vite__mapDeps([15,13,1,2,7,8,9,10,3,4])),!document.querySelector("w3m-modal")){const t=document.createElement("w3m-modal");!D.state.disableAppend&&!D.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",t)}hm=!0}}}const m6="1.7.2";function w6(s){return new f6({...s,basic:!0,sdkVersion:`html-core-${m6}`})}function y6(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<s.length;c++){const h=s.charAt(c),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=c}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,u=0,d=0;const p=c.length;for(;d!==p&&c[d]===0;)d++,h++;const g=(p-d)*n+1>>>0,f=new Uint8Array(g);for(;d!==p;){let m=c[d],b=0;for(let I=g-1;(m!==0||b<u)&&I!==-1;I--,b++)m+=256*f[I]>>>0,f[I]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");u=b,d++}let y=g-u;for(;y!==g&&f[y]===0;)y++;let w=i.repeat(h);for(;y<g;++y)w+=s.charAt(f[y]);return w}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;c[h]===i;)u++,h++;const p=(c.length-h)*r+1>>>0,g=new Uint8Array(p);for(;h<c.length;){const m=c.charCodeAt(h);if(m>255)return;let b=e[m];if(b===255)return;let I=0;for(let N=p-1;(b!==0||I<d)&&N!==-1;N--,I++)b+=t*g[N]>>>0,g[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=I,h++}let f=p-d;for(;f!==p&&g[f]===0;)f++;const y=new Uint8Array(u+(p-f));let w=u;for(;f!==p;)y[w++]=g[f++];return y}function l(c){const h=a(c);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:l}}var b6="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const uh=y6(b6);class Tn extends Error{constructor(){super(),Object.setPrototypeOf(this,Tn.prototype)}}class um extends Error{constructor(e){super(`WalletConnect Adapter - Method ${e} is not supported by the wallet`),this.name="WalletConnectFeatureNotSupportedError"}}function v6(s){let e=[s];return s===pt.Mainnet||s===pt.Deprecated_Mainnet?(e=[pt.Mainnet,pt.Deprecated_Mainnet],s===pt.Deprecated_Mainnet&&console.warn(Rc.mainnet)):(s===pt.Deprecated_Devnet||s===pt.Devnet)&&(e=[pt.Devnet,pt.Deprecated_Devnet],console.warn(Rc.devnet)),e}const Rc={mainnet:`You are using a deprecated chain ID for Solana Mainnet, please use ${pt.Mainnet} instead.`,devnet:`You are using a deprecated chain ID for Solana Devnet, please use ${pt.Devnet} instead.`,wallet:"The connected wallet is using a deprecated chain ID for Solana. Please, contact them to upgrade. You can learn more at https://github.com/ChainAgnostic/namespaces/blob/main/solana/caip10.md#chain-ids"};function dm(s,e){var i;const t=(i=s.namespaces.solana)==null?void 0:i.accounts.map(r=>`solana:${r.split(":")[1]}`);if(e===pt.Mainnet)return t!=null&&t.find(r=>r===pt.Mainnet)?pt.Mainnet:(console.warn(Rc.wallet),pt.Deprecated_Mainnet);if(e===pt.Devnet)return t!=null&&t.find(r=>r===pt.Devnet)?pt.Devnet:(console.warn(Rc.wallet),pt.Deprecated_Devnet);throw Error("WalletConnect Solana Adapter: Unable to get a default chain from the session.")}function I6(s){return{optionalNamespaces:{solana:{chains:v6(s),methods:[$s.signTransaction,$s.signMessage],events:[]}}}}class sd extends Error{constructor(){super("QR Code Modal was closed by user"),Object.setPrototypeOf(this,sd.prototype),this.name="QRCodeModalError"}}class E6{constructor(e){Nt(this,"_UniversalProvider");Nt(this,"_session");Nt(this,"_modal");Nt(this,"_projectId");Nt(this,"_network");Nt(this,"_ConnectQueueResolver");if(this.initClient(e.options),this._network=e.network,!e.options.projectId)throw Error("WalletConnect Adapter: Project ID is undefined");this._projectId=e.options.projectId}async connect(){var r,n,o,a,l,c;if(this._UniversalProvider||await new Promise(h=>{this._ConnectQueueResolver=h}),!this._UniversalProvider)throw new Error("WalletConnect Adapter - Universal Provider was undefined while calling 'connect()'");if(this._UniversalProvider.session){this._session=this._UniversalProvider.session;const h=dm(this._session,this._network);return this._network=h,this._UniversalProvider.setDefaultChain(h),{publicKey:this.publicKey}}await this.initModal();const e=I6(this._network);(r=this._modal)==null||r.open();const t=new AbortController,i=t.signal;(n=this._modal)==null||n.subscribeState(h=>{h.open||t.abort(new sd)});try{const h=await Promise.race([(o=this._UniversalProvider)==null?void 0:o.connect(e),new Promise((d,p)=>{i.addEventListener("abort",()=>{p(i.reason)})})]);if((a=this._modal)==null||a.close(),this._session=h,!h)throw new Fc;const u=dm(h,this._network);return this._network=u,(l=this._UniversalProvider)==null||l.setDefaultChain(u),{publicKey:this.publicKey}}catch(h){throw(c=this._modal)==null||c.close(),h}}async disconnect(){var e;if((e=this._UniversalProvider)!=null&&e.session){if(await this.initModal(),!this._modal)throw Error("WalletConnect Adapter -Modal is undefined: unable to disconnect");await this.client.disconnect(),this._session=void 0}else throw new Tn}get client(){if(this._UniversalProvider)return this._UniversalProvider;throw new Tn}get session(){if(!this._session)throw new Tn;return this._session}get publicKey(){var e,t,i;if((e=this._UniversalProvider)!=null&&e.session&&this._session){const{address:r}=EI(((i=(t=this._session)==null?void 0:t.namespaces.solana)==null?void 0:i.accounts[0])??"");return new ei(r)}throw new Tn}async signTransaction(e){this.checkIfWalletSupportsMethod($s.signTransaction);const t=pi(e),i=t?{}:e,{signature:r,transaction:n}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:$s.signTransaction,params:{...i,transaction:this.serialize(e)}}});return n?this.deserialize(n,t):(e.addSignature(this.publicKey,_.Buffer.from(uh.decode(r))),e)}async signMessage(e){this.checkIfWalletSupportsMethod($s.signMessage);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:$s.signMessage,params:{pubkey:this.publicKey.toString(),message:uh.encode(e)}}});return uh.decode(t)}async signAndSendTransaction(e){this.checkIfWalletSupportsMethod($s.signAndSendTransaction);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:$s.signAndSendTransaction,params:{transaction:this.serialize(e)}}});return t}async signAllTransactions(e){try{this.checkIfWalletSupportsMethod($s.signAllTransactions);const t=e.map(r=>this.serialize(r)),{transactions:i}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:$s.signAllTransactions,params:{transactions:t}}});return e.map((r,n)=>pi(r)?this.deserialize(i[n]??"",!0):this.deserialize(i[n]??""))}catch(t){if(t instanceof um){const i=e.map(n=>this.signTransaction(n));return await Promise.all(i)}throw t}}async initClient(e){const t=await Bx.init(e);this._UniversalProvider=t,this._ConnectQueueResolver&&this._ConnectQueueResolver(!0)}async initModal(){if(!this._modal){if(!this._UniversalProvider)throw new Error("WalletConnect Adapter - cannot init modal when Universal Provider is undefined");this._modal=w6({projectId:this._projectId,universalProvider:this._UniversalProvider,networks:[yu,bu,l6],manualWCControl:!0})}}serialize(e){return _.Buffer.from(e.serialize({verifySignatures:!1})).toString("base64")}deserialize(e,t=!1){return t?dh.deserialize(_.Buffer.from(e,"base64")):ph.from(_.Buffer.from(e,"base64"))}checkIfWalletSupportsMethod(e){var t;if(!((t=this.session.namespaces.solana)!=null&&t.methods.includes(e)))throw new um(e)}}const A6="WalletConnect";class N6 extends Nu{constructor(t){super();Nt(this,"name",A6);Nt(this,"url","https://walletconnect.org");Nt(this,"icon","data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjE4NSIgdmlld0JveD0iMCAwIDMwMCAxODUiIHdpZHRoPSIzMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTYxLjQzODU0MjkgMzYuMjU2MjYxMmM0OC45MTEyMjQxLTQ3Ljg4ODE2NjMgMTI4LjIxMTk4NzEtNDcuODg4MTY2MyAxNzcuMTIzMjA5MSAwbDUuODg2NTQ1IDUuNzYzNDE3NGMyLjQ0NTU2MSAyLjM5NDQwODEgMi40NDU1NjEgNi4yNzY1MTEyIDAgOC42NzA5MjA0bC0yMC4xMzY2OTUgMTkuNzE1NTAzYy0xLjIyMjc4MSAxLjE5NzIwNTEtMy4yMDUzIDEuMTk3MjA1MS00LjQyODA4MSAwbC04LjEwMDU4NC03LjkzMTE0NzljLTM0LjEyMTY5Mi0zMy40MDc5ODE3LTg5LjQ0Mzg4Ni0zMy40MDc5ODE3LTEyMy41NjU1Nzg4IDBsLTguNjc1MDU2MiA4LjQ5MzYwNTFjLTEuMjIyNzgxNiAxLjE5NzIwNDEtMy4yMDUzMDEgMS4xOTcyMDQxLTQuNDI4MDgwNiAwbC0yMC4xMzY2OTQ5LTE5LjcxNTUwMzFjLTIuNDQ1NTYxMi0yLjM5NDQwOTItMi40NDU1NjEyLTYuMjc2NTEyMiAwLTguNjcwOTIwNHptMjE4Ljc2Nzc5NjEgNDAuNzczNzQ0OSAxNy45MjE2OTcgMTcuNTQ2ODk3YzIuNDQ1NTQ5IDIuMzk0Mzk2OSAyLjQ0NTU2MyA2LjI3NjQ3NjkuMDAwMDMxIDguNjcwODg5OWwtODAuODEwMTcxIDc5LjEyMTEzNGMtMi40NDU1NDQgMi4zOTQ0MjYtNi40MTA1ODIgMi4zOTQ0NTMtOC44NTYxNi4wMDAwNjItLjAwMDAxLS4wMDAwMS0uMDAwMDIyLS4wMDAwMjItLjAwMDAzMi0uMDAwMDMybC01Ny4zNTQxNDMtNTYuMTU0NTcyYy0uNjExMzktLjU5ODYwMi0xLjYwMjY1LS41OTg2MDItMi4yMTQwNCAwLS4wMDAwMDQuMDAwMDA0LS4wMDAwMDcuMDAwMDA4LS4wMDAwMTEuMDAwMDExbC01Ny4zNTI5MjEyIDU2LjE1NDUzMWMtMi40NDU1MzY4IDIuMzk0NDMyLTYuNDEwNTc1NSAyLjM5NDQ3Mi04Ljg1NjE2MTIuMDAwMDg3LS4wMDAwMTQzLS4wMDAwMTQtLjAwMDAyOTYtLjAwMDAyOC0uMDAwMDQ0OS0uMDAwMDQ0bC04MC44MTI0MTk0My03OS4xMjIxODVjLTIuNDQ1NTYwMjEtMi4zOTQ0MDgtMi40NDU1NjAyMS02LjI3NjUxMTUgMC04LjY3MDkxOTdsMTcuOTIxNzI5NjMtMTcuNTQ2ODY3M2MyLjQ0NTU2MDItMi4zOTQ0MDgyIDYuNDEwNTk4OS0yLjM5NDQwODIgOC44NTYxNjAyIDBsNTcuMzU0OTc3NSA1Ni4xNTUzNTdjLjYxMTM5MDguNTk4NjAyIDEuNjAyNjQ5LjU5ODYwMiAyLjIxNDAzOTggMCAuMDAwMDA5Mi0uMDAwMDA5LjAwMDAxNzQtLjAwMDAxNy4wMDAwMjY1LS4wMDAwMjRsNTcuMzUyMTAzMS01Ni4xNTUzMzNjMi40NDU1MDUtMi4zOTQ0NjMzIDYuNDEwNTQ0LTIuMzk0NTUzMSA4Ljg1NjE2MS0uMDAwMi4wMDAwMzQuMDAwMDMzNi4wMDAwNjguMDAwMDY3My4wMDAxMDEuMDAwMTAxbDU3LjM1NDkwMiA1Ni4xNTU0MzJjLjYxMTM5LjU5ODYwMSAxLjYwMjY1LjU5ODYwMSAyLjIxNDA0IDBsNTcuMzUzOTc1LTU2LjE1NDMyNDljMi40NDU1NjEtMi4zOTQ0MDkyIDYuNDEwNTk5LTIuMzk0NDA5MiA4Ljg1NjE2IDB6IiBmaWxsPSIjM2I5OWZjIi8+PC9zdmc+");Nt(this,"supportedTransactionVersions",new Set(["legacy",0]));Nt(this,"_publicKey");Nt(this,"_connecting");Nt(this,"_wallet");Nt(this,"_config");Nt(this,"_readyState");Nt(this,"_onDisconnect");this._publicKey=null,this._connecting=!1,this._config=t,this._wallet=null,this._readyState=typeof window>"u"?ne.Unsupported:ne.Loadable,this._onDisconnect=this.disconnect.bind(this)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ne.Loadable)throw new Ki;this._connecting=!0,this._wallet=new E6({network:this._config.network===Ko.Mainnet?Ic.Mainnet:Ic.Devnet,options:this._config.options});const{publicKey:t}=await this._wallet.connect();this._publicKey=t,this.emit("connect",t),this._wallet.client.on("session_delete",this._onDisconnect)}catch(t){throw t.constructor.name==="QRCodeModalError"||t instanceof Error&&t.name==="QRCodeModalError"?new _v:(this._connecting=!1,t)}finally{this._connecting=!1}}async disconnect(){const t=this._wallet;if(t){t.client.off("session_delete",this._onDisconnect),this._publicKey=null;try{t.client.session&&await t.disconnect()}catch(i){console.error("WalletConnectWalletAdapter: disconnect error",i),this.emit("error",new la(i==null?void 0:i.message,i))}}this.emit("disconnect")}async signTransaction(t){try{const i=this._wallet;if(!i)throw new Fe;try{return await i.signTransaction(t)}catch(r){throw new et(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signMessage(t){try{const i=this._wallet;if(!i)throw new Fe;try{return await i.signMessage(t)}catch(r){throw new ha(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signAndSendTransaction(t){try{const i=this._wallet;if(!i)throw new Fe;try{return await i.signAndSendTransaction(t)}catch(r){throw new et(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signAllTransactions(t){try{const i=this._wallet;if(!i)throw new Fe;try{return await i.signAllTransactions(t)}catch(r){throw new et(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}}const _6={icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgdmlld0JveD0iMCAwIDI1NiAyNTYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8yMDM1XzExMDYpIj4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IiM1NEZGRjUiLz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjBfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTEzLjQ4MDYgMTk4LjYwNUMtMjkuMzI3NiAzMTkuMDQzIDE5OS42NjEgMjg1LjAyNyAzMTkuNTA3IDI1Mi45NjRDNDQyLjE2NSAyMTIuMjU5IDM1Ny4zODYgMzIuODI2OSAyNjkuNDE1IDI4Ljg1NThDMTgxLjQ0MyAyNC44ODQ3IDI4MC4zMjIgMTExLjgyNCAyMDUuNTk1IDEzNi42NTZDMTMwLjg2OCAxNjEuNDg3IDY2Ljk5MDcgNDguMDU4MyAxMy40ODA2IDE5OC42MDVaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjxnIGZpbHRlcj0idXJsKCNmaWx0ZXIxX2ZfMjAzNV8xMTA2KSI+CjxwYXRoIGQ9Ik04NS41MTE4IC00NS44MjI1QzYzLjA1NjIgLTEwNy4xNzYgLTE2LjkxODkgLTIzLjk5NTMgLTU0LjA5OTUgMjUuMjY0M0MtODkuNTY1MiA3OC44NDc5IDMuMDA5MzcgMTI1LjE1MiAzOS4zMjA4IDEwMC4wMzdDNzUuNjMyMyA3NC45MjI3IDcuNzc0NDggNzAuMDM2MyAyOS4zNzA4IDM3LjM3ODVDNTAuOTY3MSA0LjcyMDc2IDExMy41ODEgMzAuODY5NSA4NS41MTE4IC00NS44MjI1WiIgZmlsbD0iIzAwRkZGMCIgZmlsbC1vcGFjaXR5PSIwLjY3Ii8+CjwvZz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjJfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTk2LjQ3OTYgMjI1LjQyNEM2NS44NTAyIDEyMi4zNjMgLTY2LjA4MTggMTc2LjYzNyAtMTI4LjIxOSAyMTYuNjU3Qy0xODcuOTkgMjY0LjA0MiAtNDYuMDcxMSA0MDAuMzQ4IDEyLjg3MjUgMzkzLjM3NkM3MS44MTYxIDM4Ni40MDMgLTM0LjQxMTggMzI3LjA2NSAxLjk4NzAyIDI5OC4xN0MzOC4zODU4IDI2OS4yNzYgMTM0Ljc2NiAzNTQuMjQ5IDk2LjQ3OTYgMjI1LjQyNFoiIGZpbGw9IiM5RDgxRkYiLz4KPC9nPgo8ZyBmaWx0ZXI9InVybCgjZmlsdGVyM19mXzIwMzVfMTEwNikiPgo8cGF0aCBkPSJNMjgyLjEyIC0xMDcuMzUzQzIxNi4wNDcgLTE4Ni4wMzEgMTIxLjQ2MyAtMTIwLjk3IDgyLjQyOTYgLTc4LjYwNDdDNDguMjczOSAtMzAuNjQ0NiAyMjQuMjc1IDU3LjIzMTIgMjczLjEyMSA0Mi4xNzE0QzMyMS45NjggMjcuMTExNSAyMDYuNTEyIC00LjA1MDM4IDIyNy4yOTcgLTMzLjI4NzlDMjQ4LjA4MiAtNjIuNTI1NSAzNjQuNzEyIC05LjAwNTY2IDI4Mi4xMiAtMTA3LjM1M1oiIGZpbGw9IiM0RDk0RkYiLz4KPC9nPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkzLjE4OSAxNTIuODM2SDEzNi42NzRMODcuMjA4NiAxMDMuMDUxTDEzNy4zMSA1My4yNjYzTDE1MC45NTUgNDBIMTA1LjgxOUw0OC4zMzU5IDk3Ljc3NzNDNDUuNDM0OSAxMDAuNjg5IDQ1LjQ0OTggMTA1LjQwMiA0OC4zNjU2IDEwOC4yOTlMOTMuMTg5IDE1Mi44MzZaTTExOS4zMyAxMDMuMTY4SDExOC45OTVMMTE5LjMyNiAxMDMuMTY0TDExOS4zMyAxMDMuMTY4Wk0xMTkuMzMgMTAzLjE2OEwxNjguNzkxIDE1Mi45NDlMMTE4LjY5IDIwMi43MzRMMTA1LjA0NSAyMTZIMTUwLjE4TDIwNy42NjQgMTU4LjIyNkMyMTAuNTY1IDE1NS4zMTQgMjEwLjU1IDE1MC42MDIgMjA3LjYzNCAxNDcuNzA1TDE2Mi44MTEgMTAzLjE2OEgxMTkuMzNaIiBmaWxsPSJibGFjayIvPgo8L2c+CjxkZWZzPgo8ZmlsdGVyIGlkPSJmaWx0ZXIwX2ZfMjAzNV8xMTA2IiB4PSItOTAuMjQxMSIgeT0iLTY5LjczNjkiIHdpZHRoPSI1NjkuNTU4IiBoZWlnaHQ9IjQ1MS40MzEiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyMV9mXzIwMzVfMTEwNiIgeD0iLTE2MC41MTEiIHk9Ii0xNjUuOTg3IiB3aWR0aD0iMzUxLjU5NiIgaGVpZ2h0PSIzNzEuNTA3IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxmaWx0ZXIgaWQ9ImZpbHRlcjJfZl8yMDM1XzExMDYiIHg9Ii0yNDEuMDc4IiB5PSI2Ny42NDIiIHdpZHRoPSI0NDQuODUxIiBoZWlnaHQ9IjQyNC40NTIiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyM19mXzIwMzVfMTEwNiIgeD0iLTIwLjM5NjgiIHk9Ii0yNDIuNzU4IiB3aWR0aD0iNDMwLjE5MSIgaGVpZ2h0PSIzODUuMTA1IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxjbGlwUGF0aCBpZD0iY2xpcDBfMjAzNV8xMTA2Ij4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==",name:"Bitget Wallet"},C6=[_6],S6=s=>C6.find(e=>e.name.toLocaleLowerCase().includes(s.name.toLocaleLowerCase()))||s,$6=(s,e,t)=>e[s]||t[s],pm=(s,e)=>$6(s,S6(e),e);class Ci extends lv{constructor(e,t){super(),this.adapter=e,this.connection=t}getAdapter(){return this.adapter}getName(){return pm("name",this.adapter)}getUrl(){return this.adapter.url}async connect(){if(this.isConnected())return this.getAddresses();const e=await new Promise((t,i)=>{this.adapter.on("connect",()=>{this.adapter.off("connect"),this.adapter.off("error"),t(this.getAddresses())}),this.adapter.on("error",r=>{this.adapter.off("connect"),this.adapter.off("error"),i(r)}),this.adapter.connect().catch(i)});return this.emit("connect"),this.adapter.on("disconnect",()=>this.emit("disconnect")),e}getNetworkInfo(){return{}}isConnected(){return this.adapter.connected}async disconnect(){this.isConnected()&&(await new Promise((e,t)=>{this.adapter.on("disconnect",()=>{this.adapter.off("disconnect"),this.adapter.off("error"),e(void 0)}),this.adapter.on("error",i=>{this.adapter.off("disconnect"),this.adapter.off("error"),t(i)}),this.adapter.disconnect().catch(t)}),this.adapter.removeAllListeners(),this.emit("disconnect"))}getChainId(){return id}getAddress(){var e;return(e=this.adapter.publicKey)==null?void 0:e.toString()}getAddresses(){const e=this.getAddress();return e?[e]:[]}setMainAddress(){throw new Error("Not supported")}getBalance(){throw new Error("Not supported")}async signTransaction(e){if(!this.adapter.signTransaction||!this.adapter.signAllTransactions)throw new Error("Not supported");return Array.isArray(e)?this.adapter.signAllTransactions(e):this.adapter.signTransaction(e)}async sendTransaction(e){var n;const{transaction:t}=e,i=Array.isArray(t)?t:[t];if(i.length===0)throw new Error("Empty transactions array");const r=[];for(const o of i){const a=await this.adapter.sendTransaction(o,this.connection,{...e.options});r.push(a)}return await this.connection.confirmTransaction(r[0],(n=e.options)==null?void 0:n.commitment),{id:r[0],data:r.length===1?r[0]:r}}async signAndSendTransaction(e){return this.sendTransaction(e)}signMessage(e){if(!this.adapter.signMessage)throw new Error("Not supported");return this.adapter.signMessage(e)}getIcon(){return pm("icon",this.adapter)}getWalletState(){const e=this.adapter.readyState;if(!(e in rd))throw new Error(`Unknown wallet state ${e}`);return rd[e]}getFeatures(){const e=[Pa.SendTransaction,Pa.SignAndSendTransaction];return this.adapter.signTransaction&&this.adapter.signAllTransactions&&e.push(Pa.SignTransaction),this.adapter.signMessage&&e.push(Pa.SignMessage),e}supportsChain(e){return e===id}}function P6(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<s.length;c++){const h=s.charAt(c),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=c}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,u=0,d=0;const p=c.length;for(;d!==p&&c[d]===0;)d++,h++;const g=(p-d)*n+1>>>0,f=new Uint8Array(g);for(;d!==p;){let m=c[d],b=0;for(let I=g-1;(m!==0||b<u)&&I!==-1;I--,b++)m+=256*f[I]>>>0,f[I]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");u=b,d++}let y=g-u;for(;y!==g&&f[y]===0;)y++;let w=i.repeat(h);for(;y<g;++y)w+=s.charAt(f[y]);return w}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;c[h]===i;)u++,h++;const p=(c.length-h)*r+1>>>0,g=new Uint8Array(p);for(;h<c.length;){const m=c.charCodeAt(h);if(m>255)return;let b=e[m];if(b===255)return;let I=0;for(let N=p-1;(b!==0||I<d)&&N!==-1;N--,I++)b+=t*g[N]>>>0,g[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=I,h++}let f=p-d;for(;f!==p&&g[f]===0;)f++;const y=new Uint8Array(u+(p-f));let w=u;for(;f!==p;)y[w++]=g[f++];return y}function l(c){const h=a(c);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:l}}var T6="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const M6=P6(T6);var V=function(s,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!i:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(s):i?i.value:e.get(s)},ot=function(s,e,t,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(s,t):r?r.value=t:e.set(s,t),t},Ot,ns,fr,mr,ar,ko,Lc,me,Uc,vu,yc,Iu,Wo,Eu,gm,fm,mm,wm;class O6 extends xm{get name(){return V(this,me,"f").name}get url(){return"https://github.com/solana-labs/wallet-standard"}get icon(){return V(this,me,"f").icon}get readyState(){return V(this,Uc,"f")}get publicKey(){return V(this,fr,"f")}get connecting(){return V(this,mr,"f")}get supportedTransactionVersions(){return V(this,Lc,"f")}get wallet(){return V(this,me,"f")}get standard(){return!0}constructor({wallet:e}){super(),Ot.add(this),ns.set(this,void 0),fr.set(this,void 0),mr.set(this,void 0),ar.set(this,void 0),ko.set(this,void 0),Lc.set(this,void 0),me.set(this,void 0),Uc.set(this,typeof window>"u"||typeof document>"u"?ne.Unsupported:ne.Installed),Eu.set(this,t=>{if("accounts"in t){const i=V(this,me,"f").accounts[0];V(this,ns,"f")&&!V(this,ar,"f")&&i!==V(this,ns,"f")&&(i?V(this,Ot,"m",yc).call(this,i):(this.emit("error",new Om),V(this,Ot,"m",Iu).call(this)))}"features"in t&&V(this,Ot,"m",Wo).call(this)}),ot(this,me,e,"f"),ot(this,ns,null,"f"),ot(this,fr,null,"f"),ot(this,mr,!1,"f"),ot(this,ar,!1,"f"),ot(this,ko,V(this,me,"f").features[km].on("change",V(this,Eu,"f")),"f"),V(this,Ot,"m",Wo).call(this)}destroy(){ot(this,ns,null,"f"),ot(this,fr,null,"f"),ot(this,mr,!1,"f"),ot(this,ar,!1,"f");const e=V(this,ko,"f");e&&(ot(this,ko,null,"f"),e())}async autoConnect(){return V(this,Ot,"m",vu).call(this,{silent:!0})}async connect(){return V(this,Ot,"m",vu).call(this)}async disconnect(){if(hd in V(this,me,"f").features)try{ot(this,ar,!0,"f"),await V(this,me,"f").features[hd].disconnect()}catch(e){this.emit("error",new la(e==null?void 0:e.message,e))}finally{ot(this,ar,!1,"f")}V(this,Ot,"m",Iu).call(this)}async sendTransaction(e,t,i={}){try{const r=V(this,ns,"f");if(!r)throw new Fe;let n;if(Oi in V(this,me,"f").features)if(r.features.includes(Oi))n=Oi;else if(Mt in V(this,me,"f").features&&r.features.includes(Mt))n=Mt;else throw new Ps;else if(Mt in V(this,me,"f").features){if(!r.features.includes(Mt))throw new Ps;n=Mt}else throw new Cn;const o=Wv(t.rpcEndpoint);if(!r.chains.includes(o))throw new ur;try{const{signers:a,...l}=i;let c;if(pi(e)?(a!=null&&a.length&&e.sign(a),c=e.serialize()):(e=await this.prepareTransaction(e,t,l),a!=null&&a.length&&e.partialSign(...a),c=new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))),n===Oi){const[h]=await V(this,me,"f").features[Oi].signAndSendTransaction({account:r,chain:o,transaction:c,options:{preflightCommitment:pl(l.preflightCommitment||t.commitment),skipPreflight:l.skipPreflight,maxRetries:l.maxRetries,minContextSlot:l.minContextSlot}});return M6.encode(h.signature)}else{const[h]=await V(this,me,"f").features[Mt].signTransaction({account:r,chain:o,transaction:c,options:{preflightCommitment:pl(l.preflightCommitment||t.commitment),minContextSlot:l.minContextSlot}});return await t.sendRawTransaction(h.signedTransaction,{...l,preflightCommitment:pl(l.preflightCommitment||t.commitment)})}}catch(a){throw a instanceof jt?a:new ur(a==null?void 0:a.message,a)}}catch(r){throw this.emit("error",r),r}}}ns=new WeakMap,fr=new WeakMap,mr=new WeakMap,ar=new WeakMap,ko=new WeakMap,Lc=new WeakMap,me=new WeakMap,Uc=new WeakMap,Eu=new WeakMap,Ot=new WeakSet,vu=async function(e){try{if(this.connected||this.connecting)return;if(V(this,Uc,"f")!==ne.Installed)throw new Ki;if(ot(this,mr,!0,"f"),!V(this,me,"f").accounts.length)try{await V(this,me,"f").features[Dm].connect(e)}catch(i){throw new Fc(i==null?void 0:i.message,i)}const t=V(this,me,"f").accounts[0];if(!t)throw new Ps;V(this,Ot,"m",yc).call(this,t)}catch(t){throw this.emit("error",t),t}finally{ot(this,mr,!1,"f")}},yc=function(e){let t;try{t=new ei(e.address)}catch(i){throw new Pr(i==null?void 0:i.message,i)}ot(this,ns,e,"f"),ot(this,fr,t,"f"),V(this,Ot,"m",Wo).call(this),this.emit("connect",t)},Iu=function(){ot(this,ns,null,"f"),ot(this,fr,null,"f"),V(this,Ot,"m",Wo).call(this),this.emit("disconnect")},Wo=function(){var t,i;const e=Oi in V(this,me,"f").features?V(this,me,"f").features[Oi].supportedTransactionVersions:V(this,me,"f").features[Mt].supportedTransactionVersions;ot(this,Lc,gv(e,["legacy"])?null:new Set(e),"f"),Mt in V(this,me,"f").features&&((t=V(this,ns,"f"))!=null&&t.features.includes(Mt))?(this.signTransaction=V(this,Ot,"m",gm),this.signAllTransactions=V(this,Ot,"m",fm)):(delete this.signTransaction,delete this.signAllTransactions),io in V(this,me,"f").features&&((i=V(this,ns,"f"))!=null&&i.features.includes(io))?this.signMessage=V(this,Ot,"m",mm):delete this.signMessage,ul in V(this,me,"f").features?this.signIn=V(this,Ot,"m",wm):delete this.signIn},gm=async function(e){try{const t=V(this,ns,"f");if(!t)throw new Fe;if(!(Mt in V(this,me,"f").features))throw new Cn;if(!t.features.includes(Mt))throw new Ps;try{const r=(await V(this,me,"f").features[Mt].signTransaction({account:t,transaction:pi(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return pi(e)?dh.deserialize(r):ph.from(r)}catch(i){throw i instanceof jt?i:new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},fm=async function(e){try{const t=V(this,ns,"f");if(!t)throw new Fe;if(!(Mt in V(this,me,"f").features))throw new Cn;if(!t.features.includes(Mt))throw new Ps;try{const i=await V(this,me,"f").features[Mt].signTransaction(...e.map(r=>({account:t,transaction:pi(r)?r.serialize():new Uint8Array(r.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((r,n)=>{const o=i[n].signedTransaction;return pi(r)?dh.deserialize(o):ph.from(o)})}catch(i){throw new et(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},mm=async function(e){try{const t=V(this,ns,"f");if(!t)throw new Fe;if(!(io in V(this,me,"f").features))throw new Cn;if(!t.features.includes(io))throw new Ps;try{return(await V(this,me,"f").features[io].signMessage({account:t,message:e}))[0].signature}catch(i){throw new ha(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},wm=async function(e={}){try{if(!(ul in V(this,me,"f").features))throw new Cn;let t;try{[t]=await V(this,me,"f").features[ul].signIn(e)}catch(i){throw new ld(i==null?void 0:i.message,i)}if(!t)throw new ld;return V(this,Ot,"m",yc).call(this,t.account),t}catch(t){throw this.emit("error",t),t}};function x6(s){return fv().get().filter(Cv).map(e=>new Ci(new O6({wallet:e}),s))}function D6(s){return s.includes("rpcpool.com")?"triton":s.includes("helius-rpc.com")?"helius":s.includes("rpc.ankr.com")?"ankr":"unknown"}async function k6(s,e,t,i){const r=i.transaction.transaction,n=o=>o.programId.toString()!=="ComputeBudget111111111111111111111111111111";if(fh(r)){const o=(await Promise.all(r.message.addressTableLookups.map(l=>s.getAddressLookupTable(l.accountKey)))).map(l=>l.value).filter(l=>l!==null),a=hv.decompile(r.message,{addressLookupTableAccounts:o});a.recentBlockhash=e,r.message.recentBlockhash=e,a.instructions=a.instructions.filter(n),a.instructions.push(...await ym(s,r)),r.message=a.compileToV0Message(o),r.sign(i.transaction.signers??[])}else r.recentBlockhash=e,r.lastValidBlockHeight=t,r.instructions=r.instructions.filter(n),r.add(...await ym(s,r)),i.transaction.signers&&r.partialSign(...i.transaction.signers);return r}async function ym(s,e,t){var w,m;let i=2e5,r=0;e:for(;;){if(fh(e)&&!e.message.recentBlockhash){const{blockhash:I}=await s.getLatestBlockhash(t);e.message.recentBlockhash=I}const b=await(fh(e)?s.simulateTransaction(e,{commitment:t,replaceRecentBlockhash:!0}):s.simulateTransaction(e));if(b.value.err){if(j6(b.value)){if(r<5){r++,await gh(1e3);continue e}}else if(r<3){r++,await gh(1e3);continue e}throw new Error(`Simulation failed: ${JSON.stringify(b.value.err)}
917
917
  Logs:
918
918
  ${(b.value.logs||[]).join(`
919
919
  `)}`)}else{b.value.unitsConsumed&&(i=b.value.unitsConsumed);break}}const n=Math.floor(i*1.2),o=[];o.push(nd.setComputeUnitLimit({units:n}));const a=((m=(w=Mi.transactionSettings)==null?void 0:w.Solana)==null?void 0:m.priorityFee)||{},{percentile:l=.9,percentileMultiple:c=1,min:h=1e5,max:u=1e8}=a,d=async b=>{if(b==="triton")try{return{fee:await mv(s,e,l,c,h,u),methodUsed:"triton"}}catch(I){console.warn("Failed to determine priority fee using Triton RPC:",I)}try{return{fee:await wv(s,e,l,c,h,u),methodUsed:"default"}}catch(I){return console.warn("Failed to determine priority fee using Triton RPC:",I),{fee:h,methodUsed:"minimum"}}},p=D6(s.rpcEndpoint),{fee:g,methodUsed:f}=await d(p),y=g/1e6/dv*n;return console.table({"RPC Provider":p,"Method used":f,"Percentile used":l,"Multiple used":c,"Compute budget":n,"Priority fee":g,"Max fee in SOL":y}),o.push(nd.setComputeUnitPrice({microLamports:g})),o}function j6(s){const e={};if(s.err==="BlockhashNotFound"&&(e.BlockhashNotFound="Blockhash not found during simulation. Trying again."),s.logs)for(const t of s.logs)t.includes("SlippageToleranceExceeded")&&(e.SlippageToleranceExceeded="Slippage failure during simulation. Trying again."),t.includes("RequireGteViolated")&&(e.RequireGteViolated="Swap instruction failure during simulation. Trying again.");return uv(e)?!1:(console.table(e),!0)}const R6=s=>s.getName().toLowerCase().replaceAll("wallet","").trim();function L6(){const s=Mi.isMainnet?"mainnet-beta":"devnet",e=new vm(Mi.rpcs.Solana||pv(s));return{...x6(e).reduce((t,i)=>(t[R6(i)]=i,t),{}),bitget:new Ci(new $v,e),clover:new Ci(new Tv,e),coin98:new Ci(new Dv,e),solong:new Ci(new Fv,e),torus:new Ci(new Bv,e),nightly:new Ci(new jv,e),...Mi.ui.walletConnectProjectId?{walletConnect:new Ci(new N6({network:Mi.isMainnet?Ko.Mainnet:Ko.Devnet,options:{projectId:Mi.ui.walletConnectProjectId,customStoragePrefix:"wh-connect-solana-adapter"}}),e)}:{}}}async function U6(s,e,t){if(!e)throw new Error("Wallet not found");if(!Mi.rpcs.Solana)throw new Error("Solana RPC not found");const i=(t==null?void 0:t.commitment)??"finalized",r=new vm(Mi.rpcs.Solana),{blockhash:n,lastValidBlockHeight:o}=await r.getLatestBlockhash(i),a=await k6(r,n,o,s);let l=null,c=null,h=1,u="";const p=(await e.signTransaction(a)).serialize(),g={skipPreflight:!0,maxRetries:0,preFlightCommitment:i};u=await r.sendRawTransaction(p,g),l=r.confirmTransaction({signature:u,blockhash:n,lastValidBlockHeight:o},i);try{for(;!c&&(c=await Promise.race([l,new Promise(y=>setTimeout(()=>{y(null)},5e3))]),!c);){console.log(`Tx not confirmed after ${5e3*h++}ms, resending`);try{await r.sendRawTransaction(p,g)}catch(y){console.error("Failed to resend transaction:",y)}}}catch(f){if(f instanceof Error&&f.name==="TransactionExpiredBlockheightExceededError")for(let m=0;m<5;++m){try{if(await r.getTransaction(u,{commitment:"confirmed",maxSupportedTransactionVersion:0}))return u}catch{}await gh(2e3)}throw f}if(c.value.err){let f=`Transaction failed: ${c.value.err}`;if(typeof c.value.err=="object")try{f=`Transaction failed: ${JSON.stringify(c.value.err,(y,w)=>typeof w=="bigint"?w.toString():w)}`}catch{f="Transaction failed: Unknown error"}throw new Error(`Transaction failed: ${f}`)}return u}const jq=Object.freeze(Object.defineProperty({__proto__:null,fetchOptions:L6,signAndSendTransaction:U6},Symbol.toStringTag,{value:"Module"}));export{Rk as $,ie as A,wu as B,te as C,Bn as D,ze as E,dF as F,bd as G,iI as H,Wm as I,K0 as J,rI as K,pF as L,ct as M,uF as N,D as O,Bc as P,mF as Q,Se as R,G as S,Vt as T,gF as U,jk as V,mu as W,bq as X,Ag as Y,ky as Z,Ck as _,wc as a,vq as a0,yq as a1,sl as a2,Eq as a3,Iq as a4,jq as a5,se as b,fc as c,Ny as d,Dq as e,Ue as f,Q as g,Fs as h,Dn as i,xt as j,os as k,Mq as l,v as m,At as n,kq as o,Xe as p,Yt as q,xq as r,vs as s,ac as t,H8 as u,Lo as v,Z as w,Tq as x,Oq as y,Qb as z};