@wormhole-foundation/wormhole-connect 5.2.0-beta.1-development → 5.2.0-beta.2-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 (363) hide show
  1. package/dist/main.mjs +1 -1
  2. package/lib/{add-CiBQclh_.js → add-CsKFlygp.js} +1 -1
  3. package/lib/{add-FlBFbmID.mjs → add-DjE3EcEV.mjs} +1 -1
  4. package/lib/{add-BEf65R9W.mjs → add-DyWulnuS.mjs} +1 -1
  5. package/lib/{add-BfnfRWYd.js → add-bXKhUwqm.js} +1 -1
  6. package/lib/{all-wallets-CGkgmWtX.js → all-wallets-CjJkeTbL.js} +1 -1
  7. package/lib/{all-wallets-0d0F49_e.mjs → all-wallets-DHqzP6L8.mjs} +1 -1
  8. package/lib/{all-wallets-BNdvPhp9.js → all-wallets-DuVECYbS.js} +1 -1
  9. package/lib/{all-wallets-srUUo70q.mjs → all-wallets-vsNOuzqB.mjs} +1 -1
  10. package/lib/{app-store-CyolaTwE.mjs → app-store-BqQ0jSql.mjs} +1 -1
  11. package/lib/{app-store-DhVoNqde.js → app-store-C7d9uBwB.js} +1 -1
  12. package/lib/{app-store-CJ8FOJYx.js → app-store-D9Uf0g65.js} +1 -1
  13. package/lib/{app-store-CImc6f5s.mjs → app-store-UdtOo-dU.mjs} +1 -1
  14. package/lib/{apple-EatMtIc0.mjs → apple-BbL0nfeU.mjs} +1 -1
  15. package/lib/{apple-B7hoK4SW.js → apple-C-UBDZE5.js} +1 -1
  16. package/lib/{apple-tebbLLOI.mjs → apple-Vysn1QLU.mjs} +1 -1
  17. package/lib/{apple-86OXeSyJ.js → apple-wWE5v0dD.js} +1 -1
  18. package/lib/{aptos-C8LQMcii.mjs → aptos-CRLnl4L1.mjs} +2 -2
  19. package/lib/{aptos-B0625Vkk.js → aptos-CfulxqiY.js} +1 -1
  20. package/lib/{arrow-bottom-DgI3vkHl.mjs → arrow-bottom-9yPqOOG8.mjs} +1 -1
  21. package/lib/{arrow-bottom-D7KU41sS.js → arrow-bottom-BBJZscVl.js} +1 -1
  22. package/lib/{arrow-bottom-Bmf9qeKd.mjs → arrow-bottom-BGYif__M.mjs} +1 -1
  23. package/lib/{arrow-bottom-BRHd31a5.js → arrow-bottom-C-OOeDgc.js} +1 -1
  24. package/lib/{arrow-bottom-circle-1_MXO-aE.js → arrow-bottom-circle-CTY2zo9T.js} +1 -1
  25. package/lib/{arrow-bottom-circle-BRl5lIFV.mjs → arrow-bottom-circle-CqVKSEcX.mjs} +1 -1
  26. package/lib/{arrow-bottom-circle-Ioaofxby.mjs → arrow-bottom-circle-D0nATh37.mjs} +1 -1
  27. package/lib/{arrow-bottom-circle-dUItEBid.js → arrow-bottom-circle-D3Z0Vp2Y.js} +1 -1
  28. package/lib/{arrow-left-CeaRd5Vx.mjs → arrow-left-BNgvZYhH.mjs} +1 -1
  29. package/lib/{arrow-left-B4VB8tQR.js → arrow-left-JnPB5GSd.js} +1 -1
  30. package/lib/{arrow-left-DRD62h5u.js → arrow-left-Ltg2X3oS.js} +1 -1
  31. package/lib/{arrow-left-B18SPbUr.mjs → arrow-left-O1B6lnQQ.mjs} +1 -1
  32. package/lib/{arrow-right-BpXZlXh9.mjs → arrow-right-Bh49cjrw.mjs} +1 -1
  33. package/lib/{arrow-right-CzWLUAUO.mjs → arrow-right-CcdvbUHJ.mjs} +1 -1
  34. package/lib/{arrow-right-CI54SlzC.js → arrow-right-D_chbEOv.js} +1 -1
  35. package/lib/{arrow-right-Dd6A8iJC.js → arrow-right-Db115d3K.js} +1 -1
  36. package/lib/{arrow-top-c0RWLlO2.mjs → arrow-top-CrrEgZiG.mjs} +1 -1
  37. package/lib/{arrow-top-oGu2iy6k.mjs → arrow-top-D3Cn3i5J.mjs} +1 -1
  38. package/lib/{arrow-top-BOP9Mx0U.js → arrow-top-NsizVEZs.js} +1 -1
  39. package/lib/{arrow-top-TPGebFgG.js → arrow-top-v7JHs5yr.js} +1 -1
  40. package/lib/{bank-BSgi9PAk.mjs → bank-BLISl4z-.mjs} +1 -1
  41. package/lib/{bank--z_wgCs2.mjs → bank-DYm6Brrt.mjs} +1 -1
  42. package/lib/{bank-DDWUQfzS.js → bank-MKPdWaVj.js} +1 -1
  43. package/lib/{bank-CyILnlME.js → bank-VxPvAyIR.js} +1 -1
  44. package/lib/{basic-C_NK3mGS.js → basic-At2DeO6e.js} +1 -1
  45. package/lib/{basic-BJyZdZ9-.js → basic-Bag02rxR.js} +1 -1
  46. package/lib/{basic-BYApoDKu.mjs → basic-CZS3r-7y.mjs} +2 -2
  47. package/lib/{basic-DFA9dkML.mjs → basic-mhTL58sP.mjs} +2 -2
  48. package/lib/{browser-CCRCeieU.js → browser-BOdwTvLM.js} +1 -1
  49. package/lib/{browser-BCF5N3KG.mjs → browser-CQoATCsU.mjs} +1 -1
  50. package/lib/{browser-CvrEVIwv.js → browser-DC17lLQo.js} +1 -1
  51. package/lib/{browser-BloW4u4E.mjs → browser-Dhq2eg1F.mjs} +1 -1
  52. package/lib/{card-CglIhKSq.js → card-B1jkqvQw.js} +1 -1
  53. package/lib/{card-7rHQoEDL.mjs → card-Bnhxo8qg.mjs} +1 -1
  54. package/lib/{card-fE2IIT1i.js → card-CyD4w17N.js} +1 -1
  55. package/lib/{card-Ctp3kX-1.mjs → card-QUPRN71N.mjs} +1 -1
  56. package/lib/{checkmark-Xh1LmaXe.js → checkmark-CMV_m5HB.js} +1 -1
  57. package/lib/{checkmark-CLHlN5To.mjs → checkmark-Ck1oHQed.mjs} +1 -1
  58. package/lib/{checkmark-BW1_81nx.mjs → checkmark-DpHJ69gx.mjs} +1 -1
  59. package/lib/{checkmark-BOxmV8Mo.js → checkmark-PcRLVwM7.js} +1 -1
  60. package/lib/{checkmark-bold-DhAt_JOH.mjs → checkmark-bold-B5gYm08I.mjs} +1 -1
  61. package/lib/{checkmark-bold-CBr8ZyFy.js → checkmark-bold-CBYhZkvd.js} +1 -1
  62. package/lib/{checkmark-bold-BC0jnANx.js → checkmark-bold-CQpK4eqT.js} +1 -1
  63. package/lib/{checkmark-bold-xYDW18M6.mjs → checkmark-bold-CehhvElT.mjs} +1 -1
  64. package/lib/{chevron-bottom-Didolf5t.js → chevron-bottom-CLOFEFwk.js} +1 -1
  65. package/lib/{chevron-bottom-y5gkyNtV.js → chevron-bottom-cCJ79L3b.js} +1 -1
  66. package/lib/{chevron-bottom-Daxbr3Rx.mjs → chevron-bottom-kzZqZ7cD.mjs} +1 -1
  67. package/lib/{chevron-bottom-C-ilw2I8.mjs → chevron-bottom-zSmwaICv.mjs} +1 -1
  68. package/lib/{chevron-left-DqSA6E9z.mjs → chevron-left-BJoHbC-q.mjs} +1 -1
  69. package/lib/{chevron-left-BNIGAhWk.mjs → chevron-left-CetDiLJ5.mjs} +1 -1
  70. package/lib/{chevron-left-D6J8hdRo.js → chevron-left-D1eQItCZ.js} +1 -1
  71. package/lib/{chevron-left-Bj3XIxUw.js → chevron-left-DtwepZEO.js} +1 -1
  72. package/lib/{chevron-right-DeT5P2q2.mjs → chevron-right-BElFJP8x.mjs} +1 -1
  73. package/lib/{chevron-right-BXl56y5C.js → chevron-right-BK72iuUp.js} +1 -1
  74. package/lib/{chevron-right-k8adpOIy.mjs → chevron-right-BPKqB4CI.mjs} +1 -1
  75. package/lib/{chevron-right-IBo1CiY2.js → chevron-right-C4M4ehTo.js} +1 -1
  76. package/lib/{chevron-top-B1HrfXOo.js → chevron-top-BsUpwWoO.js} +1 -1
  77. package/lib/{chevron-top-C34CbI0W.mjs → chevron-top-DrplS-a-.mjs} +1 -1
  78. package/lib/{chevron-top-CNrQ2igu.mjs → chevron-top-HSamTfwf.mjs} +1 -1
  79. package/lib/{chevron-top-C-1fCeSU.js → chevron-top-lx2Zjd8U.js} +1 -1
  80. package/lib/{chrome-store-DIzR2Dq1.mjs → chrome-store-72u2IREP.mjs} +1 -1
  81. package/lib/{chrome-store-DFTjCxuH.js → chrome-store-CKlW00NE.js} +1 -1
  82. package/lib/{chrome-store-DOoQVREZ.mjs → chrome-store-D5vKSXEJ.mjs} +1 -1
  83. package/lib/{chrome-store-DtvL-QKw.js → chrome-store-DEjNj4C1.js} +1 -1
  84. package/lib/{clock-sTn1dfri.mjs → clock-BJnEmJF_.mjs} +1 -1
  85. package/lib/{clock-C-Q57pEM.js → clock-CegkCEjG.js} +1 -1
  86. package/lib/{clock-Cv1fuvau.mjs → clock-D8tmafKX.mjs} +1 -1
  87. package/lib/{clock-C4xod9nJ.js → clock-c-XKF-YF.js} +1 -1
  88. package/lib/{close-B1b7Ptej.js → close-B1DNieDl.js} +1 -1
  89. package/lib/{close-CqPEBQBo.mjs → close-BLaMCEER.mjs} +1 -1
  90. package/lib/{close-Dfc_8zBq.js → close-BXqDsx2V.js} +1 -1
  91. package/lib/{close-B0uyRg3N.mjs → close-KbDW0r_h.mjs} +1 -1
  92. package/lib/{coinPlaceholder-nKeNJJKK.mjs → coinPlaceholder-BT1Y-3-M.mjs} +1 -1
  93. package/lib/{coinPlaceholder-DiW2_ozZ.js → coinPlaceholder-D8bKyc3B.js} +1 -1
  94. package/lib/{coinPlaceholder-DudKKK-9.js → coinPlaceholder-DXry0FTZ.js} +1 -1
  95. package/lib/{coinPlaceholder-BoiiMs6L.mjs → coinPlaceholder-Khb7TWos.mjs} +1 -1
  96. package/lib/{compass-B0X-vi2r.mjs → compass-B-B5LrsP.mjs} +1 -1
  97. package/lib/{compass-DwHx2eWH.js → compass-BlTWcnQW.js} +1 -1
  98. package/lib/{compass-BZP8Ac-k.js → compass-JmtJwxxN.js} +1 -1
  99. package/lib/{compass-gJFmkVKU.mjs → compass-U-g2nxny.mjs} +1 -1
  100. package/lib/constants-0NS634P7.js +1 -0
  101. package/lib/{constants-CvYlmQON.mjs → constants-mdk7Ai0-.mjs} +3 -3
  102. package/lib/{copy-CCtC0O9D.mjs → copy-BvSO3cWO.mjs} +1 -1
  103. package/lib/{copy-DO-PtwSL.js → copy-DUVgOnZ0.js} +1 -1
  104. package/lib/{copy-BnBqHWHD.js → copy-Db1iZINZ.js} +1 -1
  105. package/lib/{copy-DAbUkldO.mjs → copy-EenPqnRM.mjs} +1 -1
  106. package/lib/{core-B-drR9_7.js → core-B8BH62nw.js} +3 -3
  107. package/lib/{core-B_r-qOmo.mjs → core-CebHe-Zk.mjs} +4 -4
  108. package/lib/{cursor-BBkU3FcH.js → cursor-C1vKbs6D.js} +1 -1
  109. package/lib/{cursor-BxL72yqS.mjs → cursor-CpavELPr.mjs} +1 -1
  110. package/lib/{cursor-DYH9xEcp.mjs → cursor-Y_J2NVyX.mjs} +1 -1
  111. package/lib/{cursor-transparent-CtFV2CXJ.mjs → cursor-transparent-BmduW9te.mjs} +1 -1
  112. package/lib/{cursor-transparent-56UaQ3Bn.js → cursor-transparent-D-zs9Ci-.js} +1 -1
  113. package/lib/{cursor-transparent-BdZnO_wt.mjs → cursor-transparent-DB4tN9bG.mjs} +1 -1
  114. package/lib/{cursor-transparent-BEJAwX5N.js → cursor-transparent-DLISjDWq.js} +1 -1
  115. package/lib/{cursor-BBzWvQHe.js → cursor-ubFxdRQ2.js} +1 -1
  116. package/lib/{desktop-Pyfuvetn.js → desktop-C5un7nSf.js} +1 -1
  117. package/lib/{desktop-3yOLdhPI.mjs → desktop-CCnIAsli.mjs} +1 -1
  118. package/lib/{desktop-2v6QoLZE.mjs → desktop-Xt7PaZC0.mjs} +1 -1
  119. package/lib/{desktop-3NUUpk4c.js → desktop-aNSoY7vR.js} +1 -1
  120. package/lib/{disconnect-cHTRr7Ec.mjs → disconnect-C8GkaVa4.mjs} +1 -1
  121. package/lib/{disconnect-BaX_JURb.js → disconnect-CfkBFFvh.js} +1 -1
  122. package/lib/{disconnect-BfTUZAHR.js → disconnect-DMgKQybs.js} +1 -1
  123. package/lib/{disconnect-Bv_Bim13.mjs → disconnect-YLOHKTM7.mjs} +1 -1
  124. package/lib/{discord-CSIF6CGN.js → discord-BN-USOhL.js} +1 -1
  125. package/lib/{discord-D1ikT3b-.js → discord-CvxC97sE.js} +1 -1
  126. package/lib/{discord-CKjUttdg.mjs → discord-D1oPOGJI.mjs} +1 -1
  127. package/lib/{discord-C2VL_GWD.mjs → discord-O_jJHDL7.mjs} +1 -1
  128. package/lib/{etherscan-DgfkHroL.js → etherscan-3zg6RVUm.js} +1 -1
  129. package/lib/{etherscan-BsljyTKF.mjs → etherscan-Bss5SYdE.mjs} +1 -1
  130. package/lib/{etherscan-DNbmb9VE.mjs → etherscan-D-4oyw9M.mjs} +1 -1
  131. package/lib/{etherscan-C4o1jcxp.js → etherscan-D-Im_svB.js} +1 -1
  132. package/lib/{evm-BVhY4VIn.js → evm-B1r0-d85.js} +2 -2
  133. package/lib/{evm-D6avkBIT.mjs → evm-B9Foo-Fc.mjs} +3 -3
  134. package/lib/{evm-C9PlJk_E.mjs → evm-D6v_yOIF.mjs} +3 -3
  135. package/lib/{evm-DsYQcqsM.js → evm-DviFlx-R.js} +1 -1
  136. package/lib/{exclamation-triangle-BYOLGjLp.js → exclamation-triangle-B_5amtlW.js} +1 -1
  137. package/lib/{exclamation-triangle-7sXeuvtw.mjs → exclamation-triangle-DOzBPDHq.mjs} +1 -1
  138. package/lib/{exclamation-triangle-C9ULgQJ_.js → exclamation-triangle-DtvIimzC.js} +1 -1
  139. package/lib/{exclamation-triangle-B5VkBuje.mjs → exclamation-triangle-DyLghy3P.mjs} +1 -1
  140. package/lib/{extension-NsgFQY7m.js → extension-C2ZOdhvk.js} +1 -1
  141. package/lib/{extension-VaBFk192.js → extension-ChidYt_2.js} +1 -1
  142. package/lib/{extension-MYgCtDFH.mjs → extension-ClxdT5sv.mjs} +1 -1
  143. package/lib/{extension-DQxWqGMB.mjs → extension-XP0Cxc3a.mjs} +1 -1
  144. package/lib/{external-link-Cd0vLGIE.mjs → external-link-9KNXLmMz.mjs} +1 -1
  145. package/lib/{external-link-BJpDXZJf.mjs → external-link-BHvdXmV0.mjs} +1 -1
  146. package/lib/{external-link-Dixa5654.js → external-link-DFtIt6g1.js} +1 -1
  147. package/lib/{external-link-B_MqtCKD.js → external-link-Dts-4Sk6.js} +1 -1
  148. package/lib/{facebook-BKr0sc8j.mjs → facebook-BZ86PCoF.mjs} +1 -1
  149. package/lib/{facebook-COEHDC_C.js → facebook-BhtZqeWN.js} +1 -1
  150. package/lib/{facebook-CW9qBsFQ.mjs → facebook-D1ClEy04.mjs} +1 -1
  151. package/lib/{facebook-B5uxGSPx.js → facebook-Dn_bhYL7.js} +1 -1
  152. package/lib/{farcaster-Ds4f9Ltv.mjs → farcaster-BE4Jp2jQ.mjs} +1 -1
  153. package/lib/{farcaster-CKtNojdp.js → farcaster-BTbmAgvi.js} +1 -1
  154. package/lib/{farcaster-YHCXqrrj.mjs → farcaster-D5wA55pg.mjs} +1 -1
  155. package/lib/{farcaster-m5MVs-aT.js → farcaster-cOdQDShS.js} +1 -1
  156. package/lib/{filters-CNHTPTvF.js → filters-9M72BaSe.js} +1 -1
  157. package/lib/{filters-otxJEOs7.mjs → filters-CevFjA1u.mjs} +1 -1
  158. package/lib/{filters-C_fotjQ9.mjs → filters-DBWBF_sX.mjs} +1 -1
  159. package/lib/{filters-CDHyMrNp.js → filters-DU-C_SVc.js} +1 -1
  160. package/lib/{github-CKZKwTIP.js → github-BXvu9xPz.js} +1 -1
  161. package/lib/{github-Dibydlav.mjs → github-BbpuqjN2.mjs} +1 -1
  162. package/lib/{github-CEJ7ZdVF.js → github-CUgzRfE2.js} +1 -1
  163. package/lib/{github-BNYDlQMz.mjs → github-DrYHJIJe.mjs} +1 -1
  164. package/lib/{google-Dx6T3HNH.mjs → google-C0OkaUs7.mjs} +1 -1
  165. package/lib/{google-BA66k4rL.mjs → google-huTnWdlg.mjs} +1 -1
  166. package/lib/{google-B21849VG.js → google-n_csvYgo.js} +1 -1
  167. package/lib/{google-y2naTeYr.js → google-sRPd04eZ.js} +1 -1
  168. package/lib/{help-circle-cbP1i7bz.js → help-circle-Bn8Y_0jP.js} +1 -1
  169. package/lib/{help-circle-CPvN7YEE.js → help-circle-DD1uNYG1.js} +1 -1
  170. package/lib/{help-circle-CimYq20b.mjs → help-circle-DHfEXweO.mjs} +1 -1
  171. package/lib/{help-circle-B2i3-wGO.mjs → help-circle-NWXXQDwT.mjs} +1 -1
  172. package/lib/hosted.js +1 -1
  173. package/lib/hosted.mjs +1 -1
  174. package/lib/{hypercore-DXRD8m3E.mjs → hypercore-B9UmlJWh.mjs} +9 -9
  175. package/lib/{hypercore-CHTw8bic.js → hypercore-DWVgITsg.js} +1 -1
  176. package/lib/{id-CPeIs5Fq.js → id-Cs-jcmzE.js} +1 -1
  177. package/lib/{id-DiVzvOfZ.mjs → id-CxLQ5PPh.mjs} +1 -1
  178. package/lib/{id-B4jo17C5.mjs → id-DQA-GcPk.mjs} +1 -1
  179. package/lib/{id-DSFow20F.js → id-Dh2EW9hF.js} +1 -1
  180. package/lib/{image-B6EzmhFU.js → image-C28LaM6Q.js} +1 -1
  181. package/lib/{image-BVF33tR1.mjs → image-H6yEsFi5.mjs} +1 -1
  182. package/lib/{image-BhAe9DNs.js → image-JeKn_hvH.js} +1 -1
  183. package/lib/{image-apDrsEYS.mjs → image-wLpPfXgm.mjs} +1 -1
  184. package/lib/{index-CuufMtD7.mjs → index-BHURLsGo.mjs} +1 -1
  185. package/lib/{index-Kh39Gi5k.js → index-Bircjm-u.js} +1 -1
  186. package/lib/{index-BBSVPcAD.js → index-BjTalDhN.js} +1 -1
  187. package/lib/{index-EOQIdj8y.mjs → index-CDRfkHVR.mjs} +78 -78
  188. package/lib/{index-FgK-pdrK.mjs → index-CGaLT_H7.mjs} +78 -78
  189. package/lib/{index-xvDlUtry.mjs → index-CYflVh0l.mjs} +1 -1
  190. package/lib/{index-BHwMXTV2.js → index-C_Sdh7IS.js} +2 -2
  191. package/lib/{index-CV_PfShb.mjs → index-Cpg9jRCx.mjs} +1 -1
  192. package/lib/{index-BGzNVaPV.js → index-Cv7Y2G3w.js} +2 -2
  193. package/lib/{index-CltqjT6y.js → index-DKsmI0k_.js} +1 -1
  194. package/lib/{index-n-le376F.js → index-Db6-b_fu.js} +2 -2
  195. package/lib/{index-pg8PO4KF.js → index-DtIfurr3.js} +1 -1
  196. package/lib/{index-CGmXt9G7.mjs → index-kPwB0sVz.mjs} +1 -1
  197. package/lib/{index-CYFUlQL7.mjs → index-tBNddJw6.mjs} +3 -3
  198. package/lib/{index.es-lG9bYbuU.js → index.es-CCdg9Kcb.js} +3 -3
  199. package/lib/{index.es-B1Hb17ux.js → index.es-D5cfl75E.js} +1 -1
  200. package/lib/{index.es-OUX5OQzg.mjs → index.es-DL7qNQxZ.mjs} +2 -2
  201. package/lib/{index.es-D9dqjxA-.mjs → index.es-NIH5Fjyc.mjs} +3 -3
  202. package/lib/index.js +387 -47
  203. package/lib/index.mjs +45924 -22287
  204. package/lib/{info-lLJkbrKO.js → info-3tKvMSGK.js} +1 -1
  205. package/lib/{info-O1n15_1D.mjs → info-D1P1BYvd.mjs} +1 -1
  206. package/lib/{info-Boiui9f7.js → info-DZ8mFZ5I.js} +1 -1
  207. package/lib/{info-circle-CMe56iw6.js → info-circle-BWTGwB05.js} +1 -1
  208. package/lib/{info-circle-BFolIbkj.mjs → info-circle-CBoblsmh.mjs} +1 -1
  209. package/lib/{info-circle-CUSrqyXO.mjs → info-circle-D2Tm0COC.mjs} +1 -1
  210. package/lib/{info-circle-Cc7pM3j0.js → info-circle-DWpUIxPL.js} +1 -1
  211. package/lib/{info-C9gVJcre.mjs → info-vy3IpaAd.mjs} +1 -1
  212. package/lib/lifi.js +1 -1
  213. package/lib/lifi.mjs +2 -2
  214. package/lib/{lightbulb-ftjHXSjH.js → lightbulb-BOEWy2Rz.js} +1 -1
  215. package/lib/{lightbulb-VYLU20z_.js → lightbulb-DZHQdxc7.js} +1 -1
  216. package/lib/{lightbulb-C3PATB9z.mjs → lightbulb-Dk9UCkA8.mjs} +1 -1
  217. package/lib/{lightbulb-CqdzQLC3.mjs → lightbulb-n7B2hmGB.mjs} +1 -1
  218. package/lib/{mail-DK7EnkPU.js → mail-CVJU8oQm.js} +1 -1
  219. package/lib/{mail-Cbku7Uh4.mjs → mail-D1TMsRtq.mjs} +1 -1
  220. package/lib/{mail-DFrUqNVg.js → mail-ghlLDYMn.js} +1 -1
  221. package/lib/{mail-pAAtront.mjs → mail-vpaKmnyj.mjs} +1 -1
  222. package/lib/mayan.js +1 -1
  223. package/lib/mayan.mjs +2 -2
  224. package/lib/{mobile-BhxSbHuq.js → mobile-CIjo1PIt.js} +1 -1
  225. package/lib/{mobile-VGlrj4tw.mjs → mobile-Nl5-39QD.mjs} +1 -1
  226. package/lib/{mobile-DssA8Pv3.js → mobile-OJfwf5iq.js} +1 -1
  227. package/lib/{mobile-OA7to7W8.mjs → mobile-XD26WLUC.mjs} +1 -1
  228. package/lib/{more-B2vO9WWk.js → more-BgXKD3yk.js} +1 -1
  229. package/lib/{more-BN4Q6SUx.mjs → more-BhUbEmgG.mjs} +1 -1
  230. package/lib/{more-DHFKZx0b.js → more-BwBE0n-c.js} +1 -1
  231. package/lib/{more-Ch4Lqfvk.mjs → more-Dif8cdfi.mjs} +1 -1
  232. package/lib/{network-placeholder-C9vBCfoS.js → network-placeholder-BQRWPjks.js} +1 -1
  233. package/lib/{network-placeholder-DEjE8_cC.js → network-placeholder-BbuoxtHw.js} +1 -1
  234. package/lib/{network-placeholder-DabWxIRQ.mjs → network-placeholder-Bhrzds35.mjs} +1 -1
  235. package/lib/{network-placeholder-BB4x45Tg.mjs → network-placeholder-C2aJv5DP.mjs} +1 -1
  236. package/lib/{nftPlaceholder-HRZgFSge.mjs → nftPlaceholder-BDBtmgsF.mjs} +1 -1
  237. package/lib/{nftPlaceholder-Dm0gJJff.js → nftPlaceholder-BmyG2OA3.js} +1 -1
  238. package/lib/{nftPlaceholder-DkQ8_eeY.mjs → nftPlaceholder-D3L3lYNG.mjs} +1 -1
  239. package/lib/{nftPlaceholder-C3mbGCd_.js → nftPlaceholder-UwX_upXy.js} +1 -1
  240. package/lib/{off-nA_OrJUe.mjs → off-BY4DlvOg.mjs} +1 -1
  241. package/lib/{off--Q32bGkI.js → off-CcLMdVvT.js} +1 -1
  242. package/lib/{off-wbTBMRhe.mjs → off-DC1r69jz.mjs} +1 -1
  243. package/lib/{off-CrU10ihl.js → off-DgHo3MD-.js} +1 -1
  244. package/lib/{play-store-BHw33DCQ.js → play-store-0OC2D6-S.js} +1 -1
  245. package/lib/{play-store-CS0C9q5-.js → play-store-BJ1EzGT-.js} +1 -1
  246. package/lib/{play-store-BVmr7Z4C.mjs → play-store-Ddp0iLCA.mjs} +1 -1
  247. package/lib/{play-store-D9U-UFF5.mjs → play-store-rS2tQFht.mjs} +1 -1
  248. package/lib/{plus-Bi6V8pNp.js → plus-BbFv3eUM.js} +1 -1
  249. package/lib/{plus-D3x4t8Ce.mjs → plus-Bdj0NxMO.mjs} +1 -1
  250. package/lib/{plus-Dc8ywSwP.js → plus-BiqsWZTU.js} +1 -1
  251. package/lib/{plus-CW3w3sls.mjs → plus-l8xvIUjr.mjs} +1 -1
  252. package/lib/{qr-code-DgC6Fdg7.mjs → qr-code-CrlCde0x.mjs} +1 -1
  253. package/lib/{qr-code-ji9rZFGq.js → qr-code-CwVMQOBz.js} +1 -1
  254. package/lib/{qr-code-OMVNklZX.mjs → qr-code-DwQDvjbs.mjs} +1 -1
  255. package/lib/{qr-code-BZDngjZY.js → qr-code-lOm2J3lG.js} +1 -1
  256. package/lib/{recycle-horizontal-DytoyBfI.mjs → recycle-horizontal-BLDEBDKQ.mjs} +1 -1
  257. package/lib/{recycle-horizontal-B2I-zPCU.mjs → recycle-horizontal-DOXJkLkE.mjs} +1 -1
  258. package/lib/{recycle-horizontal-D9hq32DZ.js → recycle-horizontal-D_KYiXB2.js} +1 -1
  259. package/lib/{recycle-horizontal-Bt5GY9OR.js → recycle-horizontal-vcfEBLHF.js} +1 -1
  260. package/lib/{refresh-H6w6oM_A.js → refresh-BSOKVuqM.js} +1 -1
  261. package/lib/{refresh-BSAssZBM.mjs → refresh-BXxBUdnO.mjs} +1 -1
  262. package/lib/{refresh-CjLexDSA.mjs → refresh-D2E75sGo.mjs} +1 -1
  263. package/lib/{refresh-BKK5da-L.js → refresh-DyTPW1lm.js} +1 -1
  264. package/lib/{reown-logo-C6FOwVYq.mjs → reown-logo-BasQMgg6.mjs} +1 -1
  265. package/lib/{reown-logo-DwXu5uNR.mjs → reown-logo-Ca0n-4co.mjs} +1 -1
  266. package/lib/{reown-logo-B6Ov41nY.js → reown-logo-I-0VXJcs.js} +1 -1
  267. package/lib/{reown-logo-DLSNj3TE.js → reown-logo-zFtk69x0.js} +1 -1
  268. package/lib/{search-Co9ezsvt.mjs → search-C8Dr302a.mjs} +1 -1
  269. package/lib/{search-BOcgdRAL.mjs → search-Cs5OMH24.mjs} +1 -1
  270. package/lib/{search-CAbVUgnN.js → search-D4N5PCXY.js} +1 -1
  271. package/lib/{search-Bb7bK2Uc.js → search-DKkge_rX.js} +1 -1
  272. package/lib/{secp256k1-C4MOK2TW.mjs → secp256k1-BApZtlJM.mjs} +1 -1
  273. package/lib/{secp256k1-jJLvhP5o.js → secp256k1-BvEkCzAq.js} +1 -1
  274. package/lib/{secp256k1-BnR7-XEW.js → secp256k1-BxlHgrPu.js} +1 -1
  275. package/lib/{secp256k1-DT9ulpgk.js → secp256k1-Cob6dKlh.js} +1 -1
  276. package/lib/{secp256k1-BoJRjFfg.mjs → secp256k1-D6LTGgSG.mjs} +1 -1
  277. package/lib/{secp256k1-0A8Ewnv6.mjs → secp256k1-DMo8iyn0.mjs} +1 -1
  278. package/lib/{secp256k1-YadE7hrp.mjs → secp256k1-Szby676i.mjs} +1 -1
  279. package/lib/{secp256k1-Cux0xw_z.js → secp256k1-e1mb-DFW.js} +1 -1
  280. package/lib/{send-CRsiv27V.js → send-CWr-_fO9.js} +1 -1
  281. package/lib/{send-BpJl2Xn8.mjs → send-CvrTc0pM.mjs} +1 -1
  282. package/lib/{send-DLjvhVAl.mjs → send-DTWzuOtI.mjs} +1 -1
  283. package/lib/{send-B44wmSUh.js → send-f0aDSW2z.js} +1 -1
  284. package/lib/{solana-CiNUMNJ8.mjs → solana-Bu1QCXxV.mjs} +8 -8
  285. package/lib/{solana-BGU37dz5.js → solana-DBtle7NE.js} +4 -4
  286. package/lib/{solanaEmbed.esm-CQlwytxQ.js → solanaEmbed.esm-2zbmc9eY.js} +1 -1
  287. package/lib/{solanaEmbed.esm-DyqmLXfp.mjs → solanaEmbed.esm-Ekp0oGzh.mjs} +2 -2
  288. package/lib/{sui-BjzF-Q-b.js → sui-Dai0MBus.js} +1 -1
  289. package/lib/{sui-Bib-iOCV.mjs → sui-ybNGBjmb.mjs} +2 -2
  290. package/lib/{swapHorizontal-D-uqFVHs.js → swapHorizontal-BiYn3yW8.js} +1 -1
  291. package/lib/{swapHorizontal-BsTJkttx.js → swapHorizontal-CzdzeOB3.js} +1 -1
  292. package/lib/{swapHorizontal-BRWRUIJB.mjs → swapHorizontal-WwJR0_Dj.mjs} +1 -1
  293. package/lib/{swapHorizontal-B8qVmnu8.mjs → swapHorizontal-vKLfqFpk.mjs} +1 -1
  294. package/lib/{swapHorizontalBold-BdNeqRi3.mjs → swapHorizontalBold-2i6pbDOS.mjs} +1 -1
  295. package/lib/{swapHorizontalBold-aLja8kkS.js → swapHorizontalBold-DaCZ8LV2.js} +1 -1
  296. package/lib/{swapHorizontalBold-nE-ChWuU.mjs → swapHorizontalBold-DfD-NVuF.mjs} +1 -1
  297. package/lib/{swapHorizontalBold-CYYFuggs.js → swapHorizontalBold-DwoIuf9J.js} +1 -1
  298. package/lib/{swapHorizontalMedium-vhOD9TfP.js → swapHorizontalMedium-7lGQEzS_.js} +1 -1
  299. package/lib/{swapHorizontalMedium-C6W9-JzO.mjs → swapHorizontalMedium-B6bvh8T3.mjs} +1 -1
  300. package/lib/{swapHorizontalMedium-BeZ1rL5X.js → swapHorizontalMedium-BITalXpE.js} +1 -1
  301. package/lib/{swapHorizontalMedium-BI3ILASr.mjs → swapHorizontalMedium-DKlsnxq3.mjs} +1 -1
  302. package/lib/{swapHorizontalRoundedBold-BkFwOs0Y.js → swapHorizontalRoundedBold-DFUk0LD-.js} +1 -1
  303. package/lib/{swapHorizontalRoundedBold-CYpeP0Et.mjs → swapHorizontalRoundedBold-DMN64jKj.mjs} +1 -1
  304. package/lib/{swapHorizontalRoundedBold-DP1Z5JQM.js → swapHorizontalRoundedBold-Dh7YccsV.js} +1 -1
  305. package/lib/{swapHorizontalRoundedBold-BAIOqirj.mjs → swapHorizontalRoundedBold-X09CF7C1.mjs} +1 -1
  306. package/lib/{swapVertical-Ci9CWSzV.mjs → swapVertical-DFfJ4ib5.mjs} +1 -1
  307. package/lib/{swapVertical-29kKOB66.js → swapVertical-DTpt3txk.js} +1 -1
  308. package/lib/{swapVertical-3zrfl1Xi.mjs → swapVertical-DYWBLAIn.mjs} +1 -1
  309. package/lib/{swapVertical-CFtauJeV.js → swapVertical-j_z5zwC9.js} +1 -1
  310. package/lib/{telegram-Dr2j2upn.js → telegram-C-Fp394u.js} +1 -1
  311. package/lib/{telegram-DrrslbwQ.mjs → telegram-CjnGu7GA.mjs} +1 -1
  312. package/lib/{telegram-CvywROv3.mjs → telegram-SL_ehdQ1.mjs} +1 -1
  313. package/lib/{telegram-Dwr-qPTP.js → telegram-jAlzfvmm.js} +1 -1
  314. package/lib/{three-dots-CcmyKQwf.mjs → three-dots-A97eKq-t.mjs} +1 -1
  315. package/lib/{three-dots-CS6LN5K6.mjs → three-dots-CqqJjHxY.mjs} +1 -1
  316. package/lib/{three-dots-Ls5fYKC0.js → three-dots-DBwclFqo.js} +1 -1
  317. package/lib/{three-dots-BNuSEqpQ.js → three-dots-DX75nC3P.js} +1 -1
  318. package/lib/{tokenHelpers-DAwzvT17.mjs → tokenHelpers-C4pLIPnz.mjs} +1 -1
  319. package/lib/{tokenHelpers-BWM8KMa6.js → tokenHelpers-CMFBs8po.js} +1 -1
  320. package/lib/{tokens-D1ONPHia.js → tokens-DKt-90PV.js} +1 -1
  321. package/lib/{tokens-DggD3cX7.mjs → tokens-r-3L-zm5.mjs} +1 -1
  322. package/lib/{twitch-Bd58rlGF.js → twitch-BPtSPWwi.js} +1 -1
  323. package/lib/{twitch-C8SyvzoN.mjs → twitch-BjnldiJg.mjs} +1 -1
  324. package/lib/{twitch-BnpIZdrn.js → twitch-CnX1zLyh.js} +1 -1
  325. package/lib/{twitch-C4Eo2_CN.mjs → twitch-UUmNfBhR.mjs} +1 -1
  326. package/lib/{twitterIcon-C-y4j0Tc.mjs → twitterIcon-Bug3Ov3V.mjs} +1 -1
  327. package/lib/{twitterIcon-BMzY5zmt.mjs → twitterIcon-CORzXqes.mjs} +1 -1
  328. package/lib/{twitterIcon-DIykPyaS.js → twitterIcon-CuzAcNnN.js} +1 -1
  329. package/lib/{twitterIcon-BEbzFMeP.js → twitterIcon-DPZQ1g4F.js} +1 -1
  330. package/lib/{verify-Crtvz15I.js → verify-BcHypLx-.js} +1 -1
  331. package/lib/{verify-NthP_npu.mjs → verify-BzcXHXHH.mjs} +1 -1
  332. package/lib/{verify-CrMRxyWg.mjs → verify-CGTYC5Gb.mjs} +1 -1
  333. package/lib/{verify-CwFpdYoH.js → verify-DF_R0wi3.js} +1 -1
  334. package/lib/{verify-filled-BlrU9vQA.js → verify-filled-BIxOwlrY.js} +1 -1
  335. package/lib/{verify-filled-D9kdEJV2.mjs → verify-filled-BdtikQ9V.mjs} +1 -1
  336. package/lib/{verify-filled-CGCh-dVk.js → verify-filled-Bpb0HYP3.js} +1 -1
  337. package/lib/{verify-filled-CjDyTxlc.mjs → verify-filled-woSjwI7B.mjs} +1 -1
  338. package/lib/{w3m-modal-CdkJJVqN.mjs → w3m-modal-1TEj0hI8.mjs} +2 -2
  339. package/lib/{w3m-modal--0Rp9fNB.js → w3m-modal-CQc0dHrk.js} +1 -1
  340. package/lib/{w3m-modal-1XXe-6js.js → w3m-modal-DskVGuLl.js} +1 -1
  341. package/lib/{w3m-modal-DM4Y_2h6.mjs → w3m-modal-Xo0_Tr7j.mjs} +2 -2
  342. package/lib/{wallet-CkpI9kzj.js → wallet-BGd3SuA7.js} +1 -1
  343. package/lib/{wallet-CamNgIPw.mjs → wallet-ClQpKYZP.mjs} +1 -1
  344. package/lib/{wallet-Cq98Nsz0.mjs → wallet-DGfBrlb3.mjs} +1 -1
  345. package/lib/{wallet-C1IpUTIA.js → wallet-E8LGI5Yo.js} +1 -1
  346. package/lib/{wallet-placeholder-Dqi7ETT0.js → wallet-placeholder-BYbEXUsl.js} +1 -1
  347. package/lib/{wallet-placeholder-BNjSzhI7.mjs → wallet-placeholder-BwiUHiNG.mjs} +1 -1
  348. package/lib/{wallet-placeholder-CB7fUzRo.js → wallet-placeholder-DS2lYgtI.js} +1 -1
  349. package/lib/{wallet-placeholder-DA1MWd3N.mjs → wallet-placeholder-eA_d6nk7.mjs} +1 -1
  350. package/lib/{walletconnect-Bn6uzute.js → walletconnect-BV7N-T1F.js} +1 -1
  351. package/lib/{walletconnect-nqXULWld.js → walletconnect-BpbAq3o_.js} +1 -1
  352. package/lib/{walletconnect-BNEO7K5p.mjs → walletconnect-Ca3Q0Xhv.mjs} +1 -1
  353. package/lib/{walletconnect-CZpyRToX.mjs → walletconnect-CupXpY7C.mjs} +1 -1
  354. package/lib/{warning-circle-CaIyIC07.mjs → warning-circle-8ClY5fmd.mjs} +1 -1
  355. package/lib/{warning-circle--gP3MuWN.js → warning-circle-C41Ocsy3.js} +1 -1
  356. package/lib/{warning-circle-bxxlNMW0.js → warning-circle-Dx395109.js} +1 -1
  357. package/lib/{warning-circle-BJa5UE7S.mjs → warning-circle-jzOn90Sg.mjs} +1 -1
  358. package/lib/{x-CNpeVFtn.js → x-BvVb63M2.js} +1 -1
  359. package/lib/{x-CpgiFnfX.mjs → x-CbB6unwR.mjs} +1 -1
  360. package/lib/{x-aiX6h0m_.mjs → x-CigOCsqT.mjs} +1 -1
  361. package/lib/{x-CK85Brc3.js → x-fQKPMjaI.js} +1 -1
  362. package/package.json +9 -9
  363. package/lib/constants-CZ1Cg3we.js +0 -1
@@ -1,5 +1,5 @@
1
- "use strict";const v=require("./index.es-B1Hb17ux.js"),z=require("./platform-DH1Olrgt.js");function xd(i){if(i.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<i.length;h++){const l=i.charAt(h),u=l.charCodeAt(0);if(e[u]!==255)throw new TypeError(l+" is ambiguous");e[u]=h}const t=i.length,s=i.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let l=0,u=0,p=0;const g=h.length;for(;p!==g&&h[p]===0;)p++,l++;const w=(g-p)*n+1>>>0,y=new Uint8Array(w);for(;p!==g;){let f=h[p],E=0;for(let _=w-1;(f!==0||E<u)&&_!==-1;_--,E++)f+=256*y[_]>>>0,y[_]=f%t>>>0,f=f/t>>>0;if(f!==0)throw new Error("Non-zero carry");u=E,p++}let d=w-u;for(;d!==w&&y[d]===0;)d++;let m=s.repeat(l);for(;d<w;++d)m+=i.charAt(y[d]);return m}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,u=0,p=0;for(;h[l]===s;)u++,l++;const g=(h.length-l)*r+1>>>0,w=new Uint8Array(g);for(;l<h.length;){const f=h.charCodeAt(l);if(f>255)return;let E=e[f];if(E===255)return;let _=0;for(let C=g-1;(E!==0||_<p)&&C!==-1;C--,_++)E+=t*w[C]>>>0,w[C]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");p=_,l++}let y=g-p;for(;y!==g&&w[y]===0;)y++;const d=new Uint8Array(u+(g-y));let m=u;for(;y!==g;)d[m++]=w[y++];return d}function c(h){const l=a(h);if(l)return l;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Pd="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";xd(Pd);const _d=":";function Zh(i){const[e,t]=i.split(_d);return{namespace:e,reference:t}}function ga(i,e=[]){const t=[];return Object.keys(i).forEach(s=>{if(e.length&&!e.includes(s))return;const r=i[s];t.push(...r.accounts)}),t}function rn(i=[],e=[]){return[...new Set([...i,...e])]}function _r(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Od(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ks(i,...e){if(!Od(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Ad(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");_r(i.outputLen),_r(i.blockLen)}function zi(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Jh(i,e){Ks(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const rr=BigInt(2**32-1),ya=BigInt(32);function Rd(i,e=!1){return e?{h:Number(i&rr),l:Number(i>>ya&rr)}:{h:Number(i>>ya&rr)|0,l:Number(i&rr)|0}}function Nd(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=Rd(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Td=(i,e,t)=>i<<t|e>>>32-t,Cd=(i,e,t)=>e<<t|i>>>32-t,Bd=(i,e,t)=>e<<t-32|i>>>64-t,Ud=(i,e,t)=>i<<t-32|e>>>64-t,pi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function jd(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function nn(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function pt(i,e){return i<<32-e|i>>>e}const wa=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function qd(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function ma(i){for(let e=0;e<i.length;e++)i[e]=qd(i[e])}function kd(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function qr(i){return typeof i=="string"&&(i=kd(i)),Ks(i),i}function Ld(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Ks(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}let Go=class{clone(){return this._cloneInto()}};function Yh(i){const e=s=>i().update(qr(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Qh(i=32){if(pi&&typeof pi.getRandomValues=="function")return pi.getRandomValues(new Uint8Array(i));if(pi&&typeof pi.randomBytes=="function")return pi.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Xh=[],el=[],tl=[],Dd=BigInt(0),ys=BigInt(1),Fd=BigInt(2),Md=BigInt(7),zd=BigInt(256),Hd=BigInt(113);for(let i=0,e=ys,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Xh.push(2*(5*s+t)),el.push((i+1)*(i+2)/2%64);let r=Dd;for(let n=0;n<7;n++)e=(e<<ys^(e>>Md)*Hd)%zd,e&Fd&&(r^=ys<<(ys<<BigInt(n))-ys);tl.push(r)}const[Vd,Kd]=Nd(tl,!0),ba=(i,e,t)=>t>32?Bd(i,e,t):Td(i,e,t),va=(i,e,t)=>t>32?Ud(i,e,t):Cd(i,e,t);function Gd(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=ba(h,l,1)^t[a],p=va(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=el[o],c=ba(r,n,a),h=va(r,n,a),l=Xh[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=Vd[s],i[1]^=Kd[s]}t.fill(0)}let Wd=class il extends Go{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,_r(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=jd(this.state)}keccak(){wa||ma(this.state32),Gd(this.state32,this.rounds),wa||ma(this.state32),this.posOut=0,this.pos=0}update(e){zi(this);const{blockLen:t,state:s}=this;e=qr(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){zi(this,!1),Ks(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 _r(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Jh(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:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new il(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Zd=(i,e,t)=>Yh(()=>new Wd(e,i,t));Zd(1,136,256/8);function on(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function sl(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ze(i,...e){if(!sl(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Ea(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Jd(i,e){Ze(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function $a(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const Ft=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),Yd=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Qd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Qd)throw new Error("Non little-endian hardware is not supported");function Xd(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function Qn(i){if(typeof i=="string")i=Xd(i);else if(sl(i))i=Xn(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function ep(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function tp(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}const ip=(i,e)=>{function t(s,...r){if(Ze(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?Ze(h):Ze(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&Ze(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");Ze(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ze(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(Ze(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(h,l)}}}return Object.assign(t,i),t};function Ia(i,e,t=!0){if(e===void 0)return new Uint8Array(i);if(e.length!==i)throw new Error("invalid output length, expected "+i+", got: "+e.length);if(t&&!sp(e))throw new Error("invalid output, must be aligned");return e}function Sa(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);i.setUint32(e+4,o,s),i.setUint32(e+0,a,s)}function sp(i){return i.byteOffset%4===0}function Xn(i){return Uint8Array.from(i)}function Hi(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const rl=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),rp=rl("expand 16-byte k"),np=rl("expand 32-byte k"),op=Ft(rp),ap=Ft(np);function Q(i,e){return i<<e|i>>>32-e}function eo(i){return i.byteOffset%4===0}const nr=64,cp=16,nl=2**32-1,xa=new Uint32Array;function hp(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(nr),l=Ft(h),u=eo(r)&&eo(n),p=u?Ft(r):xa,g=u?Ft(n):xa;for(let w=0;w<c;o++){if(i(e,t,s,l,o,a),o>=nl)throw new Error("arx: counter overflow");const y=Math.min(nr,c-w);if(u&&y===nr){const d=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let m=0,f;m<cp;m++)f=d+m,g[f]=p[f]^l[m];w+=nr;continue}for(let d=0,m;d<y;d++)m=w+d,n[m]=r[m]^h[d];w+=y}}function lp(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=ep({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return on(r),on(o),$a(n),$a(t),(a,c,h,l,u=0)=>{Ze(a),Ze(c),Ze(h);const p=h.length;if(l===void 0&&(l=new Uint8Array(p)),Ze(l),on(u),u<0||u>=nl)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const g=[];let w=a.length,y,d;if(w===32)g.push(y=Xn(a)),d=ap;else if(w===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),d=op,g.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${w}`);eo(c)||g.push(c=Xn(c));const m=Ft(y);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(d,m,Ft(c.subarray(0,16)),m),c=c.subarray(16)}const f=16-r;if(f!==c.length)throw new Error(`arx: nonce must be ${f} or 16 bytes`);if(f!==12){const _=new Uint8Array(12);_.set(c,n?0:12-c.length),c=_,g.push(c)}const E=Ft(c);return hp(i,d,m,E,h,l,u,o),Hi(...g),l}}const _e=(i,e)=>i[e++]&255|(i[e++]&255)<<8;let up=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=Qn(e),Ze(e,32);const t=_e(e,0),s=_e(e,2),r=_e(e,4),n=_e(e,6),o=_e(e,8),a=_e(e,10),c=_e(e,12),h=_e(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>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|c<<5)&8065,this.r[8]=(c>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=_e(e,16+2*l)}process(e,t,s=!1){const r=s?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],l=o[3],u=o[4],p=o[5],g=o[6],w=o[7],y=o[8],d=o[9],m=_e(e,t+0),f=_e(e,t+2),E=_e(e,t+4),_=_e(e,t+6),C=_e(e,t+8),O=_e(e,t+10),P=_e(e,t+12),R=_e(e,t+14);let S=n[0]+(m&8191),U=n[1]+((m>>>13|f<<3)&8191),N=n[2]+((f>>>10|E<<6)&8191),B=n[3]+((E>>>7|_<<9)&8191),j=n[4]+((_>>>4|C<<12)&8191),b=n[5]+(C>>>1&8191),I=n[6]+((C>>>14|O<<2)&8191),$=n[7]+((O>>>11|P<<5)&8191),A=n[8]+((P>>>8|R<<8)&8191),T=n[9]+(R>>>5|r),x=0,q=x+S*a+U*(5*d)+N*(5*y)+B*(5*w)+j*(5*g);x=q>>>13,q&=8191,q+=b*(5*p)+I*(5*u)+$*(5*l)+A*(5*h)+T*(5*c),x+=q>>>13,q&=8191;let k=x+S*c+U*a+N*(5*d)+B*(5*y)+j*(5*w);x=k>>>13,k&=8191,k+=b*(5*g)+I*(5*p)+$*(5*u)+A*(5*l)+T*(5*h),x+=k>>>13,k&=8191;let L=x+S*h+U*c+N*a+B*(5*d)+j*(5*y);x=L>>>13,L&=8191,L+=b*(5*w)+I*(5*g)+$*(5*p)+A*(5*u)+T*(5*l),x+=L>>>13,L&=8191;let M=x+S*l+U*h+N*c+B*a+j*(5*d);x=M>>>13,M&=8191,M+=b*(5*y)+I*(5*w)+$*(5*g)+A*(5*p)+T*(5*u),x+=M>>>13,M&=8191;let F=x+S*u+U*l+N*h+B*c+j*a;x=F>>>13,F&=8191,F+=b*(5*d)+I*(5*y)+$*(5*w)+A*(5*g)+T*(5*p),x+=F>>>13,F&=8191;let H=x+S*p+U*u+N*l+B*h+j*c;x=H>>>13,H&=8191,H+=b*a+I*(5*d)+$*(5*y)+A*(5*w)+T*(5*g),x+=H>>>13,H&=8191;let K=x+S*g+U*p+N*u+B*l+j*h;x=K>>>13,K&=8191,K+=b*c+I*a+$*(5*d)+A*(5*y)+T*(5*w),x+=K>>>13,K&=8191;let Z=x+S*w+U*g+N*p+B*u+j*l;x=Z>>>13,Z&=8191,Z+=b*h+I*c+$*a+A*(5*d)+T*(5*y),x+=Z>>>13,Z&=8191;let G=x+S*y+U*w+N*g+B*p+j*u;x=G>>>13,G&=8191,G+=b*l+I*h+$*c+A*a+T*(5*d),x+=G>>>13,G&=8191;let W=x+S*d+U*y+N*w+B*g+j*p;x=W>>>13,W&=8191,W+=b*u+I*l+$*h+A*c+T*a,x+=W>>>13,W&=8191,x=(x<<2)+x|0,x=x+q|0,q=x&8191,x=x>>>13,k+=x,n[0]=q,n[1]=k,n[2]=L,n[3]=M,n[4]=F,n[5]=H,n[6]=K,n[7]=Z,n[8]=G,n[9]=W}finalize(){const{h:e,pad:t}=this,s=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,s[0]=e[0]+5,r=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+r,r=s[a]>>>13,s[a]&=8191;s[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)s[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|s[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;Hi(s)}update(e){Ea(this);const{buffer:t,blockLen:s}=this;e=Qn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o===s){for(;s<=r-n;n+=s)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Hi(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ea(this),Jd(e,this),this.finished=!0;const{buffer:t,h:s}=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++]=s[o]>>>0,e[n++]=s[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}};function dp(i){const e=(s,r)=>i(r).update(Qn(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const pp=dp(i=>new up(i));function fp(i,e,t,s,r,n=20){let o=i[0],a=i[1],c=i[2],h=i[3],l=e[0],u=e[1],p=e[2],g=e[3],w=e[4],y=e[5],d=e[6],m=e[7],f=r,E=t[0],_=t[1],C=t[2],O=o,P=a,R=c,S=h,U=l,N=u,B=p,j=g,b=w,I=y,$=d,A=m,T=f,x=E,q=_,k=C;for(let M=0;M<n;M+=2)O=O+U|0,T=Q(T^O,16),b=b+T|0,U=Q(U^b,12),O=O+U|0,T=Q(T^O,8),b=b+T|0,U=Q(U^b,7),P=P+N|0,x=Q(x^P,16),I=I+x|0,N=Q(N^I,12),P=P+N|0,x=Q(x^P,8),I=I+x|0,N=Q(N^I,7),R=R+B|0,q=Q(q^R,16),$=$+q|0,B=Q(B^$,12),R=R+B|0,q=Q(q^R,8),$=$+q|0,B=Q(B^$,7),S=S+j|0,k=Q(k^S,16),A=A+k|0,j=Q(j^A,12),S=S+j|0,k=Q(k^S,8),A=A+k|0,j=Q(j^A,7),O=O+N|0,k=Q(k^O,16),$=$+k|0,N=Q(N^$,12),O=O+N|0,k=Q(k^O,8),$=$+k|0,N=Q(N^$,7),P=P+B|0,T=Q(T^P,16),A=A+T|0,B=Q(B^A,12),P=P+B|0,T=Q(T^P,8),A=A+T|0,B=Q(B^A,7),R=R+j|0,x=Q(x^R,16),b=b+x|0,j=Q(j^b,12),R=R+j|0,x=Q(x^R,8),b=b+x|0,j=Q(j^b,7),S=S+U|0,q=Q(q^S,16),I=I+q|0,U=Q(U^I,12),S=S+U|0,q=Q(q^S,8),I=I+q|0,U=Q(U^I,7);let L=0;s[L++]=o+O|0,s[L++]=a+P|0,s[L++]=c+R|0,s[L++]=h+S|0,s[L++]=l+U|0,s[L++]=u+N|0,s[L++]=p+B|0,s[L++]=g+j|0,s[L++]=w+b|0,s[L++]=y+I|0,s[L++]=d+$|0,s[L++]=m+A|0,s[L++]=f+T|0,s[L++]=E+x|0,s[L++]=_+q|0,s[L++]=C+k|0}const gp=lp(fp,{counterRight:!1,counterLength:4,allowShortKeys:!1}),yp=new Uint8Array(16),Pa=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(yp.subarray(t))},wp=new Uint8Array(32);function _a(i,e,t,s,r){const n=i(e,t,wp),o=pp.create(n);r&&Pa(o,r),Pa(o,s);const a=new Uint8Array(16),c=Yd(a);Sa(c,0,BigInt(r?r.length:0),!0),Sa(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return Hi(n,a),h}const mp=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=Ia(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=_a(i,e,t,a,s);return n.set(c,o),Hi(c),n},decrypt(r,n){n=Ia(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=_a(i,e,t,o,s);if(!tp(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),Hi(c),n}});ip({blockSize:64,nonceLength:12,tagLength:16},mp(gp));let ol=class extends Go{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ad(e);const s=qr(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(s.length>r?e.create().update(s).digest():s);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 zi(this),this.iHash.update(e),this}digestInto(e){zi(this),Ks(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:s,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=s._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const al=(i,e,t)=>new ol(i,e).update(t).digest();al.create=(i,e)=>new ol(i,e);function bp(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=s?4:0,h=s?0:4;i.setUint32(e+c,o,s),i.setUint32(e+h,a,s)}function vp(i,e,t){return i&e^~i&t}function Ep(i,e,t){return i&e^i&t^e&t}let $p=class extends Go{constructor(e,t,s,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=nn(this.buffer)}update(e){zi(this);const{view:t,buffer:s,blockLen:r}=this;e=qr(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const c=nn(e);for(;r<=n-o;o+=r)this.process(c,o);continue}s.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){zi(this),Jh(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(s,0),o=0);for(let u=o;u<r;u++)t[u]=0;bp(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=nn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,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(s),e}};const Ip=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]),Bt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ut=new Uint32Array(64);let Sp=class extends $p{constructor(){super(64,32,8,!1),this.A=Bt[0]|0,this.B=Bt[1]|0,this.C=Bt[2]|0,this.D=Bt[3]|0,this.E=Bt[4]|0,this.F=Bt[5]|0,this.G=Bt[6]|0,this.H=Bt[7]|0}get(){const{A:e,B:t,C:s,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,s,r,n,o,a,c]}set(e,t,s,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Ut[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=Ut[u-15],g=Ut[u-2],w=pt(p,7)^pt(p,18)^p>>>3,y=pt(g,17)^pt(g,19)^g>>>10;Ut[u]=y+Ut[u-7]+w+Ut[u-16]|0}let{A:s,B:r,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let u=0;u<64;u++){const p=pt(a,6)^pt(a,11)^pt(a,25),g=l+p+vp(a,c,h)+Ip[u]+Ut[u]|0,w=(pt(s,2)^pt(s,13)^pt(s,22))+Ep(s,r,n)|0;l=h,h=c,c=a,a=o+g|0,o=n,n=r,r=s,s=g+w|0}s=s+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(s,r,n,o,a,c,h,l)}roundClean(){Ut.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const xp=Yh(()=>new Sp);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kr=BigInt(0),Lr=BigInt(1),Pp=BigInt(2);function ri(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Gs(i){if(!ri(i))throw new Error("Uint8Array expected")}function Vi(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const _p=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Ki(i){Gs(i);let e="";for(let t=0;t<i.length;t++)e+=_p[i[t]];return e}function qi(i){const e=i.toString(16);return e.length&1?"0"+e:e}function Wo(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?kr:BigInt("0x"+i)}const vt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Oa(i){if(i>=vt._0&&i<=vt._9)return i-vt._0;if(i>=vt.A&&i<=vt.F)return i-(vt.A-10);if(i>=vt.a&&i<=vt.f)return i-(vt.a-10)}function Gi(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const s=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=Oa(i.charCodeAt(n)),a=Oa(i.charCodeAt(n+1));if(o===void 0||a===void 0){const c=i[n]+i[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}s[r]=o*16+a}return s}function Xt(i){return Wo(Ki(i))}function Us(i){return Gs(i),Wo(Ki(Uint8Array.from(i).reverse()))}function Wi(i,e){return Gi(i.toString(16).padStart(e*2,"0"))}function Dr(i,e){return Wi(i,e).reverse()}function Op(i){return Gi(qi(i))}function Ke(i,e,t){let s;if(typeof e=="string")try{s=Gi(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(ri(e))s=Uint8Array.from(e);else throw new Error(i+" must be hex string or Uint8Array");const r=s.length;if(typeof t=="number"&&r!==t)throw new Error(i+" of length "+t+" expected, got "+r);return s}function js(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Gs(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}function Ap(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}function Rp(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const an=i=>typeof i=="bigint"&&kr<=i;function Fr(i,e,t){return an(i)&&an(e)&&an(t)&&e<=i&&i<t}function Nt(i,e,t,s){if(!Fr(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function cl(i){let e;for(e=0;i>kr;i>>=Lr,e+=1);return e}function Np(i,e){return i>>BigInt(e)&Lr}function Tp(i,e,t){return i|(t?Lr:kr)<<BigInt(e)}const Zo=i=>(Pp<<BigInt(i-1))-Lr,cn=i=>new Uint8Array(i),Aa=i=>Uint8Array.from(i);function hl(i,e,t){if(typeof i!="number"||i<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let s=cn(i),r=cn(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=cn())=>{r=a(Aa([0]),l),s=a(),l.length!==0&&(r=a(Aa([1]),l),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const u=[];for(;l<e;){s=a();const p=s.slice();u.push(p),l+=s.length}return js(...u)};return(l,u)=>{o(),c(l);let p;for(;!(p=u(h()));)c();return o(),p}}const Cp={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||ri(i),isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function cs(i,e,t={}){const s=(r,n,o)=>{const a=Cp[n];if(typeof a!="function")throw new Error("invalid validator function");const c=i[r];if(!(o&&c===void 0)&&!a(c,i))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))s(r,n,!1);for(const[r,n]of Object.entries(t))s(r,n,!0);return i}const Bp=()=>{throw new Error("not implemented")};function to(i){const e=new WeakMap;return(t,...s)=>{const r=e.get(t);if(r!==void 0)return r;const n=i(t,...s);return e.set(t,n),n}}var Up=Object.freeze({__proto__:null,isBytes:ri,abytes:Gs,abool:Vi,bytesToHex:Ki,numberToHexUnpadded:qi,hexToNumber:Wo,hexToBytes:Gi,bytesToNumberBE:Xt,bytesToNumberLE:Us,numberToBytesBE:Wi,numberToBytesLE:Dr,numberToVarBytesBE:Op,ensureBytes:Ke,concatBytes:js,equalBytes:Ap,utf8ToBytes:Rp,inRange:Fr,aInRange:Nt,bitLen:cl,bitGet:Np,bitSet:Tp,bitMask:Zo,createHmacDrbg:hl,validateObject:cs,notImplemented:Bp,memoized:to});const Se=BigInt(0),pe=BigInt(1),Gt=BigInt(2),jp=BigInt(3),io=BigInt(4),Ra=BigInt(5),Na=BigInt(8);function Le(i,e){const t=i%e;return t>=Se?t:e+t}function ll(i,e,t){if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(t<=Se)throw new Error("invalid modulus");if(t===pe)return Se;let s=pe;for(;e>Se;)e&pe&&(s=s*i%t),i=i*i%t,e>>=pe;return s}function ct(i,e,t){let s=i;for(;e-- >Se;)s*=s,s%=t;return s}function so(i,e){if(i===Se)throw new Error("invert: expected non-zero number");if(e<=Se)throw new Error("invert: expected positive modulus, got "+e);let t=Le(i,e),s=e,r=Se,n=pe;for(;t!==Se;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==pe)throw new Error("invert: does not exist");return Le(r,e)}function qp(i){const e=(i-pe)/Gt;let t,s,r;for(t=i-pe,s=0;t%Gt===Se;t/=Gt,s++);for(r=Gt;r<i&&ll(r,e,i)!==i-pe;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+pe)/io;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(t+pe)/Gt;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=s,h=o.pow(o.mul(o.ONE,r),t),l=o.pow(a,n),u=o.pow(a,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let p=1;for(let w=o.sqr(u);p<c&&!o.eql(w,o.ONE);p++)w=o.sqr(w);const g=o.pow(h,pe<<BigInt(c-p-1));h=o.sqr(g),l=o.mul(l,g),u=o.mul(u,h),c=p}return l}}function kp(i){if(i%io===jp){const e=(i+pe)/io;return function(t,s){const r=t.pow(s,e);if(!t.eql(t.sqr(r),s))throw new Error("Cannot find square root");return r}}if(i%Na===Ra){const e=(i-Ra)/Na;return function(t,s){const r=t.mul(s,Gt),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,Gt),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),s))throw new Error("Cannot find square root");return c}}return qp(i)}const Lp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Dp(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Lp.reduce((s,r)=>(s[r]="function",s),e);return cs(i,t)}function Fp(i,e,t){if(t<Se)throw new Error("invalid exponent, negatives unsupported");if(t===Se)return i.ONE;if(t===pe)return e;let s=i.ONE,r=e;for(;t>Se;)t&pe&&(s=i.mul(s,r)),r=i.sqr(r),t>>=pe;return s}function Mp(i,e){const t=new Array(e.length),s=e.reduce((n,o,a)=>i.is0(o)?n:(t[a]=n,i.mul(n,o)),i.ONE),r=i.inv(s);return e.reduceRight((n,o,a)=>i.is0(o)?n:(t[a]=i.mul(n,t[a]),i.mul(n,o)),r),t}function ul(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function dl(i,e,t=!1,s={}){if(i<=Se)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=ul(i,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:i,isLE:t,BITS:r,BYTES:n,MASK:Zo(r),ZERO:Se,ONE:pe,create:c=>Le(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Se<=c&&c<i},is0:c=>c===Se,isOdd:c=>(c&pe)===pe,neg:c=>Le(-c,i),eql:(c,h)=>c===h,sqr:c=>Le(c*c,i),add:(c,h)=>Le(c+h,i),sub:(c,h)=>Le(c-h,i),mul:(c,h)=>Le(c*h,i),pow:(c,h)=>Fp(a,c,h),div:(c,h)=>Le(c*so(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>so(c,i),sqrt:s.sqrt||(c=>(o||(o=kp(i)),o(a,c))),invertBatch:c=>Mp(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?Dr(c,n):Wi(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?Us(c):Xt(c)}});return Object.freeze(a)}function pl(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function fl(i){const e=pl(i);return e+Math.ceil(e/2)}function zp(i,e,t=!1){const s=i.length,r=pl(e),n=fl(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?Us(i):Xt(i),a=Le(o,e-pe)+pe;return t?Dr(a,r):Wi(a,r)}const Ta=BigInt(0),or=BigInt(1);function hn(i,e){const t=e.negate();return i?t:e}function gl(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function ln(i,e){gl(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function Hp(i,e){if(!Array.isArray(i))throw new Error("array expected");i.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function Vp(i,e){if(!Array.isArray(i))throw new Error("array of scalars expected");i.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}const un=new WeakMap,yl=new WeakMap;function dn(i){return yl.get(i)||1}function Kp(i,e){return{constTimeNegate:hn,hasPrecomputes(t){return dn(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>Ta;)s&or&&(r=r.add(n)),n=n.double(),s>>=or;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=ln(s,e),o=[];let a=t,c=a;for(let h=0;h<r;h++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,s,r){const{windows:n,windowSize:o}=ln(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),l=2**t,u=BigInt(t);for(let p=0;p<n;p++){const g=p*o;let w=Number(r&h);r>>=u,w>o&&(w-=l,r+=or);const y=g,d=g+Math.abs(w)-1,m=p%2!==0,f=w<0;w===0?c=c.add(hn(m,s[y])):a=a.add(hn(f,s[d]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=ln(t,e),c=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let u=0;u<o;u++){const p=u*a;if(r===Ta)break;let g=Number(r&c);if(r>>=l,g>a&&(g-=h,r+=or),g===0)continue;let w=s[p+Math.abs(g)-1];g<0&&(w=w.negate()),n=n.add(w)}return n},getPrecomputes(t,s,r){let n=un.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&un.set(s,r(n))),n},wNAFCached(t,s,r){const n=dn(t);return this.wNAF(n,this.getPrecomputes(n,t,r),s)},wNAFCachedUnsafe(t,s,r,n){const o=dn(t);return o===1?this.unsafeLadder(t,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,r),s,n)},setWindowSize(t,s){gl(s,e),yl.set(t,s),un.delete(t)}}}function Gp(i,e,t,s){if(Hp(t,i),Vp(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=cl(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r),h=Math.floor((e.BITS-1)/o)*o;let l=r;for(let u=h;u>=0;u-=o){c.fill(r);for(let g=0;g<s.length;g++){const w=s[g],y=Number(w>>BigInt(u)&BigInt(a));c[y]=c[y].add(t[g])}let p=r;for(let g=c.length-1,w=r;g>0;g--)w=w.add(c[g]),p=p.add(w);if(l=l.add(p),u!==0)for(let g=0;g<o;g++)l=l.double()}return l}function wl(i){return Dp(i.Fp),cs(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ul(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const fi=BigInt(0),pn=BigInt(1);function Wp(i){return cs(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function Zp(i){const e=Wp(i),{P:t}=e,s=f=>Le(f,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(f=>f),c=e.powPminus2||(f=>ll(f,t-BigInt(2),t));function h(f,E,_){const C=s(f*(E-_));return E=s(E-C),_=s(_+C),[E,_]}const l=(e.a-BigInt(2))/BigInt(4);function u(f,E){Nt("u",f,fi,t),Nt("scalar",E,fi,t);const _=E,C=f;let O=pn,P=fi,R=f,S=pn,U=fi,N;for(let j=BigInt(r-1);j>=fi;j--){const b=_>>j&pn;U^=b,N=h(U,O,R),O=N[0],R=N[1],N=h(U,P,S),P=N[0],S=N[1],U=b;const I=O+P,$=s(I*I),A=O-P,T=s(A*A),x=$-T,q=R+S,k=R-S,L=s(k*I),M=s(q*A),F=L+M,H=L-M;R=s(F*F),S=s(C*s(H*H)),O=s($*T),P=s(x*($+s(l*x)))}N=h(U,O,R),O=N[0],R=N[1],N=h(U,P,S),P=N[0],S=N[1];const B=c(P);return s(O*B)}function p(f){return Dr(s(f),n)}function g(f){const E=Ke("u coordinate",f,n);return o===32&&(E[31]&=127),Us(E)}function w(f){const E=Ke("scalar",f),_=E.length;if(_!==n&&_!==o){let C=""+n+" or "+o;throw new Error("invalid scalar, expected "+C+" bytes, got "+_)}return Us(a(E))}function y(f,E){const _=g(E),C=w(f),O=u(_,C);if(O===fi)throw new Error("invalid private or public key received");return p(O)}const d=p(e.Gu);function m(f){return y(f,d)}return{scalarMult:y,scalarMultBase:m,getSharedSecret:(f,E)=>y(f,E),getPublicKey:f=>m(f),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:d}}const ro=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Jp=BigInt(1),Ca=BigInt(2),Yp=BigInt(3),Qp=BigInt(5);BigInt(8);function Xp(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=ro,o=i*i%n*i%n,a=ct(o,Ca,n)*o%n,c=ct(a,Jp,n)*i%n,h=ct(c,Qp,n)*c%n,l=ct(h,e,n)*h%n,u=ct(l,t,n)*l%n,p=ct(u,s,n)*u%n,g=ct(p,r,n)*p%n,w=ct(g,r,n)*p%n,y=ct(w,e,n)*h%n;return{pow_p_5_8:ct(y,Ca,n)*i%n,b2:o}}function ef(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}Zp({P:ro,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=ro,{pow_p_5_8:t,b2:s}=Xp(i);return Le(ct(t,Yp,e)*s,e)},adjustScalarBytes:ef,randomBytes:Qh});function Ba(i){i.lowS!==void 0&&Vi("lowS",i.lowS),i.prehash!==void 0&&Vi("prehash",i.prehash)}function tf(i){const e=wl(i);cs(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:s,a:r}=e;if(t){if(!s.eql(r,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:sf,hexToBytes:rf}=Up;let nf=class extends Error{constructor(e=""){super(e)}};const xt={Err:nf,_tlv:{encode:(i,e)=>{const{Err:t}=xt;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const s=e.length/2,r=qi(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?qi(r.length/2|128):"";return qi(i)+n+r+e},decode(i,e){const{Err:t}=xt;let s=0;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==i)throw new t("tlv.decode: wrong tlv");const r=e[s++],n=!!(r&128);let o=0;if(!n)o=r;else{const c=r&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const h=e.subarray(s,s+c);if(h.length!==c)throw new t("tlv.decode: length bytes not complete");if(h[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const l of h)o=o<<8|l;if(s+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(s,s+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(i){const{Err:e}=xt;if(i<Ot)throw new e("integer: negative integers are not allowed");let t=qi(i);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(i){const{Err:e}=xt;if(i[0]&128)throw new e("invalid signature integer: negative");if(i[0]===0&&!(i[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return sf(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=xt,r=typeof i=="string"?rf(i):i;Gs(r);const{v:n,l:o}=s.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l}=s.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(h)}},hexFromSig(i){const{_tlv:e,_int:t}=xt,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},Ot=BigInt(0),be=BigInt(1);BigInt(2);const Ua=BigInt(3);BigInt(4);function of(i){const e=tf(i),{Fp:t}=e,s=dl(e.n,e.nBitLength),r=e.toBytes||((y,d,m)=>{const f=d.toAffine();return js(Uint8Array.from([4]),t.toBytes(f.x),t.toBytes(f.y))}),n=e.fromBytes||(y=>{const d=y.subarray(1),m=t.fromBytes(d.subarray(0,t.BYTES)),f=t.fromBytes(d.subarray(t.BYTES,2*t.BYTES));return{x:m,y:f}});function o(y){const{a:d,b:m}=e,f=t.sqr(y),E=t.mul(f,y);return t.add(t.add(E,t.mul(y,d)),m)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Fr(y,be,e.n)}function c(y){const{allowedPrivateKeyLengths:d,nByteLength:m,wrapPrivateKey:f,n:E}=e;if(d&&typeof y!="bigint"){if(ri(y)&&(y=Ki(y)),typeof y!="string"||!d.includes(y.length))throw new Error("invalid private key");y=y.padStart(m*2,"0")}let _;try{_=typeof y=="bigint"?y:Xt(Ke("private key",y,m))}catch{throw new Error("invalid private key, expected hex or "+m+" bytes, got "+typeof y)}return f&&(_=Le(_,E)),Nt("private key",_,be,E),_}function h(y){if(!(y instanceof p))throw new Error("ProjectivePoint expected")}const l=to((y,d)=>{const{px:m,py:f,pz:E}=y;if(t.eql(E,t.ONE))return{x:m,y:f};const _=y.is0();d==null&&(d=_?t.ONE:t.inv(E));const C=t.mul(m,d),O=t.mul(f,d),P=t.mul(E,d);if(_)return{x:t.ZERO,y:t.ZERO};if(!t.eql(P,t.ONE))throw new Error("invZ was invalid");return{x:C,y:O}}),u=to(y=>{if(y.is0()){if(e.allowInfinityPoint&&!t.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:d,y:m}=y.toAffine();if(!t.isValid(d)||!t.isValid(m))throw new Error("bad point: x or y not FE");const f=t.sqr(m),E=o(d);if(!t.eql(f,E))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class p{constructor(d,m,f){if(this.px=d,this.py=m,this.pz=f,d==null||!t.isValid(d))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(f==null||!t.isValid(f))throw new Error("z required");Object.freeze(this)}static fromAffine(d){const{x:m,y:f}=d||{};if(!d||!t.isValid(m)||!t.isValid(f))throw new Error("invalid affine point");if(d instanceof p)throw new Error("projective point not allowed");const E=_=>t.eql(_,t.ZERO);return E(m)&&E(f)?p.ZERO:new p(m,f,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){const m=t.invertBatch(d.map(f=>f.pz));return d.map((f,E)=>f.toAffine(m[E])).map(p.fromAffine)}static fromHex(d){const m=p.fromAffine(n(Ke("pointHex",d)));return m.assertValidity(),m}static fromPrivateKey(d){return p.BASE.multiply(c(d))}static msm(d,m){return Gp(p,s,d,m)}_setWindowSize(d){w.setWindowSize(this,d)}assertValidity(){u(this)}hasEvenY(){const{y:d}=this.toAffine();if(t.isOdd)return!t.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){h(d);const{px:m,py:f,pz:E}=this,{px:_,py:C,pz:O}=d,P=t.eql(t.mul(m,O),t.mul(_,E)),R=t.eql(t.mul(f,O),t.mul(C,E));return P&&R}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:d,b:m}=e,f=t.mul(m,Ua),{px:E,py:_,pz:C}=this;let O=t.ZERO,P=t.ZERO,R=t.ZERO,S=t.mul(E,E),U=t.mul(_,_),N=t.mul(C,C),B=t.mul(E,_);return B=t.add(B,B),R=t.mul(E,C),R=t.add(R,R),O=t.mul(d,R),P=t.mul(f,N),P=t.add(O,P),O=t.sub(U,P),P=t.add(U,P),P=t.mul(O,P),O=t.mul(B,O),R=t.mul(f,R),N=t.mul(d,N),B=t.sub(S,N),B=t.mul(d,B),B=t.add(B,R),R=t.add(S,S),S=t.add(R,S),S=t.add(S,N),S=t.mul(S,B),P=t.add(P,S),N=t.mul(_,C),N=t.add(N,N),S=t.mul(N,B),O=t.sub(O,S),R=t.mul(N,U),R=t.add(R,R),R=t.add(R,R),new p(O,P,R)}add(d){h(d);const{px:m,py:f,pz:E}=this,{px:_,py:C,pz:O}=d;let P=t.ZERO,R=t.ZERO,S=t.ZERO;const U=e.a,N=t.mul(e.b,Ua);let B=t.mul(m,_),j=t.mul(f,C),b=t.mul(E,O),I=t.add(m,f),$=t.add(_,C);I=t.mul(I,$),$=t.add(B,j),I=t.sub(I,$),$=t.add(m,E);let A=t.add(_,O);return $=t.mul($,A),A=t.add(B,b),$=t.sub($,A),A=t.add(f,E),P=t.add(C,O),A=t.mul(A,P),P=t.add(j,b),A=t.sub(A,P),S=t.mul(U,$),P=t.mul(N,b),S=t.add(P,S),P=t.sub(j,S),S=t.add(j,S),R=t.mul(P,S),j=t.add(B,B),j=t.add(j,B),b=t.mul(U,b),$=t.mul(N,$),j=t.add(j,b),b=t.sub(B,b),b=t.mul(U,b),$=t.add($,b),B=t.mul(j,$),R=t.add(R,B),B=t.mul(A,$),P=t.mul(I,P),P=t.sub(P,B),B=t.mul(I,j),S=t.mul(A,S),S=t.add(S,B),new p(P,R,S)}subtract(d){return this.add(d.negate())}is0(){return this.equals(p.ZERO)}wNAF(d){return w.wNAFCached(this,d,p.normalizeZ)}multiplyUnsafe(d){const{endo:m,n:f}=e;Nt("scalar",d,Ot,f);const E=p.ZERO;if(d===Ot)return E;if(this.is0()||d===be)return this;if(!m||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,d,p.normalizeZ);let{k1neg:_,k1:C,k2neg:O,k2:P}=m.splitScalar(d),R=E,S=E,U=this;for(;C>Ot||P>Ot;)C&be&&(R=R.add(U)),P&be&&(S=S.add(U)),U=U.double(),C>>=be,P>>=be;return _&&(R=R.negate()),O&&(S=S.negate()),S=new p(t.mul(S.px,m.beta),S.py,S.pz),R.add(S)}multiply(d){const{endo:m,n:f}=e;Nt("scalar",d,be,f);let E,_;if(m){const{k1neg:C,k1:O,k2neg:P,k2:R}=m.splitScalar(d);let{p:S,f:U}=this.wNAF(O),{p:N,f:B}=this.wNAF(R);S=w.constTimeNegate(C,S),N=w.constTimeNegate(P,N),N=new p(t.mul(N.px,m.beta),N.py,N.pz),E=S.add(N),_=U.add(B)}else{const{p:C,f:O}=this.wNAF(d);E=C,_=O}return p.normalizeZ([E,_])[0]}multiplyAndAddUnsafe(d,m,f){const E=p.BASE,_=(O,P)=>P===Ot||P===be||!O.equals(E)?O.multiplyUnsafe(P):O.multiply(P),C=_(this,m).add(_(d,f));return C.is0()?void 0:C}toAffine(d){return l(this,d)}isTorsionFree(){const{h:d,isTorsionFree:m}=e;if(d===be)return!0;if(m)return m(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:d,clearCofactor:m}=e;return d===be?this:m?m(p,this):this.multiplyUnsafe(e.h)}toRawBytes(d=!0){return Vi("isCompressed",d),this.assertValidity(),r(p,this,d)}toHex(d=!0){return Vi("isCompressed",d),Ki(this.toRawBytes(d))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const g=e.nBitLength,w=Kp(p,e.endo?Math.ceil(g/2):g);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function af(i){const e=wl(i);return cs(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function cf(i){const e=af(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(b){return Le(b,s)}function a(b){return so(b,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=of({...e,toBytes(b,I,$){const A=I.toAffine(),T=t.toBytes(A.x),x=js;return Vi("isCompressed",$),$?x(Uint8Array.from([I.hasEvenY()?2:3]),T):x(Uint8Array.from([4]),T,t.toBytes(A.y))},fromBytes(b){const I=b.length,$=b[0],A=b.subarray(1);if(I===r&&($===2||$===3)){const T=Xt(A);if(!Fr(T,be,t.ORDER))throw new Error("Point is not on curve");const x=l(T);let q;try{q=t.sqrt(x)}catch(L){const M=L instanceof Error?": "+L.message:"";throw new Error("Point is not on curve"+M)}const k=(q&be)===be;return($&1)===1!==k&&(q=t.neg(q)),{x:T,y:q}}else if(I===n&&$===4){const T=t.fromBytes(A.subarray(0,t.BYTES)),x=t.fromBytes(A.subarray(t.BYTES,2*t.BYTES));return{x:T,y:x}}else{const T=r,x=n;throw new Error("invalid Point, expected length of "+T+", or uncompressed "+x+", got "+I)}}}),p=b=>Ki(Wi(b,e.nByteLength));function g(b){const I=s>>be;return b>I}function w(b){return g(b)?o(-b):b}const y=(b,I,$)=>Xt(b.slice(I,$));class d{constructor(I,$,A){this.r=I,this.s=$,this.recovery=A,this.assertValidity()}static fromCompact(I){const $=e.nByteLength;return I=Ke("compactSignature",I,$*2),new d(y(I,0,$),y(I,$,2*$))}static fromDER(I){const{r:$,s:A}=xt.toSig(Ke("DER",I));return new d($,A)}assertValidity(){Nt("r",this.r,be,s),Nt("s",this.s,be,s)}addRecoveryBit(I){return new d(this.r,this.s,I)}recoverPublicKey(I){const{r:$,s:A,recovery:T}=this,x=O(Ke("msgHash",I));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");const q=T===2||T===3?$+e.n:$;if(q>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const k=(T&1)===0?"02":"03",L=c.fromHex(k+p(q)),M=a(q),F=o(-x*M),H=o(A*M),K=c.BASE.multiplyAndAddUnsafe(L,F,H);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new d(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Gi(this.toDERHex())}toDERHex(){return xt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Gi(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const m={isValidPrivateKey(b){try{return h(b),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const b=fl(e.n);return zp(e.randomBytes(b),e.n)},precompute(b=8,I=c.BASE){return I._setWindowSize(b),I.multiply(BigInt(3)),I}};function f(b,I=!0){return c.fromPrivateKey(b).toRawBytes(I)}function E(b){const I=ri(b),$=typeof b=="string",A=(I||$)&&b.length;return I?A===r||A===n:$?A===2*r||A===2*n:b instanceof c}function _(b,I,$=!0){if(E(b))throw new Error("first arg must be private key");if(!E(I))throw new Error("second arg must be public key");return c.fromHex(I).multiply(h(b)).toRawBytes($)}const C=e.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const I=Xt(b),$=b.length*8-e.nBitLength;return $>0?I>>BigInt($):I},O=e.bits2int_modN||function(b){return o(C(b))},P=Zo(e.nBitLength);function R(b){return Nt("num < 2^"+e.nBitLength,b,Ot,P),Wi(b,e.nByteLength)}function S(b,I,$=U){if(["recovered","canonical"].some(G=>G in $))throw new Error("sign() legacy options not supported");const{hash:A,randomBytes:T}=e;let{lowS:x,prehash:q,extraEntropy:k}=$;x==null&&(x=!0),b=Ke("msgHash",b),Ba($),q&&(b=Ke("prehashed msgHash",A(b)));const L=O(b),M=h(I),F=[R(M),R(L)];if(k!=null&&k!==!1){const G=k===!0?T(t.BYTES):k;F.push(Ke("extraEntropy",G))}const H=js(...F),K=L;function Z(G){const W=C(G);if(!u(W))return;const Be=a(W),ue=c.BASE.multiply(W).toAffine(),ae=o(ue.x);if(ae===Ot)return;const he=o(Be*o(K+ae*M));if(he===Ot)return;let Xe=(ue.x===ae?0:2)|Number(ue.y&be),dt=he;return x&&g(he)&&(dt=w(he),Xe^=1),new d(ae,dt,Xe)}return{seed:H,k2sig:Z}}const U={lowS:e.lowS,prehash:!1},N={lowS:e.lowS,prehash:!1};function B(b,I,$=U){const{seed:A,k2sig:T}=S(b,I,$),x=e;return hl(x.hash.outputLen,x.nByteLength,x.hmac)(A,T)}c.BASE._setWindowSize(8);function j(b,I,$,A=N){const T=b;I=Ke("msgHash",I),$=Ke("publicKey",$);const{lowS:x,prehash:q,format:k}=A;if(Ba(A),"strict"in A)throw new Error("options.strict was renamed to lowS");if(k!==void 0&&k!=="compact"&&k!=="der")throw new Error("format must be compact or der");const L=typeof T=="string"||ri(T),M=!L&&!k&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!L&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,H;try{if(M&&(F=new d(T.r,T.s)),L){try{k!=="compact"&&(F=d.fromDER(T))}catch(he){if(!(he instanceof xt.Err))throw he}!F&&k!=="der"&&(F=d.fromCompact(T))}H=c.fromHex($)}catch{return!1}if(!F||x&&F.hasHighS())return!1;q&&(I=e.hash(I));const{r:K,s:Z}=F,G=O(I),W=a(Z),Be=o(G*W),ue=o(K*W),ae=c.BASE.multiplyAndAddUnsafe(H,Be,ue)?.toAffine();return ae?o(ae.x)===K:!1}return{CURVE:e,getPublicKey:f,getSharedSecret:_,sign:B,verify:j,ProjectivePoint:c,Signature:d,utils:m}}function hf(i){return{hash:i,hmac:(e,...t)=>al(i,e,Ld(...t)),randomBytes:Qh}}function lf(i,e){const t=s=>cf({...i,...hf(s)});return{...t(e),create:t}}const ml=dl(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),uf=ml.create(BigInt("-3")),df=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");lf({a:uf,b:df,Fp:ml,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},xp);function Jo(i){return i.includes(":")}function _s(i){return Jo(i)?i.split(":")[0]:i}const pf={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}};function no(i,e){const{message:t,code:s}=pf[i];return{message:t,code:s}}function Mi(i,e){return!!Array.isArray(i)}function fn(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}var ff=Object.defineProperty,gf=(i,e,t)=>e in i?ff(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ja=(i,e,t)=>gf(i,typeof e!="symbol"?e+"":e,t);let yf=class extends v.IEvents{constructor(e){super(),this.opts=e,ja(this,"protocol","wc"),ja(this,"version",2)}};var wf=Object.defineProperty,mf=(i,e,t)=>e in i?wf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bf=(i,e,t)=>mf(i,e+"",t);let vf=class extends v.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,bf(this,"records",new Map)}},Ef=class{constructor(e,t){this.logger=e,this.core=t}};class $f extends v.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}let If=class extends v.IEvents{constructor(e){super()}},Sf=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},xf=class extends v.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},Pf=class extends v.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},_f=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},Of=class{constructor(e,t){this.projectId=e,this.logger=t}},Af=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var Rf=Object.defineProperty,Nf=(i,e,t)=>e in i?Rf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qa=(i,e,t)=>Nf(i,typeof e!="symbol"?e+"":e,t);let Tf=class{constructor(e){this.opts=e,qa(this,"protocol","wc"),qa(this,"version",2)}},Cf=class{constructor(e){this.client=e}};function Bf(i){if(i.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<i.length;h++){const l=i.charAt(h),u=l.charCodeAt(0);if(e[u]!==255)throw new TypeError(l+" is ambiguous");e[u]=h}const t=i.length,s=i.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let l=0,u=0,p=0;const g=h.length;for(;p!==g&&h[p]===0;)p++,l++;const w=(g-p)*n+1>>>0,y=new Uint8Array(w);for(;p!==g;){let f=h[p],E=0;for(let _=w-1;(f!==0||E<u)&&_!==-1;_--,E++)f+=256*y[_]>>>0,y[_]=f%t>>>0,f=f/t>>>0;if(f!==0)throw new Error("Non-zero carry");u=E,p++}let d=w-u;for(;d!==w&&y[d]===0;)d++;let m=s.repeat(l);for(;d<w;++d)m+=i.charAt(y[d]);return m}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,u=0,p=0;for(;h[l]===s;)u++,l++;const g=(h.length-l)*r+1>>>0,w=new Uint8Array(g);for(;l<h.length;){const f=h.charCodeAt(l);if(f>255)return;let E=e[f];if(E===255)return;let _=0;for(let C=g-1;(E!==0||_<p)&&C!==-1;C--,_++)E+=t*w[C]>>>0,w[C]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");p=_,l++}let y=g-p;for(;y!==g&&w[y]===0;)y++;const d=new Uint8Array(u+(g-y));let m=u;for(;y!==g;)d[m++]=w[y++];return d}function c(h){const l=a(h);if(l)return l;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Uf="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";Bf(Uf);const jf="ReactNative",ut={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},qf="js";function Or(){return typeof z.process$1<"u"&&typeof z.process$1.versions<"u"&&typeof z.process$1.versions.node<"u"}function li(){return!v.cjsExports$2.getDocument()&&!!v.cjsExports$2.getNavigator()&&navigator.product===jf}function kf(){return li()&&typeof z.global<"u"&&typeof(z.global==null?void 0:z.global.Platform)<"u"&&(z.global==null?void 0:z.global.Platform.OS)==="android"}function Lf(){return li()&&typeof z.global<"u"&&typeof(z.global==null?void 0:z.global.Platform)<"u"&&(z.global==null?void 0:z.global.Platform.OS)==="ios"}function Ws(){return!Or()&&!!v.cjsExports$2.getNavigator()&&!!v.cjsExports$2.getDocument()}function Mr(){return li()?ut.reactNative:Or()?ut.node:Ws()?ut.browser:ut.unknown}function ka(){var i;try{return li()&&typeof z.global<"u"&&typeof(z.global==null?void 0:z.global.Application)<"u"?(i=z.global.Application)==null?void 0:i.applicationId:void 0}catch{return}}function Df(i,e){const t=new URLSearchParams(i);for(const s of Object.keys(e).sort())if(e.hasOwnProperty(s)){const r=e[s];r!==void 0&&t.set(s,r)}return t.toString()}function Ff(){return v.cjsExports.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Mf(){if(Mr()===ut.reactNative&&typeof z.global<"u"&&typeof(z.global==null?void 0:z.global.Platform)<"u"){const{OS:t,Version:s}=z.global.Platform;return[t,s].join("-")}const i=v.detect();if(i===null)return"unknown";const e=i.os?i.os.replace(" ","").toLowerCase():"unknown";return i.type==="browser"?[e,i.name,i.version].join("-"):[e,i.version].join("-")}function zf(){var i;const e=Mr();return e===ut.browser?[e,((i=v.cjsExports$2.getLocation())==null?void 0:i.host)||"unknown"].join(":"):e}function bl(i,e,t){const s=Mf(),r=zf();return[[i,e].join("-"),[qf,t].join("-"),s,r].join("/")}function Hf({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=bl(i,e,s),u={auth:r,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=Df(h[1]||"",u);return h[0]+"?"+p}function oo(i){return Object.fromEntries(i.entries())}function ao(i){return new Map(Object.entries(i))}function Vf(i=v.cjsExports$1.FIVE_MINUTES,e){const t=v.cjsExports$1.toMiliseconds(i||v.cjsExports$1.FIVE_MINUTES);let s,r,n,o;return{resolve:a=>{n&&s&&(clearTimeout(n),s(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const h=new Error(e);o=Promise.reject(h),c(h)},t),s=a,r=c})}}function Dt(i,e,t){return new Promise(async(s,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await i;s(o)}catch(o){r(o)}clearTimeout(n)})}function vl(i,e){if(typeof e=="string"&&e.startsWith(`${i}:`))return e;if(i.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(i.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: ${i}`)}function Kf(i){return vl("topic",i)}function Gf(i){return vl("id",i)}function Wf(i){const[e,t]=i.split(":"),s={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")s.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))s.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return s}function Ns(i,e){return v.cjsExports$1.fromMiliseconds(Date.now()+v.cjsExports$1.toMiliseconds(i))}function La(i){return Date.now()>=v.cjsExports$1.toMiliseconds(i)}function gn(i,e){return`${i}${e?`:${e}`:""}`}function Da(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function El(){return typeof z.process$1<"u"&&z.process$1.env.IS_VITEST==="true"}function $l(i){return z.Buffer.from(i,"base64").toString("utf-8")}function Zf(i){return new Promise(e=>setTimeout(e,i))}function qs(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Jf(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Zs(i,...e){if(!Jf(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Yo(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");qs(i.outputLen),qs(i.blockLen)}function Zi(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Il(i,e){Zs(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ar=BigInt(2**32-1),Fa=BigInt(32);function Yf(i,e=!1){return e?{h:Number(i&ar),l:Number(i>>Fa&ar)}:{h:Number(i>>Fa&ar)|0,l:Number(i&ar)|0}}function Qf(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=Yf(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Xf=(i,e,t)=>i<<t|e>>>32-t,eg=(i,e,t)=>e<<t|i>>>32-t,tg=(i,e,t)=>e<<t-32|i>>>64-t,ig=(i,e,t)=>i<<t-32|e>>>64-t,gi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function sg(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function yn(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function ft(i,e){return i<<32-e|i>>>e}const Ma=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function rg(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function za(i){for(let e=0;e<i.length;e++)i[e]=rg(i[e])}function ng(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function Ji(i){return typeof i=="string"&&(i=ng(i)),Zs(i),i}function og(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Zs(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}let Qo=class{clone(){return this._cloneInto()}};function Sl(i){const e=s=>i().update(Ji(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function hs(i=32){if(gi&&typeof gi.getRandomValues=="function")return gi.getRandomValues(new Uint8Array(i));if(gi&&typeof gi.randomBytes=="function")return gi.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const xl=[],Pl=[],_l=[],ag=BigInt(0),ws=BigInt(1),cg=BigInt(2),hg=BigInt(7),lg=BigInt(256),ug=BigInt(113);for(let i=0,e=ws,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],xl.push(2*(5*s+t)),Pl.push((i+1)*(i+2)/2%64);let r=ag;for(let n=0;n<7;n++)e=(e<<ws^(e>>hg)*ug)%lg,e&cg&&(r^=ws<<(ws<<BigInt(n))-ws);_l.push(r)}const[dg,pg]=Qf(_l,!0),Ha=(i,e,t)=>t>32?tg(i,e,t):Xf(i,e,t),Va=(i,e,t)=>t>32?ig(i,e,t):eg(i,e,t);function fg(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=Ha(h,l,1)^t[a],p=Va(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Pl[o],c=Ha(r,n,a),h=Va(r,n,a),l=xl[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=dg[s],i[1]^=pg[s]}t.fill(0)}let gg=class Ol extends Qo{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,qs(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=sg(this.state)}keccak(){Ma||za(this.state32),fg(this.state32,this.rounds),Ma||za(this.state32),this.posOut=0,this.pos=0}update(e){Zi(this);const{blockLen:t,state:s}=this;e=Ji(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Zi(this,!1),Zs(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 qs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Il(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:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Ol(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const yg=(i,e,t)=>Sl(()=>new gg(e,i,t));yg(1,136,256/8);function wn(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Al(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Je(i,...e){if(!Al(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Ka(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function wg(i,e){Je(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Ga(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const Mt=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),mg=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),bg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!bg)throw new Error("Non little-endian hardware is not supported");function vg(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function co(i){if(typeof i=="string")i=vg(i);else if(Al(i))i=ho(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function Eg(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function $g(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}const Ig=(i,e)=>{function t(s,...r){if(Je(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?Je(h):Je(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&Je(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");Je(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Je(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(Je(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(h,l)}}}return Object.assign(t,i),t};function Wa(i,e,t=!0){if(e===void 0)return new Uint8Array(i);if(e.length!==i)throw new Error("invalid output length, expected "+i+", got: "+e.length);if(t&&!Sg(e))throw new Error("invalid output, must be aligned");return e}function Za(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);i.setUint32(e+4,o,s),i.setUint32(e+0,a,s)}function Sg(i){return i.byteOffset%4===0}function ho(i){return Uint8Array.from(i)}function Yi(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const Rl=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),xg=Rl("expand 16-byte k"),Pg=Rl("expand 32-byte k"),_g=Mt(xg),Og=Mt(Pg);function X(i,e){return i<<e|i>>>32-e}function lo(i){return i.byteOffset%4===0}const cr=64,Ag=16,Nl=2**32-1,Ja=new Uint32Array;function Rg(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(cr),l=Mt(h),u=lo(r)&&lo(n),p=u?Mt(r):Ja,g=u?Mt(n):Ja;for(let w=0;w<c;o++){if(i(e,t,s,l,o,a),o>=Nl)throw new Error("arx: counter overflow");const y=Math.min(cr,c-w);if(u&&y===cr){const d=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let m=0,f;m<Ag;m++)f=d+m,g[f]=p[f]^l[m];w+=cr;continue}for(let d=0,m;d<y;d++)m=w+d,n[m]=r[m]^h[d];w+=y}}function Ng(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=Eg({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return wn(r),wn(o),Ga(n),Ga(t),(a,c,h,l,u=0)=>{Je(a),Je(c),Je(h);const p=h.length;if(l===void 0&&(l=new Uint8Array(p)),Je(l),wn(u),u<0||u>=Nl)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const g=[];let w=a.length,y,d;if(w===32)g.push(y=ho(a)),d=Og;else if(w===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),d=_g,g.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${w}`);lo(c)||g.push(c=ho(c));const m=Mt(y);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(d,m,Mt(c.subarray(0,16)),m),c=c.subarray(16)}const f=16-r;if(f!==c.length)throw new Error(`arx: nonce must be ${f} or 16 bytes`);if(f!==12){const _=new Uint8Array(12);_.set(c,n?0:12-c.length),c=_,g.push(c)}const E=Mt(c);return Rg(i,d,m,E,h,l,u,o),Yi(...g),l}}const Oe=(i,e)=>i[e++]&255|(i[e++]&255)<<8;let Tg=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=co(e),Je(e,32);const t=Oe(e,0),s=Oe(e,2),r=Oe(e,4),n=Oe(e,6),o=Oe(e,8),a=Oe(e,10),c=Oe(e,12),h=Oe(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>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|c<<5)&8065,this.r[8]=(c>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Oe(e,16+2*l)}process(e,t,s=!1){const r=s?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],l=o[3],u=o[4],p=o[5],g=o[6],w=o[7],y=o[8],d=o[9],m=Oe(e,t+0),f=Oe(e,t+2),E=Oe(e,t+4),_=Oe(e,t+6),C=Oe(e,t+8),O=Oe(e,t+10),P=Oe(e,t+12),R=Oe(e,t+14);let S=n[0]+(m&8191),U=n[1]+((m>>>13|f<<3)&8191),N=n[2]+((f>>>10|E<<6)&8191),B=n[3]+((E>>>7|_<<9)&8191),j=n[4]+((_>>>4|C<<12)&8191),b=n[5]+(C>>>1&8191),I=n[6]+((C>>>14|O<<2)&8191),$=n[7]+((O>>>11|P<<5)&8191),A=n[8]+((P>>>8|R<<8)&8191),T=n[9]+(R>>>5|r),x=0,q=x+S*a+U*(5*d)+N*(5*y)+B*(5*w)+j*(5*g);x=q>>>13,q&=8191,q+=b*(5*p)+I*(5*u)+$*(5*l)+A*(5*h)+T*(5*c),x+=q>>>13,q&=8191;let k=x+S*c+U*a+N*(5*d)+B*(5*y)+j*(5*w);x=k>>>13,k&=8191,k+=b*(5*g)+I*(5*p)+$*(5*u)+A*(5*l)+T*(5*h),x+=k>>>13,k&=8191;let L=x+S*h+U*c+N*a+B*(5*d)+j*(5*y);x=L>>>13,L&=8191,L+=b*(5*w)+I*(5*g)+$*(5*p)+A*(5*u)+T*(5*l),x+=L>>>13,L&=8191;let M=x+S*l+U*h+N*c+B*a+j*(5*d);x=M>>>13,M&=8191,M+=b*(5*y)+I*(5*w)+$*(5*g)+A*(5*p)+T*(5*u),x+=M>>>13,M&=8191;let F=x+S*u+U*l+N*h+B*c+j*a;x=F>>>13,F&=8191,F+=b*(5*d)+I*(5*y)+$*(5*w)+A*(5*g)+T*(5*p),x+=F>>>13,F&=8191;let H=x+S*p+U*u+N*l+B*h+j*c;x=H>>>13,H&=8191,H+=b*a+I*(5*d)+$*(5*y)+A*(5*w)+T*(5*g),x+=H>>>13,H&=8191;let K=x+S*g+U*p+N*u+B*l+j*h;x=K>>>13,K&=8191,K+=b*c+I*a+$*(5*d)+A*(5*y)+T*(5*w),x+=K>>>13,K&=8191;let Z=x+S*w+U*g+N*p+B*u+j*l;x=Z>>>13,Z&=8191,Z+=b*h+I*c+$*a+A*(5*d)+T*(5*y),x+=Z>>>13,Z&=8191;let G=x+S*y+U*w+N*g+B*p+j*u;x=G>>>13,G&=8191,G+=b*l+I*h+$*c+A*a+T*(5*d),x+=G>>>13,G&=8191;let W=x+S*d+U*y+N*w+B*g+j*p;x=W>>>13,W&=8191,W+=b*u+I*l+$*h+A*c+T*a,x+=W>>>13,W&=8191,x=(x<<2)+x|0,x=x+q|0,q=x&8191,x=x>>>13,k+=x,n[0]=q,n[1]=k,n[2]=L,n[3]=M,n[4]=F,n[5]=H,n[6]=K,n[7]=Z,n[8]=G,n[9]=W}finalize(){const{h:e,pad:t}=this,s=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,s[0]=e[0]+5,r=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+r,r=s[a]>>>13,s[a]&=8191;s[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)s[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|s[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;Yi(s)}update(e){Ka(this);const{buffer:t,blockLen:s}=this;e=co(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o===s){for(;s<=r-n;n+=s)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Yi(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ka(this),wg(e,this),this.finished=!0;const{buffer:t,h:s}=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++]=s[o]>>>0,e[n++]=s[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}};function Cg(i){const e=(s,r)=>i(r).update(co(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const Bg=Cg(i=>new Tg(i));function Ug(i,e,t,s,r,n=20){let o=i[0],a=i[1],c=i[2],h=i[3],l=e[0],u=e[1],p=e[2],g=e[3],w=e[4],y=e[5],d=e[6],m=e[7],f=r,E=t[0],_=t[1],C=t[2],O=o,P=a,R=c,S=h,U=l,N=u,B=p,j=g,b=w,I=y,$=d,A=m,T=f,x=E,q=_,k=C;for(let M=0;M<n;M+=2)O=O+U|0,T=X(T^O,16),b=b+T|0,U=X(U^b,12),O=O+U|0,T=X(T^O,8),b=b+T|0,U=X(U^b,7),P=P+N|0,x=X(x^P,16),I=I+x|0,N=X(N^I,12),P=P+N|0,x=X(x^P,8),I=I+x|0,N=X(N^I,7),R=R+B|0,q=X(q^R,16),$=$+q|0,B=X(B^$,12),R=R+B|0,q=X(q^R,8),$=$+q|0,B=X(B^$,7),S=S+j|0,k=X(k^S,16),A=A+k|0,j=X(j^A,12),S=S+j|0,k=X(k^S,8),A=A+k|0,j=X(j^A,7),O=O+N|0,k=X(k^O,16),$=$+k|0,N=X(N^$,12),O=O+N|0,k=X(k^O,8),$=$+k|0,N=X(N^$,7),P=P+B|0,T=X(T^P,16),A=A+T|0,B=X(B^A,12),P=P+B|0,T=X(T^P,8),A=A+T|0,B=X(B^A,7),R=R+j|0,x=X(x^R,16),b=b+x|0,j=X(j^b,12),R=R+j|0,x=X(x^R,8),b=b+x|0,j=X(j^b,7),S=S+U|0,q=X(q^S,16),I=I+q|0,U=X(U^I,12),S=S+U|0,q=X(q^S,8),I=I+q|0,U=X(U^I,7);let L=0;s[L++]=o+O|0,s[L++]=a+P|0,s[L++]=c+R|0,s[L++]=h+S|0,s[L++]=l+U|0,s[L++]=u+N|0,s[L++]=p+B|0,s[L++]=g+j|0,s[L++]=w+b|0,s[L++]=y+I|0,s[L++]=d+$|0,s[L++]=m+A|0,s[L++]=f+T|0,s[L++]=E+x|0,s[L++]=_+q|0,s[L++]=C+k|0}const jg=Ng(Ug,{counterRight:!1,counterLength:4,allowShortKeys:!1}),qg=new Uint8Array(16),Ya=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(qg.subarray(t))},kg=new Uint8Array(32);function Qa(i,e,t,s,r){const n=i(e,t,kg),o=Bg.create(n);r&&Ya(o,r),Ya(o,s);const a=new Uint8Array(16),c=mg(a);Za(c,0,BigInt(r?r.length:0),!0),Za(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return Yi(n,a),h}const Lg=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=Wa(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=Qa(i,e,t,a,s);return n.set(c,o),Yi(c),n},decrypt(r,n){n=Wa(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Qa(i,e,t,o,s);if(!$g(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),Yi(c),n}}),Tl=Ig({blockSize:64,nonceLength:12,tagLength:16},Lg(jg));let Cl=class extends Qo{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Yo(e);const s=Ji(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(s.length>r?e.create().update(s).digest():s);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 Zi(this),this.iHash.update(e),this}digestInto(e){Zi(this),Zs(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:s,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=s._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const zr=(i,e,t)=>new Cl(i,e).update(t).digest();zr.create=(i,e)=>new Cl(i,e);function Dg(i,e,t){return Yo(i),t===void 0&&(t=new Uint8Array(i.outputLen)),zr(i,Ji(t),Ji(e))}const mn=new Uint8Array([0]),Xa=new Uint8Array;function Fg(i,e,t,s=32){if(Yo(i),qs(s),s>255*i.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(s/i.outputLen);t===void 0&&(t=Xa);const n=new Uint8Array(r*i.outputLen),o=zr.create(i,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let h=0;h<r;h++)mn[0]=h+1,a.update(h===0?Xa:c).update(t).update(mn).digestInto(c),n.set(c,i.outputLen*h),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),mn.fill(0),n.slice(0,s)}const Mg=(i,e,t,s,r)=>Fg(i,Dg(i,e,t),s,r);function zg(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=s?4:0,h=s?0:4;i.setUint32(e+c,o,s),i.setUint32(e+h,a,s)}function Hg(i,e,t){return i&e^~i&t}function Vg(i,e,t){return i&e^i&t^e&t}let Kg=class extends Qo{constructor(e,t,s,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=yn(this.buffer)}update(e){Zi(this);const{view:t,buffer:s,blockLen:r}=this;e=Ji(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const c=yn(e);for(;r<=n-o;o+=r)this.process(c,o);continue}s.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){Zi(this),Il(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(s,0),o=0);for(let u=o;u<r;u++)t[u]=0;zg(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=yn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,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(s),e}};const Gg=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]),jt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qt=new Uint32Array(64);let Wg=class extends Kg{constructor(){super(64,32,8,!1),this.A=jt[0]|0,this.B=jt[1]|0,this.C=jt[2]|0,this.D=jt[3]|0,this.E=jt[4]|0,this.F=jt[5]|0,this.G=jt[6]|0,this.H=jt[7]|0}get(){const{A:e,B:t,C:s,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,s,r,n,o,a,c]}set(e,t,s,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)qt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=qt[u-15],g=qt[u-2],w=ft(p,7)^ft(p,18)^p>>>3,y=ft(g,17)^ft(g,19)^g>>>10;qt[u]=y+qt[u-7]+w+qt[u-16]|0}let{A:s,B:r,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let u=0;u<64;u++){const p=ft(a,6)^ft(a,11)^ft(a,25),g=l+p+Hg(a,c,h)+Gg[u]+qt[u]|0,w=(ft(s,2)^ft(s,13)^ft(s,22))+Vg(s,r,n)|0;l=h,h=c,c=a,a=o+g|0,o=n,n=r,r=s,s=g+w|0}s=s+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(s,r,n,o,a,c,h,l)}roundClean(){qt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const Js=Sl(()=>new Wg);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hr=BigInt(0),Vr=BigInt(1),Zg=BigInt(2);function ni(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ys(i){if(!ni(i))throw new Error("Uint8Array expected")}function Qi(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const Jg=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Xi(i){Ys(i);let e="";for(let t=0;t<i.length;t++)e+=Jg[i[t]];return e}function ki(i){const e=i.toString(16);return e.length&1?"0"+e:e}function Xo(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?Hr:BigInt("0x"+i)}const Et={_0:48,_9:57,A:65,F:70,a:97,f:102};function ec(i){if(i>=Et._0&&i<=Et._9)return i-Et._0;if(i>=Et.A&&i<=Et.F)return i-(Et.A-10);if(i>=Et.a&&i<=Et.f)return i-(Et.a-10)}function es(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const s=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=ec(i.charCodeAt(n)),a=ec(i.charCodeAt(n+1));if(o===void 0||a===void 0){const c=i[n]+i[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}s[r]=o*16+a}return s}function ei(i){return Xo(Xi(i))}function ks(i){return Ys(i),Xo(Xi(Uint8Array.from(i).reverse()))}function ts(i,e){return es(i.toString(16).padStart(e*2,"0"))}function Kr(i,e){return ts(i,e).reverse()}function Yg(i){return es(ki(i))}function Ge(i,e,t){let s;if(typeof e=="string")try{s=es(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(ni(e))s=Uint8Array.from(e);else throw new Error(i+" must be hex string or Uint8Array");const r=s.length;if(typeof t=="number"&&r!==t)throw new Error(i+" of length "+t+" expected, got "+r);return s}function Ls(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Ys(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}function Qg(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}function Xg(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const bn=i=>typeof i=="bigint"&&Hr<=i;function Gr(i,e,t){return bn(i)&&bn(e)&&bn(t)&&e<=i&&i<t}function Tt(i,e,t,s){if(!Gr(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function Bl(i){let e;for(e=0;i>Hr;i>>=Vr,e+=1);return e}function ey(i,e){return i>>BigInt(e)&Vr}function ty(i,e,t){return i|(t?Vr:Hr)<<BigInt(e)}const ea=i=>(Zg<<BigInt(i-1))-Vr,vn=i=>new Uint8Array(i),tc=i=>Uint8Array.from(i);function Ul(i,e,t){if(typeof i!="number"||i<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let s=vn(i),r=vn(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=vn())=>{r=a(tc([0]),l),s=a(),l.length!==0&&(r=a(tc([1]),l),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const u=[];for(;l<e;){s=a();const p=s.slice();u.push(p),l+=s.length}return Ls(...u)};return(l,u)=>{o(),c(l);let p;for(;!(p=u(h()));)c();return o(),p}}const iy={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||ni(i),isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function ls(i,e,t={}){const s=(r,n,o)=>{const a=iy[n];if(typeof a!="function")throw new Error("invalid validator function");const c=i[r];if(!(o&&c===void 0)&&!a(c,i))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))s(r,n,!1);for(const[r,n]of Object.entries(t))s(r,n,!0);return i}const sy=()=>{throw new Error("not implemented")};function uo(i){const e=new WeakMap;return(t,...s)=>{const r=e.get(t);if(r!==void 0)return r;const n=i(t,...s);return e.set(t,n),n}}var ry=Object.freeze({__proto__:null,isBytes:ni,abytes:Ys,abool:Qi,bytesToHex:Xi,numberToHexUnpadded:ki,hexToNumber:Xo,hexToBytes:es,bytesToNumberBE:ei,bytesToNumberLE:ks,numberToBytesBE:ts,numberToBytesLE:Kr,numberToVarBytesBE:Yg,ensureBytes:Ge,concatBytes:Ls,equalBytes:Qg,utf8ToBytes:Xg,inRange:Gr,aInRange:Tt,bitLen:Bl,bitGet:ey,bitSet:ty,bitMask:ea,createHmacDrbg:Ul,validateObject:ls,notImplemented:sy,memoized:uo});const xe=BigInt(0),fe=BigInt(1),Wt=BigInt(2),ny=BigInt(3),po=BigInt(4),ic=BigInt(5),sc=BigInt(8);function De(i,e){const t=i%e;return t>=xe?t:e+t}function jl(i,e,t){if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(t<=xe)throw new Error("invalid modulus");if(t===fe)return xe;let s=fe;for(;e>xe;)e&fe&&(s=s*i%t),i=i*i%t,e>>=fe;return s}function ht(i,e,t){let s=i;for(;e-- >xe;)s*=s,s%=t;return s}function fo(i,e){if(i===xe)throw new Error("invert: expected non-zero number");if(e<=xe)throw new Error("invert: expected positive modulus, got "+e);let t=De(i,e),s=e,r=xe,n=fe;for(;t!==xe;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==fe)throw new Error("invert: does not exist");return De(r,e)}function oy(i){const e=(i-fe)/Wt;let t,s,r;for(t=i-fe,s=0;t%Wt===xe;t/=Wt,s++);for(r=Wt;r<i&&jl(r,e,i)!==i-fe;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+fe)/po;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(t+fe)/Wt;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=s,h=o.pow(o.mul(o.ONE,r),t),l=o.pow(a,n),u=o.pow(a,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let p=1;for(let w=o.sqr(u);p<c&&!o.eql(w,o.ONE);p++)w=o.sqr(w);const g=o.pow(h,fe<<BigInt(c-p-1));h=o.sqr(g),l=o.mul(l,g),u=o.mul(u,h),c=p}return l}}function ay(i){if(i%po===ny){const e=(i+fe)/po;return function(t,s){const r=t.pow(s,e);if(!t.eql(t.sqr(r),s))throw new Error("Cannot find square root");return r}}if(i%sc===ic){const e=(i-ic)/sc;return function(t,s){const r=t.mul(s,Wt),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,Wt),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),s))throw new Error("Cannot find square root");return c}}return oy(i)}const cy=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hy(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=cy.reduce((s,r)=>(s[r]="function",s),e);return ls(i,t)}function ly(i,e,t){if(t<xe)throw new Error("invalid exponent, negatives unsupported");if(t===xe)return i.ONE;if(t===fe)return e;let s=i.ONE,r=e;for(;t>xe;)t&fe&&(s=i.mul(s,r)),r=i.sqr(r),t>>=fe;return s}function uy(i,e){const t=new Array(e.length),s=e.reduce((n,o,a)=>i.is0(o)?n:(t[a]=n,i.mul(n,o)),i.ONE),r=i.inv(s);return e.reduceRight((n,o,a)=>i.is0(o)?n:(t[a]=i.mul(n,t[a]),i.mul(n,o)),r),t}function ql(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function kl(i,e,t=!1,s={}){if(i<=xe)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=ql(i,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:i,isLE:t,BITS:r,BYTES:n,MASK:ea(r),ZERO:xe,ONE:fe,create:c=>De(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return xe<=c&&c<i},is0:c=>c===xe,isOdd:c=>(c&fe)===fe,neg:c=>De(-c,i),eql:(c,h)=>c===h,sqr:c=>De(c*c,i),add:(c,h)=>De(c+h,i),sub:(c,h)=>De(c-h,i),mul:(c,h)=>De(c*h,i),pow:(c,h)=>ly(a,c,h),div:(c,h)=>De(c*fo(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>fo(c,i),sqrt:s.sqrt||(c=>(o||(o=ay(i)),o(a,c))),invertBatch:c=>uy(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?Kr(c,n):ts(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?ks(c):ei(c)}});return Object.freeze(a)}function Ll(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function Dl(i){const e=Ll(i);return e+Math.ceil(e/2)}function dy(i,e,t=!1){const s=i.length,r=Ll(e),n=Dl(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?ks(i):ei(i),a=De(o,e-fe)+fe;return t?Kr(a,r):ts(a,r)}const rc=BigInt(0),hr=BigInt(1);function En(i,e){const t=e.negate();return i?t:e}function Fl(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function $n(i,e){Fl(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function py(i,e){if(!Array.isArray(i))throw new Error("array expected");i.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function fy(i,e){if(!Array.isArray(i))throw new Error("array of scalars expected");i.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}const In=new WeakMap,Ml=new WeakMap;function Sn(i){return Ml.get(i)||1}function gy(i,e){return{constTimeNegate:En,hasPrecomputes(t){return Sn(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>rc;)s&hr&&(r=r.add(n)),n=n.double(),s>>=hr;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=$n(s,e),o=[];let a=t,c=a;for(let h=0;h<r;h++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,s,r){const{windows:n,windowSize:o}=$n(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),l=2**t,u=BigInt(t);for(let p=0;p<n;p++){const g=p*o;let w=Number(r&h);r>>=u,w>o&&(w-=l,r+=hr);const y=g,d=g+Math.abs(w)-1,m=p%2!==0,f=w<0;w===0?c=c.add(En(m,s[y])):a=a.add(En(f,s[d]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=$n(t,e),c=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let u=0;u<o;u++){const p=u*a;if(r===rc)break;let g=Number(r&c);if(r>>=l,g>a&&(g-=h,r+=hr),g===0)continue;let w=s[p+Math.abs(g)-1];g<0&&(w=w.negate()),n=n.add(w)}return n},getPrecomputes(t,s,r){let n=In.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&In.set(s,r(n))),n},wNAFCached(t,s,r){const n=Sn(t);return this.wNAF(n,this.getPrecomputes(n,t,r),s)},wNAFCachedUnsafe(t,s,r,n){const o=Sn(t);return o===1?this.unsafeLadder(t,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,r),s,n)},setWindowSize(t,s){Fl(s,e),Ml.set(t,s),In.delete(t)}}}function yy(i,e,t,s){if(py(t,i),fy(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=Bl(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r),h=Math.floor((e.BITS-1)/o)*o;let l=r;for(let u=h;u>=0;u-=o){c.fill(r);for(let g=0;g<s.length;g++){const w=s[g],y=Number(w>>BigInt(u)&BigInt(a));c[y]=c[y].add(t[g])}let p=r;for(let g=c.length-1,w=r;g>0;g--)w=w.add(c[g]),p=p.add(w);if(l=l.add(p),u!==0)for(let g=0;g<o;g++)l=l.double()}return l}function zl(i){return hy(i.Fp),ls(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ql(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const yi=BigInt(0),xn=BigInt(1);function wy(i){return ls(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function my(i){const e=wy(i),{P:t}=e,s=f=>De(f,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(f=>f),c=e.powPminus2||(f=>jl(f,t-BigInt(2),t));function h(f,E,_){const C=s(f*(E-_));return E=s(E-C),_=s(_+C),[E,_]}const l=(e.a-BigInt(2))/BigInt(4);function u(f,E){Tt("u",f,yi,t),Tt("scalar",E,yi,t);const _=E,C=f;let O=xn,P=yi,R=f,S=xn,U=yi,N;for(let j=BigInt(r-1);j>=yi;j--){const b=_>>j&xn;U^=b,N=h(U,O,R),O=N[0],R=N[1],N=h(U,P,S),P=N[0],S=N[1],U=b;const I=O+P,$=s(I*I),A=O-P,T=s(A*A),x=$-T,q=R+S,k=R-S,L=s(k*I),M=s(q*A),F=L+M,H=L-M;R=s(F*F),S=s(C*s(H*H)),O=s($*T),P=s(x*($+s(l*x)))}N=h(U,O,R),O=N[0],R=N[1],N=h(U,P,S),P=N[0],S=N[1];const B=c(P);return s(O*B)}function p(f){return Kr(s(f),n)}function g(f){const E=Ge("u coordinate",f,n);return o===32&&(E[31]&=127),ks(E)}function w(f){const E=Ge("scalar",f),_=E.length;if(_!==n&&_!==o){let C=""+n+" or "+o;throw new Error("invalid scalar, expected "+C+" bytes, got "+_)}return ks(a(E))}function y(f,E){const _=g(E),C=w(f),O=u(_,C);if(O===yi)throw new Error("invalid private or public key received");return p(O)}const d=p(e.Gu);function m(f){return y(f,d)}return{scalarMult:y,scalarMultBase:m,getSharedSecret:(f,E)=>y(f,E),getPublicKey:f=>m(f),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:d}}const go=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const by=BigInt(1),nc=BigInt(2),vy=BigInt(3),Ey=BigInt(5);BigInt(8);function $y(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=go,o=i*i%n*i%n,a=ht(o,nc,n)*o%n,c=ht(a,by,n)*i%n,h=ht(c,Ey,n)*c%n,l=ht(h,e,n)*h%n,u=ht(l,t,n)*l%n,p=ht(u,s,n)*u%n,g=ht(p,r,n)*p%n,w=ht(g,r,n)*p%n,y=ht(w,e,n)*h%n;return{pow_p_5_8:ht(y,nc,n)*i%n,b2:o}}function Iy(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}const yo=my({P:go,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=go,{pow_p_5_8:t,b2:s}=$y(i);return De(ht(t,vy,e)*s,e)},adjustScalarBytes:Iy,randomBytes:hs});function oc(i){i.lowS!==void 0&&Qi("lowS",i.lowS),i.prehash!==void 0&&Qi("prehash",i.prehash)}function Sy(i){const e=zl(i);ls(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:s,a:r}=e;if(t){if(!s.eql(r,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:xy,hexToBytes:Py}=ry;let _y=class extends Error{constructor(e=""){super(e)}};const Pt={Err:_y,_tlv:{encode:(i,e)=>{const{Err:t}=Pt;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const s=e.length/2,r=ki(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?ki(r.length/2|128):"";return ki(i)+n+r+e},decode(i,e){const{Err:t}=Pt;let s=0;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==i)throw new t("tlv.decode: wrong tlv");const r=e[s++],n=!!(r&128);let o=0;if(!n)o=r;else{const c=r&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const h=e.subarray(s,s+c);if(h.length!==c)throw new t("tlv.decode: length bytes not complete");if(h[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const l of h)o=o<<8|l;if(s+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(s,s+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(i){const{Err:e}=Pt;if(i<At)throw new e("integer: negative integers are not allowed");let t=ki(i);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(i){const{Err:e}=Pt;if(i[0]&128)throw new e("invalid signature integer: negative");if(i[0]===0&&!(i[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return xy(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=Pt,r=typeof i=="string"?Py(i):i;Ys(r);const{v:n,l:o}=s.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l}=s.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(h)}},hexFromSig(i){const{_tlv:e,_int:t}=Pt,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},At=BigInt(0),ve=BigInt(1);BigInt(2);const ac=BigInt(3);BigInt(4);function Oy(i){const e=Sy(i),{Fp:t}=e,s=kl(e.n,e.nBitLength),r=e.toBytes||((y,d,m)=>{const f=d.toAffine();return Ls(Uint8Array.from([4]),t.toBytes(f.x),t.toBytes(f.y))}),n=e.fromBytes||(y=>{const d=y.subarray(1),m=t.fromBytes(d.subarray(0,t.BYTES)),f=t.fromBytes(d.subarray(t.BYTES,2*t.BYTES));return{x:m,y:f}});function o(y){const{a:d,b:m}=e,f=t.sqr(y),E=t.mul(f,y);return t.add(t.add(E,t.mul(y,d)),m)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Gr(y,ve,e.n)}function c(y){const{allowedPrivateKeyLengths:d,nByteLength:m,wrapPrivateKey:f,n:E}=e;if(d&&typeof y!="bigint"){if(ni(y)&&(y=Xi(y)),typeof y!="string"||!d.includes(y.length))throw new Error("invalid private key");y=y.padStart(m*2,"0")}let _;try{_=typeof y=="bigint"?y:ei(Ge("private key",y,m))}catch{throw new Error("invalid private key, expected hex or "+m+" bytes, got "+typeof y)}return f&&(_=De(_,E)),Tt("private key",_,ve,E),_}function h(y){if(!(y instanceof p))throw new Error("ProjectivePoint expected")}const l=uo((y,d)=>{const{px:m,py:f,pz:E}=y;if(t.eql(E,t.ONE))return{x:m,y:f};const _=y.is0();d==null&&(d=_?t.ONE:t.inv(E));const C=t.mul(m,d),O=t.mul(f,d),P=t.mul(E,d);if(_)return{x:t.ZERO,y:t.ZERO};if(!t.eql(P,t.ONE))throw new Error("invZ was invalid");return{x:C,y:O}}),u=uo(y=>{if(y.is0()){if(e.allowInfinityPoint&&!t.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:d,y:m}=y.toAffine();if(!t.isValid(d)||!t.isValid(m))throw new Error("bad point: x or y not FE");const f=t.sqr(m),E=o(d);if(!t.eql(f,E))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class p{constructor(d,m,f){if(this.px=d,this.py=m,this.pz=f,d==null||!t.isValid(d))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(f==null||!t.isValid(f))throw new Error("z required");Object.freeze(this)}static fromAffine(d){const{x:m,y:f}=d||{};if(!d||!t.isValid(m)||!t.isValid(f))throw new Error("invalid affine point");if(d instanceof p)throw new Error("projective point not allowed");const E=_=>t.eql(_,t.ZERO);return E(m)&&E(f)?p.ZERO:new p(m,f,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){const m=t.invertBatch(d.map(f=>f.pz));return d.map((f,E)=>f.toAffine(m[E])).map(p.fromAffine)}static fromHex(d){const m=p.fromAffine(n(Ge("pointHex",d)));return m.assertValidity(),m}static fromPrivateKey(d){return p.BASE.multiply(c(d))}static msm(d,m){return yy(p,s,d,m)}_setWindowSize(d){w.setWindowSize(this,d)}assertValidity(){u(this)}hasEvenY(){const{y:d}=this.toAffine();if(t.isOdd)return!t.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){h(d);const{px:m,py:f,pz:E}=this,{px:_,py:C,pz:O}=d,P=t.eql(t.mul(m,O),t.mul(_,E)),R=t.eql(t.mul(f,O),t.mul(C,E));return P&&R}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:d,b:m}=e,f=t.mul(m,ac),{px:E,py:_,pz:C}=this;let O=t.ZERO,P=t.ZERO,R=t.ZERO,S=t.mul(E,E),U=t.mul(_,_),N=t.mul(C,C),B=t.mul(E,_);return B=t.add(B,B),R=t.mul(E,C),R=t.add(R,R),O=t.mul(d,R),P=t.mul(f,N),P=t.add(O,P),O=t.sub(U,P),P=t.add(U,P),P=t.mul(O,P),O=t.mul(B,O),R=t.mul(f,R),N=t.mul(d,N),B=t.sub(S,N),B=t.mul(d,B),B=t.add(B,R),R=t.add(S,S),S=t.add(R,S),S=t.add(S,N),S=t.mul(S,B),P=t.add(P,S),N=t.mul(_,C),N=t.add(N,N),S=t.mul(N,B),O=t.sub(O,S),R=t.mul(N,U),R=t.add(R,R),R=t.add(R,R),new p(O,P,R)}add(d){h(d);const{px:m,py:f,pz:E}=this,{px:_,py:C,pz:O}=d;let P=t.ZERO,R=t.ZERO,S=t.ZERO;const U=e.a,N=t.mul(e.b,ac);let B=t.mul(m,_),j=t.mul(f,C),b=t.mul(E,O),I=t.add(m,f),$=t.add(_,C);I=t.mul(I,$),$=t.add(B,j),I=t.sub(I,$),$=t.add(m,E);let A=t.add(_,O);return $=t.mul($,A),A=t.add(B,b),$=t.sub($,A),A=t.add(f,E),P=t.add(C,O),A=t.mul(A,P),P=t.add(j,b),A=t.sub(A,P),S=t.mul(U,$),P=t.mul(N,b),S=t.add(P,S),P=t.sub(j,S),S=t.add(j,S),R=t.mul(P,S),j=t.add(B,B),j=t.add(j,B),b=t.mul(U,b),$=t.mul(N,$),j=t.add(j,b),b=t.sub(B,b),b=t.mul(U,b),$=t.add($,b),B=t.mul(j,$),R=t.add(R,B),B=t.mul(A,$),P=t.mul(I,P),P=t.sub(P,B),B=t.mul(I,j),S=t.mul(A,S),S=t.add(S,B),new p(P,R,S)}subtract(d){return this.add(d.negate())}is0(){return this.equals(p.ZERO)}wNAF(d){return w.wNAFCached(this,d,p.normalizeZ)}multiplyUnsafe(d){const{endo:m,n:f}=e;Tt("scalar",d,At,f);const E=p.ZERO;if(d===At)return E;if(this.is0()||d===ve)return this;if(!m||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,d,p.normalizeZ);let{k1neg:_,k1:C,k2neg:O,k2:P}=m.splitScalar(d),R=E,S=E,U=this;for(;C>At||P>At;)C&ve&&(R=R.add(U)),P&ve&&(S=S.add(U)),U=U.double(),C>>=ve,P>>=ve;return _&&(R=R.negate()),O&&(S=S.negate()),S=new p(t.mul(S.px,m.beta),S.py,S.pz),R.add(S)}multiply(d){const{endo:m,n:f}=e;Tt("scalar",d,ve,f);let E,_;if(m){const{k1neg:C,k1:O,k2neg:P,k2:R}=m.splitScalar(d);let{p:S,f:U}=this.wNAF(O),{p:N,f:B}=this.wNAF(R);S=w.constTimeNegate(C,S),N=w.constTimeNegate(P,N),N=new p(t.mul(N.px,m.beta),N.py,N.pz),E=S.add(N),_=U.add(B)}else{const{p:C,f:O}=this.wNAF(d);E=C,_=O}return p.normalizeZ([E,_])[0]}multiplyAndAddUnsafe(d,m,f){const E=p.BASE,_=(O,P)=>P===At||P===ve||!O.equals(E)?O.multiplyUnsafe(P):O.multiply(P),C=_(this,m).add(_(d,f));return C.is0()?void 0:C}toAffine(d){return l(this,d)}isTorsionFree(){const{h:d,isTorsionFree:m}=e;if(d===ve)return!0;if(m)return m(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:d,clearCofactor:m}=e;return d===ve?this:m?m(p,this):this.multiplyUnsafe(e.h)}toRawBytes(d=!0){return Qi("isCompressed",d),this.assertValidity(),r(p,this,d)}toHex(d=!0){return Qi("isCompressed",d),Xi(this.toRawBytes(d))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const g=e.nBitLength,w=gy(p,e.endo?Math.ceil(g/2):g);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Ay(i){const e=zl(i);return ls(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Ry(i){const e=Ay(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(b){return De(b,s)}function a(b){return fo(b,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=Oy({...e,toBytes(b,I,$){const A=I.toAffine(),T=t.toBytes(A.x),x=Ls;return Qi("isCompressed",$),$?x(Uint8Array.from([I.hasEvenY()?2:3]),T):x(Uint8Array.from([4]),T,t.toBytes(A.y))},fromBytes(b){const I=b.length,$=b[0],A=b.subarray(1);if(I===r&&($===2||$===3)){const T=ei(A);if(!Gr(T,ve,t.ORDER))throw new Error("Point is not on curve");const x=l(T);let q;try{q=t.sqrt(x)}catch(L){const M=L instanceof Error?": "+L.message:"";throw new Error("Point is not on curve"+M)}const k=(q&ve)===ve;return($&1)===1!==k&&(q=t.neg(q)),{x:T,y:q}}else if(I===n&&$===4){const T=t.fromBytes(A.subarray(0,t.BYTES)),x=t.fromBytes(A.subarray(t.BYTES,2*t.BYTES));return{x:T,y:x}}else{const T=r,x=n;throw new Error("invalid Point, expected length of "+T+", or uncompressed "+x+", got "+I)}}}),p=b=>Xi(ts(b,e.nByteLength));function g(b){const I=s>>ve;return b>I}function w(b){return g(b)?o(-b):b}const y=(b,I,$)=>ei(b.slice(I,$));class d{constructor(I,$,A){this.r=I,this.s=$,this.recovery=A,this.assertValidity()}static fromCompact(I){const $=e.nByteLength;return I=Ge("compactSignature",I,$*2),new d(y(I,0,$),y(I,$,2*$))}static fromDER(I){const{r:$,s:A}=Pt.toSig(Ge("DER",I));return new d($,A)}assertValidity(){Tt("r",this.r,ve,s),Tt("s",this.s,ve,s)}addRecoveryBit(I){return new d(this.r,this.s,I)}recoverPublicKey(I){const{r:$,s:A,recovery:T}=this,x=O(Ge("msgHash",I));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");const q=T===2||T===3?$+e.n:$;if(q>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const k=(T&1)===0?"02":"03",L=c.fromHex(k+p(q)),M=a(q),F=o(-x*M),H=o(A*M),K=c.BASE.multiplyAndAddUnsafe(L,F,H);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new d(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return es(this.toDERHex())}toDERHex(){return Pt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return es(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const m={isValidPrivateKey(b){try{return h(b),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const b=Dl(e.n);return dy(e.randomBytes(b),e.n)},precompute(b=8,I=c.BASE){return I._setWindowSize(b),I.multiply(BigInt(3)),I}};function f(b,I=!0){return c.fromPrivateKey(b).toRawBytes(I)}function E(b){const I=ni(b),$=typeof b=="string",A=(I||$)&&b.length;return I?A===r||A===n:$?A===2*r||A===2*n:b instanceof c}function _(b,I,$=!0){if(E(b))throw new Error("first arg must be private key");if(!E(I))throw new Error("second arg must be public key");return c.fromHex(I).multiply(h(b)).toRawBytes($)}const C=e.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const I=ei(b),$=b.length*8-e.nBitLength;return $>0?I>>BigInt($):I},O=e.bits2int_modN||function(b){return o(C(b))},P=ea(e.nBitLength);function R(b){return Tt("num < 2^"+e.nBitLength,b,At,P),ts(b,e.nByteLength)}function S(b,I,$=U){if(["recovered","canonical"].some(G=>G in $))throw new Error("sign() legacy options not supported");const{hash:A,randomBytes:T}=e;let{lowS:x,prehash:q,extraEntropy:k}=$;x==null&&(x=!0),b=Ge("msgHash",b),oc($),q&&(b=Ge("prehashed msgHash",A(b)));const L=O(b),M=h(I),F=[R(M),R(L)];if(k!=null&&k!==!1){const G=k===!0?T(t.BYTES):k;F.push(Ge("extraEntropy",G))}const H=Ls(...F),K=L;function Z(G){const W=C(G);if(!u(W))return;const Be=a(W),ue=c.BASE.multiply(W).toAffine(),ae=o(ue.x);if(ae===At)return;const he=o(Be*o(K+ae*M));if(he===At)return;let Xe=(ue.x===ae?0:2)|Number(ue.y&ve),dt=he;return x&&g(he)&&(dt=w(he),Xe^=1),new d(ae,dt,Xe)}return{seed:H,k2sig:Z}}const U={lowS:e.lowS,prehash:!1},N={lowS:e.lowS,prehash:!1};function B(b,I,$=U){const{seed:A,k2sig:T}=S(b,I,$),x=e;return Ul(x.hash.outputLen,x.nByteLength,x.hmac)(A,T)}c.BASE._setWindowSize(8);function j(b,I,$,A=N){const T=b;I=Ge("msgHash",I),$=Ge("publicKey",$);const{lowS:x,prehash:q,format:k}=A;if(oc(A),"strict"in A)throw new Error("options.strict was renamed to lowS");if(k!==void 0&&k!=="compact"&&k!=="der")throw new Error("format must be compact or der");const L=typeof T=="string"||ni(T),M=!L&&!k&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!L&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,H;try{if(M&&(F=new d(T.r,T.s)),L){try{k!=="compact"&&(F=d.fromDER(T))}catch(he){if(!(he instanceof Pt.Err))throw he}!F&&k!=="der"&&(F=d.fromCompact(T))}H=c.fromHex($)}catch{return!1}if(!F||x&&F.hasHighS())return!1;q&&(I=e.hash(I));const{r:K,s:Z}=F,G=O(I),W=a(Z),Be=o(G*W),ue=o(K*W),ae=c.BASE.multiplyAndAddUnsafe(H,Be,ue)?.toAffine();return ae?o(ae.x)===K:!1}return{CURVE:e,getPublicKey:f,getSharedSecret:_,sign:B,verify:j,ProjectivePoint:c,Signature:d,utils:m}}function Ny(i){return{hash:i,hmac:(e,...t)=>zr(i,e,og(...t)),randomBytes:hs}}function Ty(i,e){const t=s=>Ry({...i,...Ny(s)});return{...t(e),create:t}}const Hl=kl(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Cy=Hl.create(BigInt("-3")),By=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Uy=Ty({a:Cy,b:By,Fp:Hl,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Js),Vl="base10",je="base16",ti="base64pad",ta="base64url",Qs="utf8",Kl=0,us=1,Wr=2,jy=0,cc=1,Ts=12,ia=32;function qy(){const i=yo.utils.randomPrivateKey(),e=yo.getPublicKey(i);return{privateKey:v.toString(i,je),publicKey:v.toString(e,je)}}function wo(){const i=hs(ia);return v.toString(i,je)}function ky(i,e){const t=yo.getSharedSecret(v.fromString(i,je),v.fromString(e,je)),s=Mg(Js,t,void 0,void 0,ia);return v.toString(s,je)}function Ly(i){const e=Js(v.fromString(i,je));return v.toString(e,je)}function $r(i){const e=Js(v.fromString(i,Qs));return v.toString(e,je)}function Gl(i){return v.fromString(`${i}`,Vl)}function oi(i){return Number(v.toString(i,Vl))}function Wl(i){return i.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Zl(i){const e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Dy(i){const e=Gl(typeof i.type<"u"?i.type:Kl);if(oi(e)===us&&typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof i.senderPublicKey<"u"?v.fromString(i.senderPublicKey,je):void 0,s=typeof i.iv<"u"?v.fromString(i.iv,je):hs(Ts),r=v.fromString(i.symKey,je),n=Tl(r,s).encrypt(v.fromString(i.message,Qs)),o=Jl({type:e,sealed:n,iv:s,senderPublicKey:t});return i.encoding===ta?Wl(o):o}function Fy(i){const e=v.fromString(i.symKey,je),{sealed:t,iv:s}=Ds({encoded:i.encoded,encoding:i.encoding}),r=Tl(e,s).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return v.toString(r,Qs)}function My(i,e){const t=Gl(Wr),s=hs(Ts),r=v.fromString(i,Qs),n=Jl({type:t,sealed:r,iv:s});return e===ta?Wl(n):n}function zy(i,e){const{sealed:t}=Ds({encoded:i,encoding:e});return v.toString(t,Qs)}function Jl(i){if(oi(i.type)===Wr)return v.toString(v.concat([i.type,i.sealed]),ti);if(oi(i.type)===us){if(typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return v.toString(v.concat([i.type,i.senderPublicKey,i.iv,i.sealed]),ti)}return v.toString(v.concat([i.type,i.iv,i.sealed]),ti)}function Ds(i){const e=(i.encoding||ti)===ta?Zl(i.encoded):i.encoded,t=v.fromString(e,ti),s=t.slice(jy,cc),r=cc;if(oi(s)===us){const c=r+ia,h=c+Ts,l=t.slice(r,c),u=t.slice(c,h),p=t.slice(h);return{type:s,sealed:p,iv:u,senderPublicKey:l}}if(oi(s)===Wr){const c=t.slice(r),h=hs(Ts);return{type:s,sealed:c,iv:h}}const n=r+Ts,o=t.slice(r,n),a=t.slice(n);return{type:s,sealed:a,iv:o}}function Hy(i,e){const t=Ds({encoded:i,encoding:e?.encoding});return Yl({type:oi(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?v.toString(t.senderPublicKey,je):void 0,receiverPublicKey:e?.receiverPublicKey})}function Yl(i){const e=i?.type||Kl;if(e===us){if(typeof i?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof i?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:i?.senderPublicKey,receiverPublicKey:i?.receiverPublicKey}}function hc(i){return i.type===us&&typeof i.senderPublicKey=="string"&&typeof i.receiverPublicKey=="string"}function lc(i){return i.type===Wr}function Vy(i){const e=z.Buffer.from(i.x,"base64"),t=z.Buffer.from(i.y,"base64");return v.concat([new Uint8Array([4]),e,t])}function Ky(i,e){const[t,s,r]=i.split("."),n=z.Buffer.from(Zl(r),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${t}.${s}`,h=Js(c),l=Vy(e);if(!Uy.verify(v.concat([o,a]),h,l))throw new Error("Invalid signature");return v.sn(i).payload}const Gy="irn";function Ar(i){return i?.relay||{protocol:Gy}}function Os(i){const e=v.C[i];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${i}`);return e}function Wy(i,e="-"){const t={},s="relay"+e;return Object.keys(i).forEach(r=>{if(r.startsWith(s)){const n=r.replace(s,""),o=i[r];t[n]=o}}),t}function uc(i){if(!i.includes("wc:")){const h=$l(i);h!=null&&h.includes("wc:")&&(i=h)}i=i.includes("wc://")?i.replace("wc://",""):i,i=i.includes("wc:")?i.replace("wc:",""):i;const e=i.indexOf(":"),t=i.indexOf("?")!==-1?i.indexOf("?"):void 0,s=i.substring(0,e),r=i.substring(e+1,t).split("@"),n=typeof t<"u"?i.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((h,l)=>{a[l]=h});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:s,topic:Zy(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:Wy(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Zy(i){return i.startsWith("//")?i.substring(2):i}function Jy(i,e="-"){const t="relay",s={};return Object.keys(i).forEach(r=>{const n=r,o=t+e+n;i[n]&&(s[o]=i[n])}),s}function dc(i){const e=new URLSearchParams,t=Jy(i.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",i.symKey),i.expiryTimestamp&&e.set("expiryTimestamp",i.expiryTimestamp.toString()),i.methods&&e.set("methods",i.methods.join(","));const s=e.toString();return`${i.protocol}:${i.topic}@${i.version}?${s}`}const Yy={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}},Qy={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 se(i,e){const{message:t,code:s}=Qy[i];return{message:e?`${t} ${e}`:t,code:s}}function As(i,e){const{message:t,code:s}=Yy[i];return{message:e?`${t} ${e}`:t,code:s}}function mo(i){return typeof i>"u"}function Ql(i,e){return typeof i=="string"&&!!i.trim().length}function Xy(i){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(Ql(i,!1)){if(e(i))return!0;const t=$l(i);return e(t)}}catch{}return!1}function ew(i){var e;return(e=i?.proposer)==null?void 0:e.publicKey}function tw(i){return i?.topic}function Pn(i){return typeof i<"u"&&typeof i!==null}function pc(){const i=Mr();return new Promise(e=>{switch(i){case ut.browser:e(iw());break;case ut.reactNative:e(sw());break;case ut.node:e(rw());break;default:e(!0)}})}function iw(){return Ws()&&navigator?.onLine}async function sw(){return li()&&typeof z.global<"u"&&z.global!=null&&z.global.NetInfo?(await(z.global==null?void 0:z.global.NetInfo.fetch()))?.isConnected:!0}function rw(){return!0}function nw(i){switch(Mr()){case ut.browser:ow(i);break;case ut.reactNative:aw(i);break}}function ow(i){!li()&&Ws()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function aw(i){li()&&typeof z.global<"u"&&z.global!=null&&z.global.NetInfo&&z.global?.NetInfo.addEventListener(e=>i(e?.isConnected))}function cw(){var i;return Ws()&&v.cjsExports$2.getDocument()?((i=v.cjsExports$2.getDocument())==null?void 0:i.visibilityState)==="visible":!0}const Xl="wc",eu=2,bo="core",bt=`${Xl}@2:${bo}:`,hw={logger:"error"},lw={database:":memory:"},uw="crypto",fc="client_ed25519_seed",dw=v.cjsExports$1.ONE_DAY,pw="keychain",fw="0.3",gw="messages",yw="0.3",gc=v.cjsExports$1.SIX_HOURS,ww="publisher",tu="irn",mw="error",iu="wss://relay.walletconnect.org",bw="relayer",Ie={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"},vw="_subscription",et={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Ew=.1,vo="2.21.1",le={link_mode:"link_mode",relay:"relay"},Ir={inbound:"inbound",outbound:"outbound"},$w="0.3",Iw="WALLETCONNECT_CLIENT_ID",yc="WALLETCONNECT_LINK_MODE_APPS",Ve={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Sw="subscription",xw="0.3",Pw="pairing",_w="0.3",ms={wc_pairingDelete:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:v.cjsExports$1.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:v.cjsExports$1.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:0},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:0}}},Zt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},rt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Ow="history",Aw="0.3",Rw="expirer",it={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Nw="0.3",Tw="verify-api",Cw="https://verify.walletconnect.com",su="https://verify.walletconnect.org",Cs=su,Bw=`${Cs}/v3`,Uw=[Cw,su],jw="echo",qw="https://echo.walletconnect.com",mt={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},St={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"},nt={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"},Ht={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"},Vt={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"},bs={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"},kw=.1,Lw="event-client",Dw=86400,Fw="https://pulse.walletconnect.org/batch";function Mw(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var r=0;r<i.length;r++){var n=i.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=i.length,c=i.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.byteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var y=0,d=0,m=0,f=w.length;m!==f&&w[m]===0;)m++,y++;for(var E=(f-m)*l+1>>>0,_=new Uint8Array(E);m!==f;){for(var C=w[m],O=0,P=E-1;(C!==0||O<d)&&P!==-1;P--,O++)C+=256*_[P]>>>0,_[P]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");d=O,m++}for(var R=E-d;R!==E&&_[R]===0;)R++;for(var S=c.repeat(y);R<E;++R)S+=i.charAt(_[R]);return S}function p(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var y=0;if(w[y]!==" "){for(var d=0,m=0;w[y]===c;)d++,y++;for(var f=(w.length-y)*h+1>>>0,E=new Uint8Array(f);w[y];){var _=t[w.charCodeAt(y)];if(_===255)return;for(var C=0,O=f-1;(_!==0||C<m)&&O!==-1;O--,C++)_+=a*E[O]>>>0,E[O]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");m=C,y++}if(w[y]!==" "){for(var P=f-m;P!==f&&E[P]===0;)P++;for(var R=new Uint8Array(d+(f-P)),S=d;P!==f;)R[S++]=E[P++];return R}}}function g(w){var y=p(w);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:g}}var zw=Mw,Hw=zw;const ru=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},Vw=i=>new TextEncoder().encode(i),Kw=i=>new TextDecoder().decode(i);let Gw=class{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ww=class{constructor(e,t,s){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=s}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 nu(this,e)}},Zw=class{constructor(e){this.decoders=e}or(e){return nu(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const nu=(i,e)=>new Zw({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});let Jw=class{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Gw(e,t,s),this.decoder=new Ww(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Zr=({name:i,prefix:e,encode:t,decode:s})=>new Jw(i,e,t,s),Xs=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=Hw(t,e);return Zr({prefix:i,name:e,encode:s,decode:n=>ru(r(n))})},Yw=(i,e,t,s)=>{const r={};for(let l=0;l<e.length;++l)r[e[l]]=l;let n=i.length;for(;i[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const u=r[i[l]];if(u===void 0)throw new SyntaxError(`Non-${s} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Qw=(i,e,t)=>{const s=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),s)for(;n.length*t&7;)n+="=";return n},Te=({name:i,prefix:e,bitsPerChar:t,alphabet:s})=>Zr({prefix:e,name:i,encode(r){return Qw(r,s,t)},decode(r){return Yw(r,s,t,i)}}),Xw=Zr({prefix:"\0",name:"identity",encode:i=>Kw(i),decode:i=>Vw(i)});var em=Object.freeze({__proto__:null,identity:Xw});const tm=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var im=Object.freeze({__proto__:null,base2:tm});const sm=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var rm=Object.freeze({__proto__:null,base8:sm});const nm=Xs({prefix:"9",name:"base10",alphabet:"0123456789"});var om=Object.freeze({__proto__:null,base10:nm});const am=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),cm=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hm=Object.freeze({__proto__:null,base16:am,base16upper:cm});const lm=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),um=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),dm=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pm=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fm=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gm=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ym=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wm=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),mm=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var bm=Object.freeze({__proto__:null,base32:lm,base32upper:um,base32pad:dm,base32padupper:pm,base32hex:fm,base32hexupper:gm,base32hexpad:ym,base32hexpadupper:wm,base32z:mm});const vm=Xs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Em=Xs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $m=Object.freeze({__proto__:null,base36:vm,base36upper:Em});const Im=Xs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sm=Xs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xm=Object.freeze({__proto__:null,base58btc:Im,base58flickr:Sm});const Pm=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_m=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Om=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Am=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Rm=Object.freeze({__proto__:null,base64:Pm,base64pad:_m,base64url:Om,base64urlpad:Am});const ou=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Nm=ou.reduce((i,e,t)=>(i[t]=e,i),[]),Tm=ou.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function Cm(i){return i.reduce((e,t)=>(e+=Nm[t],e),"")}function Bm(i){const e=[];for(const t of i){const s=Tm[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const Um=Zr({prefix:"🚀",name:"base256emoji",encode:Cm,decode:Bm});var jm=Object.freeze({__proto__:null,base256emoji:Um}),qm=au,wc=128,km=-128,Lm=Math.pow(2,31);function au(i,e,t){e=e||[],t=t||0;for(var s=t;i>=Lm;)e[t++]=i&255|wc,i/=128;for(;i&km;)e[t++]=i&255|wc,i>>>=7;return e[t]=i|0,au.bytes=t-s+1,e}var Dm=Eo,Fm=128,mc=127;function Eo(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw Eo.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&mc)<<r:(o&mc)*Math.pow(2,r),r+=7}while(o>=Fm);return Eo.bytes=n-s,t}var Mm=Math.pow(2,7),zm=Math.pow(2,14),Hm=Math.pow(2,21),Vm=Math.pow(2,28),Km=Math.pow(2,35),Gm=Math.pow(2,42),Wm=Math.pow(2,49),Zm=Math.pow(2,56),Jm=Math.pow(2,63),Ym=function(i){return i<Mm?1:i<zm?2:i<Hm?3:i<Vm?4:i<Km?5:i<Gm?6:i<Wm?7:i<Zm?8:i<Jm?9:10},Qm={encode:qm,decode:Dm,encodingLength:Ym},cu=Qm;const bc=(i,e,t=0)=>(cu.encode(i,e,t),e),vc=i=>cu.encodingLength(i),$o=(i,e)=>{const t=e.byteLength,s=vc(i),r=s+vc(t),n=new Uint8Array(r+t);return bc(i,n,0),bc(t,n,s),n.set(e,r),new Xm(i,t,e,n)};let Xm=class{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}};const hu=({name:i,code:e,encode:t})=>new eb(i,e,t);class eb{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?$o(this.code,t):t.then(s=>$o(this.code,s))}else throw Error("Unknown type, must be binary type")}}const lu=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),tb=hu({name:"sha2-256",code:18,encode:lu("SHA-256")}),ib=hu({name:"sha2-512",code:19,encode:lu("SHA-512")});var sb=Object.freeze({__proto__:null,sha256:tb,sha512:ib});const uu=0,rb="identity",du=ru,nb=i=>$o(uu,du(i)),ob={code:uu,name:rb,encode:du,digest:nb};var ab=Object.freeze({__proto__:null,identity:ob});new TextEncoder,new TextDecoder;const Ec={...em,...im,...rm,...om,...hm,...bm,...$m,...xm,...Rm,...jm};({...sb,...ab});function cb(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function pu(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const $c=pu("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),_n=pu("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=cb(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),hb={utf8:$c,"utf-8":$c,hex:Ec.base16,latin1:_n,ascii:_n,binary:_n,...Ec};function lb(i,e="utf8"){const t=hb[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(i,"utf8"):t.decoder.decode(`${t.prefix}${i}`)}var ub=Object.defineProperty,db=(i,e,t)=>e in i?ub(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,gt=(i,e,t)=>db(i,typeof e!="symbol"?e+"":e,t);let pb=class{constructor(e,t){this.core=e,this.logger=t,gt(this,"keychain",new Map),gt(this,"name",pw),gt(this,"version",fw),gt(this,"initialized",!1),gt(this,"storagePrefix",bt),gt(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),gt(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),gt(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),gt(this,"get",s=>{this.isInitialized();const r=this.keychain.get(s);if(typeof r>"u"){const{message:n}=se("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(n)}return r}),gt(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=v.E(t,this.name)}get context(){return v.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,oo(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ao(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var fb=Object.defineProperty,gb=(i,e,t)=>e in i?fb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ae=(i,e,t)=>gb(i,typeof e!="symbol"?e+"":e,t);let yb=class{constructor(e,t,s){this.core=e,this.logger=t,Ae(this,"name",uw),Ae(this,"keychain"),Ae(this,"randomSessionIdentifier",wo()),Ae(this,"initialized",!1),Ae(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ae(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ae(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=v.Po(r);return v.Qe(n.publicKey)}),Ae(this,"generateKeyPair",()=>{this.isInitialized();const r=qy();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ae(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=v.Po(n),a=this.randomSessionIdentifier,c=dw;return await v.Qo(a,r,c,o)}),Ae(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=ky(a,n);return this.setSymKey(c,o)}),Ae(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||Ly(r);return await this.keychain.set(o,r),o}),Ae(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ae(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ae(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Yl(o),c=v.safeJsonStringify(n);if(lc(a))return My(c,o?.encoding);if(hc(a)){const p=a.senderPublicKey,g=a.receiverPublicKey;r=await this.generateSharedKey(p,g)}const h=this.getSymKey(r),{type:l,senderPublicKey:u}=a;return Dy({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o?.encoding})}),Ae(this,"decode",async(r,n,o)=>{this.isInitialized();const a=Hy(n,o);if(lc(a)){const c=zy(n,o?.encoding);return v.safeJsonParse(c)}if(hc(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=Fy({symKey:c,encoded:n,encoding:o?.encoding});return v.safeJsonParse(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ae(this,"getPayloadType",(r,n=ti)=>{const o=Ds({encoded:r,encoding:n});return oi(o.type)}),Ae(this,"getPayloadSenderPublicKey",(r,n=ti)=>{const o=Ds({encoded:r,encoding:n});return o.senderPublicKey?v.toString(o.senderPublicKey,je):void 0}),this.core=e,this.logger=v.E(t,this.name),this.keychain=s||new pb(this.core,this.logger)}get context(){return v.y(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(fc)}catch{e=wo(),await this.keychain.set(fc,e)}return lb(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var wb=Object.defineProperty,mb=Object.defineProperties,bb=Object.getOwnPropertyDescriptors,Ic=Object.getOwnPropertySymbols,vb=Object.prototype.hasOwnProperty,Eb=Object.prototype.propertyIsEnumerable,Io=(i,e,t)=>e in i?wb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,$b=(i,e)=>{for(var t in e||(e={}))vb.call(e,t)&&Io(i,t,e[t]);if(Ic)for(var t of Ic(e))Eb.call(e,t)&&Io(i,t,e[t]);return i},Ib=(i,e)=>mb(i,bb(e)),ze=(i,e,t)=>Io(i,typeof e!="symbol"?e+"":e,t);let Sb=class extends Ef{constructor(e,t){super(e,t),this.logger=e,this.core=t,ze(this,"messages",new Map),ze(this,"messagesWithoutClientAck",new Map),ze(this,"name",gw),ze(this,"version",yw),ze(this,"initialized",!1),ze(this,"storagePrefix",bt),ze(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const s=await this.getRelayerMessages();typeof s<"u"&&(this.messages=s);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(s){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(s)}finally{this.initialized=!0}}}),ze(this,"set",async(s,r,n)=>{this.isInitialized();const o=$r(r);let a=this.messages.get(s);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(s,a),n===Ir.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,Ib($b({},c),{[o]:r}))}return await this.persist(),o}),ze(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),ze(this,"getWithoutAck",s=>{this.isInitialized();const r={};for(const n of s){const o=this.messagesWithoutClientAck.get(n)||{};r[n]=Object.values(o)}return r}),ze(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=$r(r);return typeof n[o]<"u"}),ze(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=$r(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),ze(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=v.E(e,this.name),this.core=t}get context(){return v.y(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,oo(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,oo(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ao(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?ao(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var xb=Object.defineProperty,Pb=Object.defineProperties,_b=Object.getOwnPropertyDescriptors,Sc=Object.getOwnPropertySymbols,Ob=Object.prototype.hasOwnProperty,Ab=Object.prototype.propertyIsEnumerable,So=(i,e,t)=>e in i?xb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,lr=(i,e)=>{for(var t in e||(e={}))Ob.call(e,t)&&So(i,t,e[t]);if(Sc)for(var t of Sc(e))Ab.call(e,t)&&So(i,t,e[t]);return i},On=(i,e)=>Pb(i,_b(e)),ot=(i,e,t)=>So(i,typeof e!="symbol"?e+"":e,t);class Rb extends $f{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ot(this,"events",new v.eventsExports.EventEmitter),ot(this,"name",ww),ot(this,"queue",new Map),ot(this,"publishTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_MINUTE)),ot(this,"initialPublishTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_SECOND*15)),ot(this,"needsTransportRestart",!1),ot(this,"publish",async(s,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:s,message:r,opts:n}});const a=n?.ttl||gc,c=Ar(n),h=n?.prompt||!1,l=n?.tag||0,u=n?.id||v.getBigIntRpcId().toString(),p={topic:s,message:r,opts:{ttl:a,relay:c,prompt:h,tag:l,id:u,attestation:n?.attestation,tvf:n?.tvf}},g=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const w=new Promise(async y=>{const d=({id:f})=>{p.opts.id===f&&(this.removeRequestFromQueue(f),this.relayer.events.removeListener(Ie.publish,d),y(p))};this.relayer.events.on(Ie.publish,d);const m=Dt(new Promise((f,E)=>{this.rpcPublish({topic:s,message:r,ttl:a,prompt:h,tag:l,id:u,attestation:n?.attestation,tvf:n?.tvf}).then(f).catch(_=>{this.logger.warn(_,_?.message),E(_)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await m,this.events.removeListener(Ie.publish,d)}catch(f){this.queue.set(u,On(lr({},p),{attempt:1})),this.logger.warn(f,f?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:s,message:r,opts:n}}),await Dt(w,this.publishTimeout,g)}catch(w){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(w),(o=n?.internal)!=null&&o.throwOnFailedPublish)throw w}finally{this.queue.delete(u)}}),ot(this,"on",(s,r)=>{this.events.on(s,r)}),ot(this,"once",(s,r)=>{this.events.once(s,r)}),ot(this,"off",(s,r)=>{this.events.off(s,r)}),ot(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=v.E(t,this.name),this.registerEventListeners()}get context(){return v.y(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=gc,prompt:h,tag:l,id:u,attestation:p,tvf:g}=e,w={method:Os(Ar().protocol).publish,params:lr({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:p},g),id:u};mo((t=w.params)==null?void 0:t.prompt)&&((s=w.params)==null||delete s.prompt),mo((r=w.params)==null?void 0:r.tag)&&((n=w.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w});const y=await this.relayer.request(w);return this.relayer.events.emit(Ie.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,On(lr({},e),{attempt:s}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${s}`),await this.rpcPublish(On(lr({},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(v.r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ie.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ie.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var Nb=Object.defineProperty,Tb=(i,e,t)=>e in i?Nb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,wi=(i,e,t)=>Tb(i,typeof e!="symbol"?e+"":e,t);class Cb{constructor(){wi(this,"map",new Map),wi(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),wi(this,"get",e=>this.map.get(e)||[]),wi(this,"exists",(e,t)=>this.get(e).includes(t)),wi(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const r=s.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),wi(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Bb=Object.defineProperty,Ub=Object.defineProperties,jb=Object.getOwnPropertyDescriptors,xc=Object.getOwnPropertySymbols,qb=Object.prototype.hasOwnProperty,kb=Object.prototype.propertyIsEnumerable,xo=(i,e,t)=>e in i?Bb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vs=(i,e)=>{for(var t in e||(e={}))qb.call(e,t)&&xo(i,t,e[t]);if(xc)for(var t of xc(e))kb.call(e,t)&&xo(i,t,e[t]);return i},An=(i,e)=>Ub(i,jb(e)),re=(i,e,t)=>xo(i,typeof e!="symbol"?e+"":e,t);let Lb=class extends xf{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,re(this,"subscriptions",new Map),re(this,"topicMap",new Cb),re(this,"events",new v.eventsExports.EventEmitter),re(this,"name",Sw),re(this,"version",xw),re(this,"pending",new Map),re(this,"cached",[]),re(this,"initialized",!1),re(this,"storagePrefix",bt),re(this,"subscribeTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_MINUTE)),re(this,"initialSubscribeTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_SECOND*15)),re(this,"clientId"),re(this,"batchSubscribeTopicsLimit",500),re(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),re(this,"subscribe",async(s,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:s,opts:r}});try{const n=Ar(r),o={topic:s,relay:n,transportType:r?.transportType};this.pending.set(s,o);const a=await this.rpcSubscribe(s,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:s,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),re(this,"unsubscribe",async(s,r)=>{this.isInitialized(),typeof r?.id<"u"?await this.unsubscribeById(s,r.id,r):await this.unsubscribeByTopic(s,r)}),re(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),re(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),re(this,"on",(s,r)=>{this.events.on(s,r)}),re(this,"once",(s,r)=>{this.events.once(s,r)}),re(this,"off",(s,r)=>{this.events.off(s,r)}),re(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),re(this,"start",async()=>{await this.onConnect()}),re(this,"stop",async()=>{await this.onDisconnect()}),re(this,"restart",async()=>{await this.restore(),await this.onRestart()}),re(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const s=[];this.pending.forEach(r=>{s.push(r)}),await this.batchSubscribe(s)}),re(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(v.r.pulse,async()=>{await this.checkPending()}),this.events.on(Ve.created,async s=>{const r=Ve.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(Ve.deleted,async s=>{const r=Ve.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=v.E(t,this.name),this.clientId=""}get context(){return v.y(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 s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const r=Ar(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=As("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:s}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,s){var r;(!s||s?.transportType===le.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Os(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=s?.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(s?.transportType===le.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_SECOND)),a;const c=new Promise(async l=>{const u=p=>{p.topic===e&&(this.events.removeListener(Ve.created,u),l(p.id))};this.events.on(Ve.created,u);try{const p=await Dt(new Promise((g,w)=>{this.relayer.request(n).catch(y=>{this.logger.warn(y,y?.message),w(y)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Ve.created,u),l(p)}catch{}}),h=await Dt(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ie.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Os(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await Dt(new Promise(r=>{this.relayer.request(s).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Ie.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Os(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let r;try{r=await await Dt(new Promise((n,o)=>{this.relayer.request(s).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Ie.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:Os(s.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,An(vs({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,vs({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),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,vs({},t)),this.topicMap.set(t.topic,e),this.events.emit(Ve.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:s}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(Ve.deleted,An(vs({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ve.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let s=0;s<t;s++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(Ve.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=se("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=>An(vs({},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 Zf(v.cjsExports$1.toMiliseconds(v.cjsExports$1.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}=se("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 $r(e+await this.getClientId())}};var Db=Object.defineProperty,Pc=Object.getOwnPropertySymbols,Fb=Object.prototype.hasOwnProperty,Mb=Object.prototype.propertyIsEnumerable,Po=(i,e,t)=>e in i?Db(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,_c=(i,e)=>{for(var t in e||(e={}))Fb.call(e,t)&&Po(i,t,e[t]);if(Pc)for(var t of Pc(e))Mb.call(e,t)&&Po(i,t,e[t]);return i},ee=(i,e,t)=>Po(i,typeof e!="symbol"?e+"":e,t);let zb=class extends If{constructor(e){super(e),ee(this,"protocol","wc"),ee(this,"version",2),ee(this,"core"),ee(this,"logger"),ee(this,"events",new v.eventsExports.EventEmitter),ee(this,"provider"),ee(this,"messages"),ee(this,"subscriber"),ee(this,"publisher"),ee(this,"name",bw),ee(this,"transportExplicitlyClosed",!1),ee(this,"initialized",!1),ee(this,"connectionAttemptInProgress",!1),ee(this,"relayUrl"),ee(this,"projectId"),ee(this,"packageName"),ee(this,"bundleId"),ee(this,"hasExperiencedNetworkDisruption",!1),ee(this,"pingTimeout"),ee(this,"heartBeatTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.THIRTY_SECONDS+v.cjsExports$1.FIVE_SECONDS)),ee(this,"reconnectTimeout"),ee(this,"connectPromise"),ee(this,"reconnectInProgress",!1),ee(this,"requestsInFlight",[]),ee(this,"connectTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_SECOND*15)),ee(this,"request",async t=>{var s,r;this.logger.debug("Publishing Request Payload");const n=t.id||v.getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(s=t.params)==null?void 0:s.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(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),ee(this,"resetPingTimeout",()=>{Or()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,s,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(s=(t=this.provider)==null?void 0:t.connection)==null?void 0:s.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),ee(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),ee(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Ie.connect)}),ee(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ee(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(Ie.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ee(this,"registerProviderListeners",()=>{this.provider.on(et.payload,this.onPayloadHandler),this.provider.on(et.connect,this.onConnectHandler),this.provider.on(et.disconnect,this.onDisconnectHandler),this.provider.on(et.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?v.E(e.logger,this.name):v.Ot(v.k({level:e.logger||mw})),this.messages=new Sb(this.logger,e.core),this.subscriber=new Lb(this,this.logger),this.publisher=new Rb(this,this.logger),this.relayUrl=e?.relayUrl||iu,this.projectId=e.projectId,kf()?this.packageName=ka():Lf()&&(this.bundleId=ka()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return v.y(this.logger)}get connected(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===1||!1}get connecting(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:le.relay},Ir.outbound)}async subscribe(e,t){var s,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((s=t?.internal)==null?void 0:s.throwOnFailedPublish)>"u"?!0:(r=t?.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const h=l=>{l.topic===e&&(this.subscriber.off(Ve.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Ve.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,_c({internal:{throwOnFailedPublish:o}},t)).catch(p=>{o&&u(p)})||a,l()})]),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 Dt(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,s)=>{await this.connect(e).then(t).catch(s).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 pc())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((s,r)=>s.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const s of t)try{await this.onMessageEvent(s)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+r?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:s}=e;if(!t.sessionExists){const r=Ns(v.cjsExports$1.FIVE_MINUTES),n={topic:s,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,n)}this.events.emit(Ie.message,e),await this.recordMessageEvent(e,Ir.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(s,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(et.disconnect,n),await Dt(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(et.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(et.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(et.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,s()})}catch(s){await this.subscriber.stop();const r=s;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(s=>setTimeout(s,v.cjsExports$1.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,s,r,n;if(Or())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(s=this.provider)==null?void 0:s.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new v.o(new v.f(Hf({sdkVersion:vo,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:s,message:r}=e;await this.messages.set(s,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||s.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,s);return r&&this.logger.warn(`Ignoring duplicate message: ${s}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),v.isJsonRpcRequest(e)){if(!e.method.endsWith(vw))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:le.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(_c({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else v.isJsonRpcResponse(e)&&this.events.emit(Ie.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Ir.inbound),this.events.emit(Ie.message,e))}async acknowledgePayload(e){const t=v.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(et.payload,this.onPayloadHandler),this.provider.off(et.connect,this.onConnectHandler),this.provider.off(et.disconnect,this.onDisconnectHandler),this.provider.off(et.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await pc();nw(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(s=>this.logger.error(s,s?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(v.r.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&cw())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Ie.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},v.cjsExports$1.toMiliseconds(Ew)))))}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}};function Hb(){}function Oc(i){if(!i||typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(i)==="[object Object]":!1}function Ac(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Rc(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Vb="[object RegExp]",Kb="[object String]",Gb="[object Number]",Wb="[object Boolean]",Nc="[object Arguments]",Zb="[object Symbol]",Jb="[object Date]",Yb="[object Map]",Qb="[object Set]",Xb="[object Array]",e1="[object Function]",t1="[object ArrayBuffer]",Rn="[object Object]",i1="[object Error]",s1="[object DataView]",r1="[object Uint8Array]",n1="[object Uint8ClampedArray]",o1="[object Uint16Array]",a1="[object Uint32Array]",c1="[object BigUint64Array]",h1="[object Int8Array]",l1="[object Int16Array]",u1="[object Int32Array]",d1="[object BigInt64Array]",p1="[object Float32Array]",f1="[object Float64Array]";function g1(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function y1(i,e,t){return Rs(i,e,void 0,void 0,void 0,void 0,t)}function Rs(i,e,t,s,r,n,o){const a=o(i,e,t,s,r,n);if(a!==void 0)return a;if(typeof i==typeof e)switch(typeof i){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return i===e;case"number":return i===e||Object.is(i,e);case"function":return i===e;case"object":return Bs(i,e,n,o)}return Bs(i,e,n,o)}function Bs(i,e,t,s){if(Object.is(i,e))return!0;let r=Rc(i),n=Rc(e);if(r===Nc&&(r=Rn),n===Nc&&(n=Rn),r!==n)return!1;switch(r){case Kb:return i.toString()===e.toString();case Gb:{const c=i.valueOf(),h=e.valueOf();return g1(c,h)}case Wb:case Jb:case Zb:return Object.is(i.valueOf(),e.valueOf());case Vb:return i.source===e.source&&i.flags===e.flags;case e1:return i===e}t=t??new Map;const o=t.get(i),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(i,e),t.set(e,i);try{switch(r){case Yb:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!Rs(h,e.get(c),c,i,e,t,s))return!1;return!0}case Qb:{if(i.size!==e.size)return!1;const c=Array.from(i.values()),h=Array.from(e.values());for(let l=0;l<c.length;l++){const u=c[l],p=h.findIndex(g=>Rs(u,g,void 0,i,e,t,s));if(p===-1)return!1;h.splice(p,1)}return!0}case Xb:case r1:case n1:case o1:case a1:case c1:case h1:case l1:case u1:case d1:case p1:case f1:{if(typeof z.Buffer<"u"&&z.Buffer.isBuffer(i)!==z.Buffer.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!Rs(i[c],e[c],c,i,e,t,s))return!1;return!0}case t1:return i.byteLength!==e.byteLength?!1:Bs(new Uint8Array(i),new Uint8Array(e),t,s);case s1:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:Bs(new Uint8Array(i),new Uint8Array(e),t,s);case i1:return i.name===e.name&&i.message===e.message;case Rn:{if(!(Bs(i.constructor,e.constructor,t,s)||Oc(i)&&Oc(e)))return!1;const c=[...Object.keys(i),...Ac(i)],h=[...Object.keys(e),...Ac(e)];if(c.length!==h.length)return!1;for(let l=0;l<c.length;l++){const u=c[l],p=i[u];if(!Object.hasOwn(e,u))return!1;const g=e[u];if(!Rs(p,g,u,i,e,t,s))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function w1(i,e){return y1(i,e,Hb)}var m1=Object.defineProperty,Tc=Object.getOwnPropertySymbols,b1=Object.prototype.hasOwnProperty,v1=Object.prototype.propertyIsEnumerable,_o=(i,e,t)=>e in i?m1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Cc=(i,e)=>{for(var t in e||(e={}))b1.call(e,t)&&_o(i,t,e[t]);if(Tc)for(var t of Tc(e))v1.call(e,t)&&_o(i,t,e[t]);return i},qe=(i,e,t)=>_o(i,typeof e!="symbol"?e+"":e,t);let ui=class extends Sf{constructor(e,t,s,r=bt,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,qe(this,"map",new Map),qe(this,"version",$w),qe(this,"cached",[]),qe(this,"initialized",!1),qe(this,"getKey"),qe(this,"storagePrefix",bt),qe(this,"recentlyDeleted",[]),qe(this,"recentlyDeletedLimit",200),qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!mo(o)?this.map.set(this.getKey(o),o):ew(o)?this.map.set(o.id,o):tw(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),qe(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())}),qe(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),qe(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>w1(a[c],o[c]))):this.values)),qe(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Cc(Cc({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),qe(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=v.E(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return v.y(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}=se("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:s}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}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}=se("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}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var E1=Object.defineProperty,$1=(i,e,t)=>e in i?E1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,J=(i,e,t)=>$1(i,typeof e!="symbol"?e+"":e,t);let I1=class{constructor(e,t){this.core=e,this.logger=t,J(this,"name",Pw),J(this,"version",_w),J(this,"events",new v.Nt),J(this,"pairings"),J(this,"initialized",!1),J(this,"storagePrefix",bt),J(this,"ignoredPayloadTypes",[us]),J(this,"registeredMethods",[]),J(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),J(this,"register",({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]}),J(this,"create",async s=>{this.isInitialized();const r=wo(),n=await this.core.crypto.setSymKey(r),o=Ns(v.cjsExports$1.FIVE_MINUTES),a={protocol:tu},c={topic:n,expiry:o,relay:a,active:!1,methods:s?.methods},h=dc({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:s?.methods});return this.events.emit(Zt.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:s?.transportType}),{topic:n,uri:h}}),J(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s?.uri,trace:[mt.pairing_started]}});this.isValidPair(s,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=uc(s.uri);r.props.properties.topic=n,r.addTrace(mt.pairing_uri_validation_success),r.addTrace(mt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(mt.existing_pairing),l.active)throw r.setError(St.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(mt.pairing_not_expired)}const u=c||Ns(v.cjsExports$1.FIVE_MINUTES),p={topic:n,relay:a,expiry:u,active:!1,methods:h};this.core.expirer.set(n,u),await this.pairings.set(n,p),r.addTrace(mt.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(Zt.create,p),r.addTrace(mt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(mt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(St.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(g){throw r.setError(St.subscribe_pairing_topic_failure),g}return r.addTrace(mt.subscribe_pairing_topic_success),p}),J(this,"activate",async({topic:s})=>{this.isInitialized();const r=Ns(v.cjsExports$1.FIVE_MINUTES);this.core.expirer.set(s,r),await this.pairings.update(s,{active:!0,expiry:r})}),J(this,"ping",async s=>{this.isInitialized(),await this.isValidPing(s),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=s;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Vf();this.events.once(gn("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),J(this,"updateExpiry",async({topic:s,expiry:r})=>{this.isInitialized(),await this.pairings.update(s,{expiry:r})}),J(this,"updateMetadata",async({topic:s,metadata:r})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:r})}),J(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),J(this,"disconnect",async s=>{this.isInitialized(),await this.isValidDisconnect(s);const{topic:r}=s;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",As("USER_DISCONNECTED")),await this.deletePairing(r))}),J(this,"formatUriFromPairing",s=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=s,c=this.core.crypto.keychain.get(r);return dc({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),J(this,"sendRequest",async(s,r,n)=>{const o=v.formatJsonRpcRequest(r,n),a=await this.core.crypto.encode(s,o),c=ms[r].req;return this.core.history.set(s,o),this.core.relayer.publish(s,a,c),o.id}),J(this,"sendResult",async(s,r,n)=>{const o=v.formatJsonRpcResult(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=ms[c].res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),J(this,"sendError",async(s,r,n)=>{const o=v.formatJsonRpcError(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=ms[c]?ms[c].res:ms.unregistered_method.res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),J(this,"deletePairing",async(s,r)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,As("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),r?Promise.resolve():this.core.expirer.del(s)])}),J(this,"cleanup",async()=>{const s=this.pairings.getAll().filter(r=>La(r.expiry));await Promise.all(s.map(r=>this.deletePairing(r.topic)))}),J(this,"onRelayEventRequest",async s=>{const{topic:r,payload:n}=s;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)}}),J(this,"onRelayEventResponse",async s=>{const{topic:r,payload:n}=s,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)}}),J(this,"onPairingPingRequest",async(s,r)=>{const{id:n}=r;try{this.isValidPing({topic:s}),await this.sendResult(n,s,!0),this.events.emit(Zt.ping,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),J(this,"onPairingPingResponse",(s,r)=>{const{id:n}=r;setTimeout(()=>{v.isJsonRpcResult(r)?this.events.emit(gn("pairing_ping",n),{}):v.isJsonRpcError(r)&&this.events.emit(gn("pairing_ping",n),{error:r.error})},500)}),J(this,"onPairingDeleteRequest",async(s,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(Zt.delete,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),J(this,"onUnknownRpcMethodRequest",async(s,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=As("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,s,a),this.logger.error(a)}catch(a){await this.sendError(n,s,a),this.logger.error(a)}}),J(this,"onUnknownRpcMethodResponse",s=>{this.registeredMethods.includes(s)||this.logger.error(As("WC_METHOD_UNSUPPORTED",s))}),J(this,"isValidPair",(s,r)=>{var n;if(!Pn(s)){const{message:a}=se("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(St.malformed_pairing_uri),new Error(a)}if(!Xy(s.uri)){const{message:a}=se("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(St.malformed_pairing_uri),new Error(a)}const o=uc(s?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=se("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(St.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=se("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(St.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&v.cjsExports$1.toMiliseconds(o?.expiryTimestamp)<Date.now()){r.setError(St.pairing_expired);const{message:a}=se("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),J(this,"isValidPing",async s=>{if(!Pn(s)){const{message:n}=se("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),J(this,"isValidDisconnect",async s=>{if(!Pn(s)){const{message:n}=se("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),J(this,"isValidPairingTopic",async s=>{if(!Ql(s)){const{message:r}=se("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(r)}if(!this.pairings.keys.includes(s)){const{message:r}=se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(r)}if(La(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:r}=se("EXPIRED",`pairing topic: ${s}`);throw new Error(r)}}),this.core=e,this.logger=v.E(t,this.name),this.pairings=new ui(this.core,this.logger,this.name,this.storagePrefix)}get context(){return v.y(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ie.message,async e=>{const{topic:t,message:s,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==le.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);v.isJsonRpcRequest(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):v.isJsonRpcResponse(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,s)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(it.expired,async e=>{const{topic:t}=Wf(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Zt.expire,{topic:t}))})}};var S1=Object.defineProperty,x1=(i,e,t)=>e in i?S1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Re=(i,e,t)=>x1(i,typeof e!="symbol"?e+"":e,t);let P1=class extends vf{constructor(e,t){super(e,t),this.core=e,this.logger=t,Re(this,"records",new Map),Re(this,"events",new v.eventsExports.EventEmitter),Re(this,"name",Ow),Re(this,"version",Aw),Re(this,"cached",[]),Re(this,"initialized",!1),Re(this,"storagePrefix",bt),Re(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.records.set(s.id,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Re(this,"set",(s,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:s,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:s,request:{method:r.method,params:r.params||null},chainId:n,expiry:Ns(v.cjsExports$1.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(rt.created,o)}),Re(this,"resolve",async s=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:s}),!this.records.has(s.id))return;const r=await this.getRecord(s.id);typeof r.response>"u"&&(r.response=v.isJsonRpcError(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(rt.updated,r))}),Re(this,"get",async(s,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:s,id:r}),await this.getRecord(r))),Re(this,"delete",(s,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===s){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(rt.deleted,n)}}),this.persist()}),Re(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),Re(this,"on",(s,r)=>{this.events.on(s,r)}),Re(this,"once",(s,r)=>{this.events.once(s,r)}),Re(this,"off",(s,r)=>{this.events.off(s,r)}),Re(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=v.E(t,this.name)}get context(){return v.y(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 s={topic:t.topic,request:v.formatJsonRpcRequest(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),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:s}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(rt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=se("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(rt.created,e=>{const t=rt.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(rt.updated,e=>{const t=rt.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(rt.deleted,e=>{const t=rt.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(v.r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{v.cjsExports$1.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(rt.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var _1=Object.defineProperty,O1=(i,e,t)=>e in i?_1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ce=(i,e,t)=>O1(i,typeof e!="symbol"?e+"":e,t);let A1=class extends Pf{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ce(this,"expirations",new Map),Ce(this,"events",new v.eventsExports.EventEmitter),Ce(this,"name",Rw),Ce(this,"version",Nw),Ce(this,"cached",[]),Ce(this,"initialized",!1),Ce(this,"storagePrefix",bt),Ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.expirations.set(s.target,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ce(this,"has",s=>{try{const r=this.formatTarget(s);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ce(this,"set",(s,r)=>{this.isInitialized();const n=this.formatTarget(s),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(it.created,{target:n,expiration:o})}),Ce(this,"get",s=>{this.isInitialized();const r=this.formatTarget(s);return this.getExpiration(r)}),Ce(this,"del",s=>{if(this.isInitialized(),this.has(s)){const r=this.formatTarget(s),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(it.deleted,{target:r,expiration:n})}}),Ce(this,"on",(s,r)=>{this.events.on(s,r)}),Ce(this,"once",(s,r)=>{this.events.once(s,r)}),Ce(this,"off",(s,r)=>{this.events.off(s,r)}),Ce(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=v.E(t,this.name)}get context(){return v.y(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 Kf(e);if(typeof e=="number")return Gf(e);const{message:t}=se("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(it.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=se("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:s}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(s),new Error(s)}return t}checkExpiry(e,t){const{expiry:s}=t;v.cjsExports$1.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(it.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(v.r.pulse,()=>this.checkExpirations()),this.events.on(it.created,e=>{const t=it.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(it.expired,e=>{const t=it.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(it.deleted,e=>{const t=it.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var R1=Object.defineProperty,N1=(i,e,t)=>e in i?R1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ye=(i,e,t)=>N1(i,typeof e!="symbol"?e+"":e,t);let T1=class extends _f{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,ye(this,"name",Tw),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",Bw),ye(this,"storagePrefix",bt),ye(this,"version",eu),ye(this,"publicKey"),ye(this,"fetchPromise"),ye(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&v.cjsExports$1.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ye(this,"register",async r=>{if(!Ws()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const h=v.cjsExports$2.getDocument(),l=this.startAbortTimer(v.cjsExports$1.ONE_SECOND*5),u=await new Promise((p,g)=>{const w=()=>{window.removeEventListener("message",d),h.body.removeChild(y),g("attestation aborted")};this.abortController.signal.addEventListener("abort",w);const y=h.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",w,{signal:this.abortController.signal});const d=m=>{if(m.data&&typeof m.data=="string")try{const f=JSON.parse(m.data);if(f.type==="verify_attestation"){if(v.sn(f.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(y),this.abortController.signal.removeEventListener("abort",w),window.removeEventListener("message",d),p(f.attestation===null?"":f.attestation)}}catch(f){this.logger.warn(f)}};h.body.appendChild(y),window.addEventListener("message",d,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),ye(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(v.sn(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(r?.verifyUrl);return this.fetchAttestation(o,c)}),ye(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(v.cjsExports$1.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}),ye(this,"getVerifyUrl",r=>{let n=r||Cs;return Uw.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Cs}`),n=Cs),n}),ye(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(v.cjsExports$1.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)}}),ye(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),ye(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ye(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")}}),ye(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ye(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}),ye(this,"validateAttestation",(r,n)=>{const o=Ky(r,n.publicKey),a={hasExpired:v.cjsExports$1.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=v.E(t,this.name),this.abortController=new AbortController,this.isDevEnv=El(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return v.y(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),v.cjsExports$1.toMiliseconds(e))}};var C1=Object.defineProperty,B1=(i,e,t)=>e in i?C1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Bc=(i,e,t)=>B1(i,typeof e!="symbol"?e+"":e,t);let U1=class extends Of{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Bc(this,"context",jw),Bc(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${qw}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=v.E(t,this.context)}};var j1=Object.defineProperty,Uc=Object.getOwnPropertySymbols,q1=Object.prototype.hasOwnProperty,k1=Object.prototype.propertyIsEnumerable,Oo=(i,e,t)=>e in i?j1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Es=(i,e)=>{for(var t in e||(e={}))q1.call(e,t)&&Oo(i,t,e[t]);if(Uc)for(var t of Uc(e))k1.call(e,t)&&Oo(i,t,e[t]);return i},we=(i,e,t)=>Oo(i,typeof e!="symbol"?e+"":e,t);class L1 extends Af{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,we(this,"context",Lw),we(this,"storagePrefix",bt),we(this,"storageVersion",kw),we(this,"events",new Map),we(this,"shouldPersist",!1),we(this,"init",async()=>{if(!El())try{const r={eventId:Da(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:bl(this.core.relayer.protocol,this.core.relayer.version,vo)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),we(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,h=Da(),l=this.core.projectId||"",u=Date.now(),p=Es({eventId:h,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(h));return this.telemetryEnabled&&(this.events.set(h,p),this.shouldPersist=!0),p}),we(this,"getEvent",r=>{const{eventId:n,topic:o}=r;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Es(Es({},a),this.setMethods(a.eventId))}),we(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),we(this,"setEventListeners",()=>{this.core.heartbeat.on(v.r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{v.cjsExports$1.fromMiliseconds(Date.now())-v.cjsExports$1.fromMiliseconds(r.timestamp)>Dw&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),we(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),we(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)}),we(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)}),we(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),we(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,Es(Es({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),we(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)}}),we(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Fw}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${vo}${n}`,{method:"POST",body:JSON.stringify(r)})}),we(this,"getAppDomain",()=>Ff().url),this.logger=v.E(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var D1=Object.defineProperty,jc=Object.getOwnPropertySymbols,F1=Object.prototype.hasOwnProperty,M1=Object.prototype.propertyIsEnumerable,Ao=(i,e,t)=>e in i?D1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qc=(i,e)=>{for(var t in e||(e={}))F1.call(e,t)&&Ao(i,t,e[t]);if(jc)for(var t of jc(e))M1.call(e,t)&&Ao(i,t,e[t]);return i},ce=(i,e,t)=>Ao(i,typeof e!="symbol"?e+"":e,t);let z1=class fu extends yf{constructor(e){var t;super(e),ce(this,"protocol",Xl),ce(this,"version",eu),ce(this,"name",bo),ce(this,"relayUrl"),ce(this,"projectId"),ce(this,"customStoragePrefix"),ce(this,"events",new v.eventsExports.EventEmitter),ce(this,"logger"),ce(this,"heartbeat"),ce(this,"relayer"),ce(this,"crypto"),ce(this,"storage"),ce(this,"history"),ce(this,"expirer"),ce(this,"pairing"),ce(this,"verify"),ce(this,"echoClient"),ce(this,"linkModeSupportedApps"),ce(this,"eventClient"),ce(this,"initialized",!1),ce(this,"logChunkController"),ce(this,"on",(a,c)=>this.events.on(a,c)),ce(this,"once",(a,c)=>this.events.once(a,c)),ce(this,"off",(a,c)=>this.events.off(a,c)),ce(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ce(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:le.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(e?.customStoragePrefix);if(s)try{return this.customStoragePrefix=s.customStoragePrefix,this.logger=s.logger,this.heartbeat=s.heartbeat,this.crypto=s.crypto,this.history=s.history,this.expirer=s.expirer,this.storage=s.storage,this.relayer=s.relayer,this.pairing=s.pairing,this.verify=s.verify,this.echoClient=s.echoClient,this.linkModeSupportedApps=s.linkModeSupportedApps,this.eventClient=s.eventClient,this.initialized=s.initialized,this.logChunkController=s.logChunkController,s}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||iu,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=v.k({level:typeof e?.logger=="string"&&e.logger?e.logger:hw.logger,name:bo}),{logger:n,chunkLoggerController:o}=v.A({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=v.E(n,this.name),this.heartbeat=new v.i,this.crypto=new yb(this,this.logger,e?.keychain),this.history=new P1(this,this.logger),this.expirer=new A1(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new v.h(qc(qc({},lw),e?.storageOptions)),this.relayer=new zb({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new I1(this,this.logger),this.verify=new T1(this,this.logger,this.storage),this.echoClient=new U1(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new L1(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new fu(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(Iw,s),t}get context(){return v.y(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(yc,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(yc)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,s=`${t}_count`;return globalThis[s]=(globalThis[s]||0)+1,globalThis[s]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[s]} times.`),globalThis[t]}catch(t){console.warn("Failed to get global WalletConnect core",t);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${((t=e.opts)==null?void 0:t.customStoragePrefix)||""}`;globalThis[s]=e}catch(s){console.warn("Failed to set global WalletConnect core",s)}}isGlobalCoreDisabled(){try{return typeof z.process$1<"u"&&z.process$1.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const H1=z1;function Fs(i,{strict:e=!0}={}){return!i||typeof i!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(i):i.startsWith("0x")}function kc(i){return Fs(i,{strict:!1})?Math.ceil((i.length-2)/2):i.length}const gu="2.23.2";let Nn={getDocsUrl:({docsBaseUrl:i,docsPath:e="",docsSlug:t})=>e?`${i??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${gu}`};class ai extends Error{constructor(e,t={}){const s=t.cause instanceof ai?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof ai&&t.cause.docsPath||t.docsPath,n=Nn.getDocsUrl?.({...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...s?[`Details: ${s}`]:[],...Nn.version?[`Version: ${Nn.version}`]:[]].join(`
2
- `);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=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=gu}walk(e){return yu(this,e)}}function yu(i,e){return e?.(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?yu(i.cause,e):e?null:i}class wu extends ai{constructor({size:e,targetSize:t,type:s}){super(`${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function ds(i,{dir:e,size:t=32}={}){return typeof i=="string"?V1(i,{dir:e,size:t}):K1(i,{dir:e,size:t})}function V1(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new wu({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function K1(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new wu({size:i.length,targetSize:t,type:"bytes"});const s=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";s[n?r:t-r-1]=i[n?r:i.length-r-1]}return s}class G1 extends ai{constructor({max:e,min:t,signed:s,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${s?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class W1 extends ai{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ps(i,{size:e}){if(kc(i)>e)throw new W1({givenSize:kc(i),maxSize:e})}function Ro(i,e={}){const{signed:t}=e;e.size&&ps(i,{size:e.size});const s=BigInt(i);if(!t)return s;const r=(i.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return s<=n?s:s-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function Z1(i,e={}){return Number(Ro(i,e))}const J1=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function No(i,e={}){return typeof i=="number"||typeof i=="bigint"?bu(i,e):typeof i=="string"?X1(i,e):typeof i=="boolean"?Y1(i,e):mu(i,e)}function Y1(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?(ps(t,{size:e.size}),ds(t,{size:e.size})):t}function mu(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=J1[i[r]];const s=`0x${t}`;return typeof e.size=="number"?(ps(s,{size:e.size}),ds(s,{dir:"right",size:e.size})):s}function bu(i,e={}){const{signed:t,size:s}=e,r=BigInt(i);let n;s?t?n=(1n<<BigInt(s)*8n-1n)-1n:n=2n**(BigInt(s)*8n)-1n:typeof i=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof i=="bigint"?"n":"";throw new G1({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:s,value:`${i}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(s*8))+BigInt(r):r).toString(16)}`;return s?ds(a,{size:s}):a}const Q1=new TextEncoder;function X1(i,e={}){const t=Q1.encode(i);return mu(t,e)}const e0=new TextEncoder;function t0(i,e={}){return typeof i=="number"||typeof i=="bigint"?s0(i,e):typeof i=="boolean"?i0(i,e):Fs(i)?vu(i,e):Eu(i,e)}function i0(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?(ps(t,{size:e.size}),ds(t,{size:e.size})):t}const $t={zero:48,nine:57,A:65,F:70,a:97,f:102};function Lc(i){if(i>=$t.zero&&i<=$t.nine)return i-$t.zero;if(i>=$t.A&&i<=$t.F)return i-($t.A-10);if(i>=$t.a&&i<=$t.f)return i-($t.a-10)}function vu(i,e={}){let t=i;e.size&&(ps(t,{size:e.size}),t=ds(t,{dir:"right",size:e.size}));let s=t.slice(2);s.length%2&&(s=`0${s}`);const r=s.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=Lc(s.charCodeAt(a++)),h=Lc(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new ai(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function s0(i,e){const t=bu(i,e);return vu(t)}function Eu(i,e={}){const t=e0.encode(i);return typeof e.size=="number"?(ps(t,{size:e.size}),ds(t,{dir:"right",size:e.size})):t}function Rr(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function r0(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function er(i,...e){if(!r0(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function n0(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Rr(i.outputLen),Rr(i.blockLen)}function To(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function $u(i,e){er(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ur=BigInt(2**32-1),Dc=BigInt(32);function o0(i,e=!1){return e?{h:Number(i&ur),l:Number(i>>Dc&ur)}:{h:Number(i>>Dc&ur)|0,l:Number(i&ur)|0}}function a0(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=o0(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const c0=(i,e,t)=>i<<t|e>>>32-t,h0=(i,e,t)=>e<<t|i>>>32-t,l0=(i,e,t)=>e<<t-32|i>>>64-t,u0=(i,e,t)=>i<<t-32|e>>>64-t,mi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function d0(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function p0(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function f0(i,e){return i<<32-e|i>>>e}const Fc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function g0(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Mc(i){for(let e=0;e<i.length;e++)i[e]=g0(i[e])}function y0(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function sa(i){return typeof i=="string"&&(i=y0(i)),er(i),i}function w0(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];er(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}class Iu{clone(){return this._cloneInto()}}function Su(i){const e=s=>i().update(sa(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function m0(i=32){if(mi&&typeof mi.getRandomValues=="function")return mi.getRandomValues(new Uint8Array(i));if(mi&&typeof mi.randomBytes=="function")return mi.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const xu=[],Pu=[],_u=[],b0=BigInt(0),$s=BigInt(1),v0=BigInt(2),E0=BigInt(7),$0=BigInt(256),I0=BigInt(113);for(let i=0,e=$s,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],xu.push(2*(5*s+t)),Pu.push((i+1)*(i+2)/2%64);let r=b0;for(let n=0;n<7;n++)e=(e<<$s^(e>>E0)*I0)%$0,e&v0&&(r^=$s<<($s<<BigInt(n))-$s);_u.push(r)}const[S0,x0]=a0(_u,!0),zc=(i,e,t)=>t>32?l0(i,e,t):c0(i,e,t),Hc=(i,e,t)=>t>32?u0(i,e,t):h0(i,e,t);function P0(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=zc(h,l,1)^t[a],p=Hc(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Pu[o],c=zc(r,n,a),h=Hc(r,n,a),l=xu[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=S0[s],i[1]^=x0[s]}t.fill(0)}class ra extends Iu{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Rr(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=d0(this.state)}keccak(){Fc||Mc(this.state32),P0(this.state32,this.rounds),Fc||Mc(this.state32),this.posOut=0,this.pos=0}update(e){To(this);const{blockLen:t,state:s}=this;e=sa(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){To(this,!1),er(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 Rr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($u(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:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new ra(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const _0=(i,e,t)=>Su(()=>new ra(e,i,t)),O0=_0(1,136,256/8);function Ou(i,e){const t=e||"hex",s=O0(Fs(i,{strict:!1})?t0(i):i);return t==="bytes"?s:No(s)}class A0 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 s=this.keys().next().value;s&&this.delete(s)}return this}}const Tn=new A0(8192);function R0(i,e){if(Tn.has(`${i}.${e}`))return Tn.get(`${i}.${e}`);const t=i.substring(2).toLowerCase(),s=Ou(Eu(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)s[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(s[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Tn.set(`${i}.${e}`,n),n}function N0(i){const e=Ou(`0x${i.substring(4)}`).substring(26);return R0(`0x${e}`)}async function T0({hash:i,signature:e}){const t=Fs(i)?i:No(i),{secp256k1:s}=await Promise.resolve().then(()=>require("./secp256k1-BnR7-XEW.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:u,yParity:p}=e,g=Number(p??u),w=Vc(g);return new s.Signature(Ro(h),Ro(l)).addRecoveryBit(w)}const o=Fs(e)?e:No(e),a=Z1(`0x${o.slice(130)}`),c=Vc(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Vc(i){if(i===0||i===1)return i;if(i===27)return 0;if(i===28)return 1;throw new Error("Invalid yParityOrV value")}async function C0({hash:i,signature:e}){return N0(await T0({hash:i,signature:e}))}function B0(i){if(i.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<i.length;h++){const l=i.charAt(h),u=l.charCodeAt(0);if(e[u]!==255)throw new TypeError(l+" is ambiguous");e[u]=h}const t=i.length,s=i.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let l=0,u=0,p=0;const g=h.length;for(;p!==g&&h[p]===0;)p++,l++;const w=(g-p)*n+1>>>0,y=new Uint8Array(w);for(;p!==g;){let f=h[p],E=0;for(let _=w-1;(f!==0||E<u)&&_!==-1;_--,E++)f+=256*y[_]>>>0,y[_]=f%t>>>0,f=f/t>>>0;if(f!==0)throw new Error("Non-zero carry");u=E,p++}let d=w-u;for(;d!==w&&y[d]===0;)d++;let m=s.repeat(l);for(;d<w;++d)m+=i.charAt(y[d]);return m}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,u=0,p=0;for(;h[l]===s;)u++,l++;const g=(h.length-l)*r+1>>>0,w=new Uint8Array(g);for(;l<h.length;){const f=h.charCodeAt(l);if(f>255)return;let E=e[f];if(E===255)return;let _=0;for(let C=g-1;(E!==0||_<p)&&C!==-1;C--,_++)E+=t*w[C]>>>0,w[C]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");p=_,l++}let y=g-p;for(;y!==g&&w[y]===0;)y++;const d=new Uint8Array(u+(g-y));let m=u;for(;y!==g;)d[m++]=w[y++];return d}function c(h){const l=a(h);if(l)return l;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var U0="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const j0=B0(U0),q0=":";function Sr(i){const[e,t]=i.split(q0);return{namespace:e,reference:t}}function Au(i,e){return i.includes(":")?[i]:e.chains||[]}var k0=Object.defineProperty,L0=Object.defineProperties,D0=Object.getOwnPropertyDescriptors,Kc=Object.getOwnPropertySymbols,F0=Object.prototype.hasOwnProperty,M0=Object.prototype.propertyIsEnumerable,Gc=(i,e,t)=>e in i?k0(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wc=(i,e)=>{for(var t in e||(e={}))F0.call(e,t)&&Gc(i,t,e[t]);if(Kc)for(var t of Kc(e))M0.call(e,t)&&Gc(i,t,e[t]);return i},z0=(i,e)=>L0(i,D0(e));const H0="ReactNative",Li={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"};function Ru(){return typeof z.process$1<"u"&&typeof z.process$1.versions<"u"&&typeof z.process$1.versions.node<"u"}function Nu(){return!v.cjsExports$2.getDocument()&&!!v.cjsExports$2.getNavigator()&&navigator.product===H0}function Tu(){return!Ru()&&!!v.cjsExports$2.getNavigator()&&!!v.cjsExports$2.getDocument()}function V0(){return Nu()?Li.reactNative:Ru()?Li.node:Tu()?Li.browser:Li.unknown}function K0(i){var e,t;const s=G0();try{return i!=null&&i.url&&s.url&&new URL(i.url).host!==new URL(s.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${i.url} differs from the actual page url:${s.url}. This is probably unintended and can lead to issues.`),i.url=s.url),(e=i?.icons)!=null&&e.length&&i.icons.length>0&&(i.icons=i.icons.filter(r=>r!=="")),z0(Wc(Wc({},s),i),{url:i?.url||s.url,name:i?.name||s.name,description:i?.description||s.description,icons:(t=i?.icons)!=null&&t.length&&i.icons.length>0?i.icons:s.icons})}catch(r){return console.warn("Error populating app metadata",r),i||s}}function G0(){return v.cjsExports.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Qt(i,e){return i.filter(t=>e.includes(t)).length===i.length}function bi(i=v.cjsExports$1.FIVE_MINUTES,e){const t=v.cjsExports$1.toMiliseconds(i||v.cjsExports$1.FIVE_MINUTES);let s,r,n,o;return{resolve:a=>{n&&s&&(clearTimeout(n),s(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const h=new Error(e);o=Promise.reject(h),c(h)},t),s=a,r=c})}}function W0(i){const[e,t]=i.split(":"),s={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")s.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))s.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return s}function ke(i,e){return v.cjsExports$1.fromMiliseconds(Date.now()+v.cjsExports$1.toMiliseconds(i))}function vi(i){return Date.now()>=v.cjsExports$1.toMiliseconds(i)}function ne(i,e){return`${i}${e?`:${e}`:""}`}function ii(i=[],e=[]){return[...new Set([...i,...e])]}async function Z0({id:i,topic:e,wcDeepLink:t}){var s;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r?.href;if(typeof n!="string")return;const o=J0(n,i,e),a=V0();if(a===Li.browser){if(!((s=v.cjsExports$2.getDocument())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Y0(o)}else a===Li.reactNative&&typeof(z.global==null?void 0:z.global.Linking)<"u"&&await z.global.Linking.openURL(o)}catch(r){console.error(r)}}function J0(i,e,t){const s=`requestId=${e}&sessionTopic=${t}`;i.endsWith("/")&&(i=i.slice(0,-1));let r=`${i}`;if(i.startsWith("https://t.me")){const n=i.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${iv(s,!0)}`}else r=`${r}/wc?${s}`;return r}function Y0(i){let e="_self";tv()?e="_top":(ev()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function Q0(i,e){let t="";try{if(Tu()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function Zc(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function X0(){return typeof z.process$1<"u"&&z.process$1.env.IS_VITEST==="true"}function ev(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function tv(){try{return window.self!==window.top}catch{return!1}}function iv(i,e=!1){const t=z.Buffer.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Nr(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function sv(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function tr(i,...e){if(!sv(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function rv(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Nr(i.outputLen),Nr(i.blockLen)}function is(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Cu(i,e){tr(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const dr=BigInt(2**32-1),Jc=BigInt(32);function nv(i,e=!1){return e?{h:Number(i&dr),l:Number(i>>Jc&dr)}:{h:Number(i>>Jc&dr)|0,l:Number(i&dr)|0}}function ov(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=nv(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const av=(i,e,t)=>i<<t|e>>>32-t,cv=(i,e,t)=>e<<t|i>>>32-t,hv=(i,e,t)=>e<<t-32|i>>>64-t,lv=(i,e,t)=>i<<t-32|e>>>64-t,Ei=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function uv(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Cn(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function yt(i,e){return i<<32-e|i>>>e}const Yc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function dv(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Qc(i){for(let e=0;e<i.length;e++)i[e]=dv(i[e])}function pv(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function Jr(i){return typeof i=="string"&&(i=pv(i)),tr(i),i}function fv(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];tr(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}let na=class{clone(){return this._cloneInto()}};function Bu(i){const e=s=>i().update(Jr(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Uu(i=32){if(Ei&&typeof Ei.getRandomValues=="function")return Ei.getRandomValues(new Uint8Array(i));if(Ei&&typeof Ei.randomBytes=="function")return Ei.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const ju=[],qu=[],ku=[],gv=BigInt(0),Is=BigInt(1),yv=BigInt(2),wv=BigInt(7),mv=BigInt(256),bv=BigInt(113);for(let i=0,e=Is,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],ju.push(2*(5*s+t)),qu.push((i+1)*(i+2)/2%64);let r=gv;for(let n=0;n<7;n++)e=(e<<Is^(e>>wv)*bv)%mv,e&yv&&(r^=Is<<(Is<<BigInt(n))-Is);ku.push(r)}const[vv,Ev]=ov(ku,!0),Xc=(i,e,t)=>t>32?hv(i,e,t):av(i,e,t),eh=(i,e,t)=>t>32?lv(i,e,t):cv(i,e,t);function $v(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=Xc(h,l,1)^t[a],p=eh(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=qu[o],c=Xc(r,n,a),h=eh(r,n,a),l=ju[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=vv[s],i[1]^=Ev[s]}t.fill(0)}class oa extends na{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Nr(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=uv(this.state)}keccak(){Yc||Qc(this.state32),$v(this.state32,this.rounds),Yc||Qc(this.state32),this.posOut=0,this.pos=0}update(e){is(this);const{blockLen:t,state:s}=this;e=Jr(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){is(this,!1),tr(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 Nr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Cu(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:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new oa(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Iv=(i,e,t)=>Bu(()=>new oa(e,i,t)),Sv=Iv(1,136,256/8),xv="https://rpc.walletconnect.org/v1";function Lu(i){const e=`Ethereum Signed Message:
1
+ "use strict";const v=require("./index.es-D5cfl75E.js"),z=require("./platform-DH1Olrgt.js");function xd(i){if(i.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<i.length;h++){const l=i.charAt(h),u=l.charCodeAt(0);if(e[u]!==255)throw new TypeError(l+" is ambiguous");e[u]=h}const t=i.length,s=i.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let l=0,u=0,p=0;const g=h.length;for(;p!==g&&h[p]===0;)p++,l++;const w=(g-p)*n+1>>>0,y=new Uint8Array(w);for(;p!==g;){let f=h[p],E=0;for(let _=w-1;(f!==0||E<u)&&_!==-1;_--,E++)f+=256*y[_]>>>0,y[_]=f%t>>>0,f=f/t>>>0;if(f!==0)throw new Error("Non-zero carry");u=E,p++}let d=w-u;for(;d!==w&&y[d]===0;)d++;let m=s.repeat(l);for(;d<w;++d)m+=i.charAt(y[d]);return m}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,u=0,p=0;for(;h[l]===s;)u++,l++;const g=(h.length-l)*r+1>>>0,w=new Uint8Array(g);for(;l<h.length;){const f=h.charCodeAt(l);if(f>255)return;let E=e[f];if(E===255)return;let _=0;for(let C=g-1;(E!==0||_<p)&&C!==-1;C--,_++)E+=t*w[C]>>>0,w[C]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");p=_,l++}let y=g-p;for(;y!==g&&w[y]===0;)y++;const d=new Uint8Array(u+(g-y));let m=u;for(;y!==g;)d[m++]=w[y++];return d}function c(h){const l=a(h);if(l)return l;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Pd="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";xd(Pd);const _d=":";function Zh(i){const[e,t]=i.split(_d);return{namespace:e,reference:t}}function ga(i,e=[]){const t=[];return Object.keys(i).forEach(s=>{if(e.length&&!e.includes(s))return;const r=i[s];t.push(...r.accounts)}),t}function rn(i=[],e=[]){return[...new Set([...i,...e])]}function _r(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Od(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ks(i,...e){if(!Od(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Ad(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");_r(i.outputLen),_r(i.blockLen)}function zi(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Jh(i,e){Ks(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const rr=BigInt(2**32-1),ya=BigInt(32);function Rd(i,e=!1){return e?{h:Number(i&rr),l:Number(i>>ya&rr)}:{h:Number(i>>ya&rr)|0,l:Number(i&rr)|0}}function Nd(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=Rd(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Td=(i,e,t)=>i<<t|e>>>32-t,Cd=(i,e,t)=>e<<t|i>>>32-t,Bd=(i,e,t)=>e<<t-32|i>>>64-t,Ud=(i,e,t)=>i<<t-32|e>>>64-t,pi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function jd(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function nn(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function pt(i,e){return i<<32-e|i>>>e}const wa=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function qd(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function ma(i){for(let e=0;e<i.length;e++)i[e]=qd(i[e])}function kd(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function qr(i){return typeof i=="string"&&(i=kd(i)),Ks(i),i}function Ld(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Ks(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}let Go=class{clone(){return this._cloneInto()}};function Yh(i){const e=s=>i().update(qr(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Qh(i=32){if(pi&&typeof pi.getRandomValues=="function")return pi.getRandomValues(new Uint8Array(i));if(pi&&typeof pi.randomBytes=="function")return pi.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Xh=[],el=[],tl=[],Dd=BigInt(0),ys=BigInt(1),Fd=BigInt(2),Md=BigInt(7),zd=BigInt(256),Hd=BigInt(113);for(let i=0,e=ys,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Xh.push(2*(5*s+t)),el.push((i+1)*(i+2)/2%64);let r=Dd;for(let n=0;n<7;n++)e=(e<<ys^(e>>Md)*Hd)%zd,e&Fd&&(r^=ys<<(ys<<BigInt(n))-ys);tl.push(r)}const[Vd,Kd]=Nd(tl,!0),ba=(i,e,t)=>t>32?Bd(i,e,t):Td(i,e,t),va=(i,e,t)=>t>32?Ud(i,e,t):Cd(i,e,t);function Gd(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=ba(h,l,1)^t[a],p=va(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=el[o],c=ba(r,n,a),h=va(r,n,a),l=Xh[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=Vd[s],i[1]^=Kd[s]}t.fill(0)}let Wd=class il extends Go{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,_r(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=jd(this.state)}keccak(){wa||ma(this.state32),Gd(this.state32,this.rounds),wa||ma(this.state32),this.posOut=0,this.pos=0}update(e){zi(this);const{blockLen:t,state:s}=this;e=qr(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){zi(this,!1),Ks(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 _r(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Jh(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:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new il(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Zd=(i,e,t)=>Yh(()=>new Wd(e,i,t));Zd(1,136,256/8);function on(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function sl(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ze(i,...e){if(!sl(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Ea(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Jd(i,e){Ze(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function $a(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const Ft=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),Yd=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Qd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Qd)throw new Error("Non little-endian hardware is not supported");function Xd(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function Qn(i){if(typeof i=="string")i=Xd(i);else if(sl(i))i=Xn(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function ep(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function tp(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}const ip=(i,e)=>{function t(s,...r){if(Ze(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?Ze(h):Ze(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&Ze(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");Ze(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ze(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(Ze(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(h,l)}}}return Object.assign(t,i),t};function Ia(i,e,t=!0){if(e===void 0)return new Uint8Array(i);if(e.length!==i)throw new Error("invalid output length, expected "+i+", got: "+e.length);if(t&&!sp(e))throw new Error("invalid output, must be aligned");return e}function Sa(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);i.setUint32(e+4,o,s),i.setUint32(e+0,a,s)}function sp(i){return i.byteOffset%4===0}function Xn(i){return Uint8Array.from(i)}function Hi(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const rl=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),rp=rl("expand 16-byte k"),np=rl("expand 32-byte k"),op=Ft(rp),ap=Ft(np);function Q(i,e){return i<<e|i>>>32-e}function eo(i){return i.byteOffset%4===0}const nr=64,cp=16,nl=2**32-1,xa=new Uint32Array;function hp(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(nr),l=Ft(h),u=eo(r)&&eo(n),p=u?Ft(r):xa,g=u?Ft(n):xa;for(let w=0;w<c;o++){if(i(e,t,s,l,o,a),o>=nl)throw new Error("arx: counter overflow");const y=Math.min(nr,c-w);if(u&&y===nr){const d=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let m=0,f;m<cp;m++)f=d+m,g[f]=p[f]^l[m];w+=nr;continue}for(let d=0,m;d<y;d++)m=w+d,n[m]=r[m]^h[d];w+=y}}function lp(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=ep({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return on(r),on(o),$a(n),$a(t),(a,c,h,l,u=0)=>{Ze(a),Ze(c),Ze(h);const p=h.length;if(l===void 0&&(l=new Uint8Array(p)),Ze(l),on(u),u<0||u>=nl)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const g=[];let w=a.length,y,d;if(w===32)g.push(y=Xn(a)),d=ap;else if(w===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),d=op,g.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${w}`);eo(c)||g.push(c=Xn(c));const m=Ft(y);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(d,m,Ft(c.subarray(0,16)),m),c=c.subarray(16)}const f=16-r;if(f!==c.length)throw new Error(`arx: nonce must be ${f} or 16 bytes`);if(f!==12){const _=new Uint8Array(12);_.set(c,n?0:12-c.length),c=_,g.push(c)}const E=Ft(c);return hp(i,d,m,E,h,l,u,o),Hi(...g),l}}const _e=(i,e)=>i[e++]&255|(i[e++]&255)<<8;let up=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=Qn(e),Ze(e,32);const t=_e(e,0),s=_e(e,2),r=_e(e,4),n=_e(e,6),o=_e(e,8),a=_e(e,10),c=_e(e,12),h=_e(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>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|c<<5)&8065,this.r[8]=(c>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=_e(e,16+2*l)}process(e,t,s=!1){const r=s?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],l=o[3],u=o[4],p=o[5],g=o[6],w=o[7],y=o[8],d=o[9],m=_e(e,t+0),f=_e(e,t+2),E=_e(e,t+4),_=_e(e,t+6),C=_e(e,t+8),O=_e(e,t+10),P=_e(e,t+12),R=_e(e,t+14);let S=n[0]+(m&8191),U=n[1]+((m>>>13|f<<3)&8191),N=n[2]+((f>>>10|E<<6)&8191),B=n[3]+((E>>>7|_<<9)&8191),j=n[4]+((_>>>4|C<<12)&8191),b=n[5]+(C>>>1&8191),I=n[6]+((C>>>14|O<<2)&8191),$=n[7]+((O>>>11|P<<5)&8191),A=n[8]+((P>>>8|R<<8)&8191),T=n[9]+(R>>>5|r),x=0,q=x+S*a+U*(5*d)+N*(5*y)+B*(5*w)+j*(5*g);x=q>>>13,q&=8191,q+=b*(5*p)+I*(5*u)+$*(5*l)+A*(5*h)+T*(5*c),x+=q>>>13,q&=8191;let k=x+S*c+U*a+N*(5*d)+B*(5*y)+j*(5*w);x=k>>>13,k&=8191,k+=b*(5*g)+I*(5*p)+$*(5*u)+A*(5*l)+T*(5*h),x+=k>>>13,k&=8191;let L=x+S*h+U*c+N*a+B*(5*d)+j*(5*y);x=L>>>13,L&=8191,L+=b*(5*w)+I*(5*g)+$*(5*p)+A*(5*u)+T*(5*l),x+=L>>>13,L&=8191;let M=x+S*l+U*h+N*c+B*a+j*(5*d);x=M>>>13,M&=8191,M+=b*(5*y)+I*(5*w)+$*(5*g)+A*(5*p)+T*(5*u),x+=M>>>13,M&=8191;let F=x+S*u+U*l+N*h+B*c+j*a;x=F>>>13,F&=8191,F+=b*(5*d)+I*(5*y)+$*(5*w)+A*(5*g)+T*(5*p),x+=F>>>13,F&=8191;let H=x+S*p+U*u+N*l+B*h+j*c;x=H>>>13,H&=8191,H+=b*a+I*(5*d)+$*(5*y)+A*(5*w)+T*(5*g),x+=H>>>13,H&=8191;let K=x+S*g+U*p+N*u+B*l+j*h;x=K>>>13,K&=8191,K+=b*c+I*a+$*(5*d)+A*(5*y)+T*(5*w),x+=K>>>13,K&=8191;let Z=x+S*w+U*g+N*p+B*u+j*l;x=Z>>>13,Z&=8191,Z+=b*h+I*c+$*a+A*(5*d)+T*(5*y),x+=Z>>>13,Z&=8191;let G=x+S*y+U*w+N*g+B*p+j*u;x=G>>>13,G&=8191,G+=b*l+I*h+$*c+A*a+T*(5*d),x+=G>>>13,G&=8191;let W=x+S*d+U*y+N*w+B*g+j*p;x=W>>>13,W&=8191,W+=b*u+I*l+$*h+A*c+T*a,x+=W>>>13,W&=8191,x=(x<<2)+x|0,x=x+q|0,q=x&8191,x=x>>>13,k+=x,n[0]=q,n[1]=k,n[2]=L,n[3]=M,n[4]=F,n[5]=H,n[6]=K,n[7]=Z,n[8]=G,n[9]=W}finalize(){const{h:e,pad:t}=this,s=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,s[0]=e[0]+5,r=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+r,r=s[a]>>>13,s[a]&=8191;s[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)s[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|s[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;Hi(s)}update(e){Ea(this);const{buffer:t,blockLen:s}=this;e=Qn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o===s){for(;s<=r-n;n+=s)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Hi(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ea(this),Jd(e,this),this.finished=!0;const{buffer:t,h:s}=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++]=s[o]>>>0,e[n++]=s[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}};function dp(i){const e=(s,r)=>i(r).update(Qn(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const pp=dp(i=>new up(i));function fp(i,e,t,s,r,n=20){let o=i[0],a=i[1],c=i[2],h=i[3],l=e[0],u=e[1],p=e[2],g=e[3],w=e[4],y=e[5],d=e[6],m=e[7],f=r,E=t[0],_=t[1],C=t[2],O=o,P=a,R=c,S=h,U=l,N=u,B=p,j=g,b=w,I=y,$=d,A=m,T=f,x=E,q=_,k=C;for(let M=0;M<n;M+=2)O=O+U|0,T=Q(T^O,16),b=b+T|0,U=Q(U^b,12),O=O+U|0,T=Q(T^O,8),b=b+T|0,U=Q(U^b,7),P=P+N|0,x=Q(x^P,16),I=I+x|0,N=Q(N^I,12),P=P+N|0,x=Q(x^P,8),I=I+x|0,N=Q(N^I,7),R=R+B|0,q=Q(q^R,16),$=$+q|0,B=Q(B^$,12),R=R+B|0,q=Q(q^R,8),$=$+q|0,B=Q(B^$,7),S=S+j|0,k=Q(k^S,16),A=A+k|0,j=Q(j^A,12),S=S+j|0,k=Q(k^S,8),A=A+k|0,j=Q(j^A,7),O=O+N|0,k=Q(k^O,16),$=$+k|0,N=Q(N^$,12),O=O+N|0,k=Q(k^O,8),$=$+k|0,N=Q(N^$,7),P=P+B|0,T=Q(T^P,16),A=A+T|0,B=Q(B^A,12),P=P+B|0,T=Q(T^P,8),A=A+T|0,B=Q(B^A,7),R=R+j|0,x=Q(x^R,16),b=b+x|0,j=Q(j^b,12),R=R+j|0,x=Q(x^R,8),b=b+x|0,j=Q(j^b,7),S=S+U|0,q=Q(q^S,16),I=I+q|0,U=Q(U^I,12),S=S+U|0,q=Q(q^S,8),I=I+q|0,U=Q(U^I,7);let L=0;s[L++]=o+O|0,s[L++]=a+P|0,s[L++]=c+R|0,s[L++]=h+S|0,s[L++]=l+U|0,s[L++]=u+N|0,s[L++]=p+B|0,s[L++]=g+j|0,s[L++]=w+b|0,s[L++]=y+I|0,s[L++]=d+$|0,s[L++]=m+A|0,s[L++]=f+T|0,s[L++]=E+x|0,s[L++]=_+q|0,s[L++]=C+k|0}const gp=lp(fp,{counterRight:!1,counterLength:4,allowShortKeys:!1}),yp=new Uint8Array(16),Pa=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(yp.subarray(t))},wp=new Uint8Array(32);function _a(i,e,t,s,r){const n=i(e,t,wp),o=pp.create(n);r&&Pa(o,r),Pa(o,s);const a=new Uint8Array(16),c=Yd(a);Sa(c,0,BigInt(r?r.length:0),!0),Sa(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return Hi(n,a),h}const mp=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=Ia(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=_a(i,e,t,a,s);return n.set(c,o),Hi(c),n},decrypt(r,n){n=Ia(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=_a(i,e,t,o,s);if(!tp(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),Hi(c),n}});ip({blockSize:64,nonceLength:12,tagLength:16},mp(gp));let ol=class extends Go{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ad(e);const s=qr(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(s.length>r?e.create().update(s).digest():s);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 zi(this),this.iHash.update(e),this}digestInto(e){zi(this),Ks(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:s,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=s._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const al=(i,e,t)=>new ol(i,e).update(t).digest();al.create=(i,e)=>new ol(i,e);function bp(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=s?4:0,h=s?0:4;i.setUint32(e+c,o,s),i.setUint32(e+h,a,s)}function vp(i,e,t){return i&e^~i&t}function Ep(i,e,t){return i&e^i&t^e&t}let $p=class extends Go{constructor(e,t,s,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=nn(this.buffer)}update(e){zi(this);const{view:t,buffer:s,blockLen:r}=this;e=qr(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const c=nn(e);for(;r<=n-o;o+=r)this.process(c,o);continue}s.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){zi(this),Jh(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(s,0),o=0);for(let u=o;u<r;u++)t[u]=0;bp(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=nn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,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(s),e}};const Ip=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]),Bt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ut=new Uint32Array(64);let Sp=class extends $p{constructor(){super(64,32,8,!1),this.A=Bt[0]|0,this.B=Bt[1]|0,this.C=Bt[2]|0,this.D=Bt[3]|0,this.E=Bt[4]|0,this.F=Bt[5]|0,this.G=Bt[6]|0,this.H=Bt[7]|0}get(){const{A:e,B:t,C:s,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,s,r,n,o,a,c]}set(e,t,s,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Ut[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=Ut[u-15],g=Ut[u-2],w=pt(p,7)^pt(p,18)^p>>>3,y=pt(g,17)^pt(g,19)^g>>>10;Ut[u]=y+Ut[u-7]+w+Ut[u-16]|0}let{A:s,B:r,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let u=0;u<64;u++){const p=pt(a,6)^pt(a,11)^pt(a,25),g=l+p+vp(a,c,h)+Ip[u]+Ut[u]|0,w=(pt(s,2)^pt(s,13)^pt(s,22))+Ep(s,r,n)|0;l=h,h=c,c=a,a=o+g|0,o=n,n=r,r=s,s=g+w|0}s=s+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(s,r,n,o,a,c,h,l)}roundClean(){Ut.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const xp=Yh(()=>new Sp);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kr=BigInt(0),Lr=BigInt(1),Pp=BigInt(2);function ri(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Gs(i){if(!ri(i))throw new Error("Uint8Array expected")}function Vi(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const _p=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Ki(i){Gs(i);let e="";for(let t=0;t<i.length;t++)e+=_p[i[t]];return e}function qi(i){const e=i.toString(16);return e.length&1?"0"+e:e}function Wo(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?kr:BigInt("0x"+i)}const vt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Oa(i){if(i>=vt._0&&i<=vt._9)return i-vt._0;if(i>=vt.A&&i<=vt.F)return i-(vt.A-10);if(i>=vt.a&&i<=vt.f)return i-(vt.a-10)}function Gi(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const s=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=Oa(i.charCodeAt(n)),a=Oa(i.charCodeAt(n+1));if(o===void 0||a===void 0){const c=i[n]+i[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}s[r]=o*16+a}return s}function Xt(i){return Wo(Ki(i))}function Us(i){return Gs(i),Wo(Ki(Uint8Array.from(i).reverse()))}function Wi(i,e){return Gi(i.toString(16).padStart(e*2,"0"))}function Dr(i,e){return Wi(i,e).reverse()}function Op(i){return Gi(qi(i))}function Ke(i,e,t){let s;if(typeof e=="string")try{s=Gi(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(ri(e))s=Uint8Array.from(e);else throw new Error(i+" must be hex string or Uint8Array");const r=s.length;if(typeof t=="number"&&r!==t)throw new Error(i+" of length "+t+" expected, got "+r);return s}function js(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Gs(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}function Ap(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}function Rp(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const an=i=>typeof i=="bigint"&&kr<=i;function Fr(i,e,t){return an(i)&&an(e)&&an(t)&&e<=i&&i<t}function Nt(i,e,t,s){if(!Fr(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function cl(i){let e;for(e=0;i>kr;i>>=Lr,e+=1);return e}function Np(i,e){return i>>BigInt(e)&Lr}function Tp(i,e,t){return i|(t?Lr:kr)<<BigInt(e)}const Zo=i=>(Pp<<BigInt(i-1))-Lr,cn=i=>new Uint8Array(i),Aa=i=>Uint8Array.from(i);function hl(i,e,t){if(typeof i!="number"||i<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let s=cn(i),r=cn(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=cn())=>{r=a(Aa([0]),l),s=a(),l.length!==0&&(r=a(Aa([1]),l),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const u=[];for(;l<e;){s=a();const p=s.slice();u.push(p),l+=s.length}return js(...u)};return(l,u)=>{o(),c(l);let p;for(;!(p=u(h()));)c();return o(),p}}const Cp={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||ri(i),isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function cs(i,e,t={}){const s=(r,n,o)=>{const a=Cp[n];if(typeof a!="function")throw new Error("invalid validator function");const c=i[r];if(!(o&&c===void 0)&&!a(c,i))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))s(r,n,!1);for(const[r,n]of Object.entries(t))s(r,n,!0);return i}const Bp=()=>{throw new Error("not implemented")};function to(i){const e=new WeakMap;return(t,...s)=>{const r=e.get(t);if(r!==void 0)return r;const n=i(t,...s);return e.set(t,n),n}}var Up=Object.freeze({__proto__:null,isBytes:ri,abytes:Gs,abool:Vi,bytesToHex:Ki,numberToHexUnpadded:qi,hexToNumber:Wo,hexToBytes:Gi,bytesToNumberBE:Xt,bytesToNumberLE:Us,numberToBytesBE:Wi,numberToBytesLE:Dr,numberToVarBytesBE:Op,ensureBytes:Ke,concatBytes:js,equalBytes:Ap,utf8ToBytes:Rp,inRange:Fr,aInRange:Nt,bitLen:cl,bitGet:Np,bitSet:Tp,bitMask:Zo,createHmacDrbg:hl,validateObject:cs,notImplemented:Bp,memoized:to});const Se=BigInt(0),pe=BigInt(1),Gt=BigInt(2),jp=BigInt(3),io=BigInt(4),Ra=BigInt(5),Na=BigInt(8);function Le(i,e){const t=i%e;return t>=Se?t:e+t}function ll(i,e,t){if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(t<=Se)throw new Error("invalid modulus");if(t===pe)return Se;let s=pe;for(;e>Se;)e&pe&&(s=s*i%t),i=i*i%t,e>>=pe;return s}function ct(i,e,t){let s=i;for(;e-- >Se;)s*=s,s%=t;return s}function so(i,e){if(i===Se)throw new Error("invert: expected non-zero number");if(e<=Se)throw new Error("invert: expected positive modulus, got "+e);let t=Le(i,e),s=e,r=Se,n=pe;for(;t!==Se;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==pe)throw new Error("invert: does not exist");return Le(r,e)}function qp(i){const e=(i-pe)/Gt;let t,s,r;for(t=i-pe,s=0;t%Gt===Se;t/=Gt,s++);for(r=Gt;r<i&&ll(r,e,i)!==i-pe;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+pe)/io;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(t+pe)/Gt;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=s,h=o.pow(o.mul(o.ONE,r),t),l=o.pow(a,n),u=o.pow(a,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let p=1;for(let w=o.sqr(u);p<c&&!o.eql(w,o.ONE);p++)w=o.sqr(w);const g=o.pow(h,pe<<BigInt(c-p-1));h=o.sqr(g),l=o.mul(l,g),u=o.mul(u,h),c=p}return l}}function kp(i){if(i%io===jp){const e=(i+pe)/io;return function(t,s){const r=t.pow(s,e);if(!t.eql(t.sqr(r),s))throw new Error("Cannot find square root");return r}}if(i%Na===Ra){const e=(i-Ra)/Na;return function(t,s){const r=t.mul(s,Gt),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,Gt),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),s))throw new Error("Cannot find square root");return c}}return qp(i)}const Lp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Dp(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Lp.reduce((s,r)=>(s[r]="function",s),e);return cs(i,t)}function Fp(i,e,t){if(t<Se)throw new Error("invalid exponent, negatives unsupported");if(t===Se)return i.ONE;if(t===pe)return e;let s=i.ONE,r=e;for(;t>Se;)t&pe&&(s=i.mul(s,r)),r=i.sqr(r),t>>=pe;return s}function Mp(i,e){const t=new Array(e.length),s=e.reduce((n,o,a)=>i.is0(o)?n:(t[a]=n,i.mul(n,o)),i.ONE),r=i.inv(s);return e.reduceRight((n,o,a)=>i.is0(o)?n:(t[a]=i.mul(n,t[a]),i.mul(n,o)),r),t}function ul(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function dl(i,e,t=!1,s={}){if(i<=Se)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=ul(i,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:i,isLE:t,BITS:r,BYTES:n,MASK:Zo(r),ZERO:Se,ONE:pe,create:c=>Le(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Se<=c&&c<i},is0:c=>c===Se,isOdd:c=>(c&pe)===pe,neg:c=>Le(-c,i),eql:(c,h)=>c===h,sqr:c=>Le(c*c,i),add:(c,h)=>Le(c+h,i),sub:(c,h)=>Le(c-h,i),mul:(c,h)=>Le(c*h,i),pow:(c,h)=>Fp(a,c,h),div:(c,h)=>Le(c*so(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>so(c,i),sqrt:s.sqrt||(c=>(o||(o=kp(i)),o(a,c))),invertBatch:c=>Mp(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?Dr(c,n):Wi(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?Us(c):Xt(c)}});return Object.freeze(a)}function pl(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function fl(i){const e=pl(i);return e+Math.ceil(e/2)}function zp(i,e,t=!1){const s=i.length,r=pl(e),n=fl(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?Us(i):Xt(i),a=Le(o,e-pe)+pe;return t?Dr(a,r):Wi(a,r)}const Ta=BigInt(0),or=BigInt(1);function hn(i,e){const t=e.negate();return i?t:e}function gl(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function ln(i,e){gl(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function Hp(i,e){if(!Array.isArray(i))throw new Error("array expected");i.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function Vp(i,e){if(!Array.isArray(i))throw new Error("array of scalars expected");i.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}const un=new WeakMap,yl=new WeakMap;function dn(i){return yl.get(i)||1}function Kp(i,e){return{constTimeNegate:hn,hasPrecomputes(t){return dn(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>Ta;)s&or&&(r=r.add(n)),n=n.double(),s>>=or;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=ln(s,e),o=[];let a=t,c=a;for(let h=0;h<r;h++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,s,r){const{windows:n,windowSize:o}=ln(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),l=2**t,u=BigInt(t);for(let p=0;p<n;p++){const g=p*o;let w=Number(r&h);r>>=u,w>o&&(w-=l,r+=or);const y=g,d=g+Math.abs(w)-1,m=p%2!==0,f=w<0;w===0?c=c.add(hn(m,s[y])):a=a.add(hn(f,s[d]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=ln(t,e),c=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let u=0;u<o;u++){const p=u*a;if(r===Ta)break;let g=Number(r&c);if(r>>=l,g>a&&(g-=h,r+=or),g===0)continue;let w=s[p+Math.abs(g)-1];g<0&&(w=w.negate()),n=n.add(w)}return n},getPrecomputes(t,s,r){let n=un.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&un.set(s,r(n))),n},wNAFCached(t,s,r){const n=dn(t);return this.wNAF(n,this.getPrecomputes(n,t,r),s)},wNAFCachedUnsafe(t,s,r,n){const o=dn(t);return o===1?this.unsafeLadder(t,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,r),s,n)},setWindowSize(t,s){gl(s,e),yl.set(t,s),un.delete(t)}}}function Gp(i,e,t,s){if(Hp(t,i),Vp(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=cl(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r),h=Math.floor((e.BITS-1)/o)*o;let l=r;for(let u=h;u>=0;u-=o){c.fill(r);for(let g=0;g<s.length;g++){const w=s[g],y=Number(w>>BigInt(u)&BigInt(a));c[y]=c[y].add(t[g])}let p=r;for(let g=c.length-1,w=r;g>0;g--)w=w.add(c[g]),p=p.add(w);if(l=l.add(p),u!==0)for(let g=0;g<o;g++)l=l.double()}return l}function wl(i){return Dp(i.Fp),cs(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ul(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const fi=BigInt(0),pn=BigInt(1);function Wp(i){return cs(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function Zp(i){const e=Wp(i),{P:t}=e,s=f=>Le(f,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(f=>f),c=e.powPminus2||(f=>ll(f,t-BigInt(2),t));function h(f,E,_){const C=s(f*(E-_));return E=s(E-C),_=s(_+C),[E,_]}const l=(e.a-BigInt(2))/BigInt(4);function u(f,E){Nt("u",f,fi,t),Nt("scalar",E,fi,t);const _=E,C=f;let O=pn,P=fi,R=f,S=pn,U=fi,N;for(let j=BigInt(r-1);j>=fi;j--){const b=_>>j&pn;U^=b,N=h(U,O,R),O=N[0],R=N[1],N=h(U,P,S),P=N[0],S=N[1],U=b;const I=O+P,$=s(I*I),A=O-P,T=s(A*A),x=$-T,q=R+S,k=R-S,L=s(k*I),M=s(q*A),F=L+M,H=L-M;R=s(F*F),S=s(C*s(H*H)),O=s($*T),P=s(x*($+s(l*x)))}N=h(U,O,R),O=N[0],R=N[1],N=h(U,P,S),P=N[0],S=N[1];const B=c(P);return s(O*B)}function p(f){return Dr(s(f),n)}function g(f){const E=Ke("u coordinate",f,n);return o===32&&(E[31]&=127),Us(E)}function w(f){const E=Ke("scalar",f),_=E.length;if(_!==n&&_!==o){let C=""+n+" or "+o;throw new Error("invalid scalar, expected "+C+" bytes, got "+_)}return Us(a(E))}function y(f,E){const _=g(E),C=w(f),O=u(_,C);if(O===fi)throw new Error("invalid private or public key received");return p(O)}const d=p(e.Gu);function m(f){return y(f,d)}return{scalarMult:y,scalarMultBase:m,getSharedSecret:(f,E)=>y(f,E),getPublicKey:f=>m(f),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:d}}const ro=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Jp=BigInt(1),Ca=BigInt(2),Yp=BigInt(3),Qp=BigInt(5);BigInt(8);function Xp(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=ro,o=i*i%n*i%n,a=ct(o,Ca,n)*o%n,c=ct(a,Jp,n)*i%n,h=ct(c,Qp,n)*c%n,l=ct(h,e,n)*h%n,u=ct(l,t,n)*l%n,p=ct(u,s,n)*u%n,g=ct(p,r,n)*p%n,w=ct(g,r,n)*p%n,y=ct(w,e,n)*h%n;return{pow_p_5_8:ct(y,Ca,n)*i%n,b2:o}}function ef(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}Zp({P:ro,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=ro,{pow_p_5_8:t,b2:s}=Xp(i);return Le(ct(t,Yp,e)*s,e)},adjustScalarBytes:ef,randomBytes:Qh});function Ba(i){i.lowS!==void 0&&Vi("lowS",i.lowS),i.prehash!==void 0&&Vi("prehash",i.prehash)}function tf(i){const e=wl(i);cs(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:s,a:r}=e;if(t){if(!s.eql(r,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:sf,hexToBytes:rf}=Up;let nf=class extends Error{constructor(e=""){super(e)}};const xt={Err:nf,_tlv:{encode:(i,e)=>{const{Err:t}=xt;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const s=e.length/2,r=qi(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?qi(r.length/2|128):"";return qi(i)+n+r+e},decode(i,e){const{Err:t}=xt;let s=0;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==i)throw new t("tlv.decode: wrong tlv");const r=e[s++],n=!!(r&128);let o=0;if(!n)o=r;else{const c=r&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const h=e.subarray(s,s+c);if(h.length!==c)throw new t("tlv.decode: length bytes not complete");if(h[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const l of h)o=o<<8|l;if(s+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(s,s+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(i){const{Err:e}=xt;if(i<Ot)throw new e("integer: negative integers are not allowed");let t=qi(i);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(i){const{Err:e}=xt;if(i[0]&128)throw new e("invalid signature integer: negative");if(i[0]===0&&!(i[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return sf(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=xt,r=typeof i=="string"?rf(i):i;Gs(r);const{v:n,l:o}=s.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l}=s.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(h)}},hexFromSig(i){const{_tlv:e,_int:t}=xt,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},Ot=BigInt(0),be=BigInt(1);BigInt(2);const Ua=BigInt(3);BigInt(4);function of(i){const e=tf(i),{Fp:t}=e,s=dl(e.n,e.nBitLength),r=e.toBytes||((y,d,m)=>{const f=d.toAffine();return js(Uint8Array.from([4]),t.toBytes(f.x),t.toBytes(f.y))}),n=e.fromBytes||(y=>{const d=y.subarray(1),m=t.fromBytes(d.subarray(0,t.BYTES)),f=t.fromBytes(d.subarray(t.BYTES,2*t.BYTES));return{x:m,y:f}});function o(y){const{a:d,b:m}=e,f=t.sqr(y),E=t.mul(f,y);return t.add(t.add(E,t.mul(y,d)),m)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Fr(y,be,e.n)}function c(y){const{allowedPrivateKeyLengths:d,nByteLength:m,wrapPrivateKey:f,n:E}=e;if(d&&typeof y!="bigint"){if(ri(y)&&(y=Ki(y)),typeof y!="string"||!d.includes(y.length))throw new Error("invalid private key");y=y.padStart(m*2,"0")}let _;try{_=typeof y=="bigint"?y:Xt(Ke("private key",y,m))}catch{throw new Error("invalid private key, expected hex or "+m+" bytes, got "+typeof y)}return f&&(_=Le(_,E)),Nt("private key",_,be,E),_}function h(y){if(!(y instanceof p))throw new Error("ProjectivePoint expected")}const l=to((y,d)=>{const{px:m,py:f,pz:E}=y;if(t.eql(E,t.ONE))return{x:m,y:f};const _=y.is0();d==null&&(d=_?t.ONE:t.inv(E));const C=t.mul(m,d),O=t.mul(f,d),P=t.mul(E,d);if(_)return{x:t.ZERO,y:t.ZERO};if(!t.eql(P,t.ONE))throw new Error("invZ was invalid");return{x:C,y:O}}),u=to(y=>{if(y.is0()){if(e.allowInfinityPoint&&!t.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:d,y:m}=y.toAffine();if(!t.isValid(d)||!t.isValid(m))throw new Error("bad point: x or y not FE");const f=t.sqr(m),E=o(d);if(!t.eql(f,E))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class p{constructor(d,m,f){if(this.px=d,this.py=m,this.pz=f,d==null||!t.isValid(d))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(f==null||!t.isValid(f))throw new Error("z required");Object.freeze(this)}static fromAffine(d){const{x:m,y:f}=d||{};if(!d||!t.isValid(m)||!t.isValid(f))throw new Error("invalid affine point");if(d instanceof p)throw new Error("projective point not allowed");const E=_=>t.eql(_,t.ZERO);return E(m)&&E(f)?p.ZERO:new p(m,f,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){const m=t.invertBatch(d.map(f=>f.pz));return d.map((f,E)=>f.toAffine(m[E])).map(p.fromAffine)}static fromHex(d){const m=p.fromAffine(n(Ke("pointHex",d)));return m.assertValidity(),m}static fromPrivateKey(d){return p.BASE.multiply(c(d))}static msm(d,m){return Gp(p,s,d,m)}_setWindowSize(d){w.setWindowSize(this,d)}assertValidity(){u(this)}hasEvenY(){const{y:d}=this.toAffine();if(t.isOdd)return!t.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){h(d);const{px:m,py:f,pz:E}=this,{px:_,py:C,pz:O}=d,P=t.eql(t.mul(m,O),t.mul(_,E)),R=t.eql(t.mul(f,O),t.mul(C,E));return P&&R}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:d,b:m}=e,f=t.mul(m,Ua),{px:E,py:_,pz:C}=this;let O=t.ZERO,P=t.ZERO,R=t.ZERO,S=t.mul(E,E),U=t.mul(_,_),N=t.mul(C,C),B=t.mul(E,_);return B=t.add(B,B),R=t.mul(E,C),R=t.add(R,R),O=t.mul(d,R),P=t.mul(f,N),P=t.add(O,P),O=t.sub(U,P),P=t.add(U,P),P=t.mul(O,P),O=t.mul(B,O),R=t.mul(f,R),N=t.mul(d,N),B=t.sub(S,N),B=t.mul(d,B),B=t.add(B,R),R=t.add(S,S),S=t.add(R,S),S=t.add(S,N),S=t.mul(S,B),P=t.add(P,S),N=t.mul(_,C),N=t.add(N,N),S=t.mul(N,B),O=t.sub(O,S),R=t.mul(N,U),R=t.add(R,R),R=t.add(R,R),new p(O,P,R)}add(d){h(d);const{px:m,py:f,pz:E}=this,{px:_,py:C,pz:O}=d;let P=t.ZERO,R=t.ZERO,S=t.ZERO;const U=e.a,N=t.mul(e.b,Ua);let B=t.mul(m,_),j=t.mul(f,C),b=t.mul(E,O),I=t.add(m,f),$=t.add(_,C);I=t.mul(I,$),$=t.add(B,j),I=t.sub(I,$),$=t.add(m,E);let A=t.add(_,O);return $=t.mul($,A),A=t.add(B,b),$=t.sub($,A),A=t.add(f,E),P=t.add(C,O),A=t.mul(A,P),P=t.add(j,b),A=t.sub(A,P),S=t.mul(U,$),P=t.mul(N,b),S=t.add(P,S),P=t.sub(j,S),S=t.add(j,S),R=t.mul(P,S),j=t.add(B,B),j=t.add(j,B),b=t.mul(U,b),$=t.mul(N,$),j=t.add(j,b),b=t.sub(B,b),b=t.mul(U,b),$=t.add($,b),B=t.mul(j,$),R=t.add(R,B),B=t.mul(A,$),P=t.mul(I,P),P=t.sub(P,B),B=t.mul(I,j),S=t.mul(A,S),S=t.add(S,B),new p(P,R,S)}subtract(d){return this.add(d.negate())}is0(){return this.equals(p.ZERO)}wNAF(d){return w.wNAFCached(this,d,p.normalizeZ)}multiplyUnsafe(d){const{endo:m,n:f}=e;Nt("scalar",d,Ot,f);const E=p.ZERO;if(d===Ot)return E;if(this.is0()||d===be)return this;if(!m||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,d,p.normalizeZ);let{k1neg:_,k1:C,k2neg:O,k2:P}=m.splitScalar(d),R=E,S=E,U=this;for(;C>Ot||P>Ot;)C&be&&(R=R.add(U)),P&be&&(S=S.add(U)),U=U.double(),C>>=be,P>>=be;return _&&(R=R.negate()),O&&(S=S.negate()),S=new p(t.mul(S.px,m.beta),S.py,S.pz),R.add(S)}multiply(d){const{endo:m,n:f}=e;Nt("scalar",d,be,f);let E,_;if(m){const{k1neg:C,k1:O,k2neg:P,k2:R}=m.splitScalar(d);let{p:S,f:U}=this.wNAF(O),{p:N,f:B}=this.wNAF(R);S=w.constTimeNegate(C,S),N=w.constTimeNegate(P,N),N=new p(t.mul(N.px,m.beta),N.py,N.pz),E=S.add(N),_=U.add(B)}else{const{p:C,f:O}=this.wNAF(d);E=C,_=O}return p.normalizeZ([E,_])[0]}multiplyAndAddUnsafe(d,m,f){const E=p.BASE,_=(O,P)=>P===Ot||P===be||!O.equals(E)?O.multiplyUnsafe(P):O.multiply(P),C=_(this,m).add(_(d,f));return C.is0()?void 0:C}toAffine(d){return l(this,d)}isTorsionFree(){const{h:d,isTorsionFree:m}=e;if(d===be)return!0;if(m)return m(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:d,clearCofactor:m}=e;return d===be?this:m?m(p,this):this.multiplyUnsafe(e.h)}toRawBytes(d=!0){return Vi("isCompressed",d),this.assertValidity(),r(p,this,d)}toHex(d=!0){return Vi("isCompressed",d),Ki(this.toRawBytes(d))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const g=e.nBitLength,w=Kp(p,e.endo?Math.ceil(g/2):g);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function af(i){const e=wl(i);return cs(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function cf(i){const e=af(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(b){return Le(b,s)}function a(b){return so(b,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=of({...e,toBytes(b,I,$){const A=I.toAffine(),T=t.toBytes(A.x),x=js;return Vi("isCompressed",$),$?x(Uint8Array.from([I.hasEvenY()?2:3]),T):x(Uint8Array.from([4]),T,t.toBytes(A.y))},fromBytes(b){const I=b.length,$=b[0],A=b.subarray(1);if(I===r&&($===2||$===3)){const T=Xt(A);if(!Fr(T,be,t.ORDER))throw new Error("Point is not on curve");const x=l(T);let q;try{q=t.sqrt(x)}catch(L){const M=L instanceof Error?": "+L.message:"";throw new Error("Point is not on curve"+M)}const k=(q&be)===be;return($&1)===1!==k&&(q=t.neg(q)),{x:T,y:q}}else if(I===n&&$===4){const T=t.fromBytes(A.subarray(0,t.BYTES)),x=t.fromBytes(A.subarray(t.BYTES,2*t.BYTES));return{x:T,y:x}}else{const T=r,x=n;throw new Error("invalid Point, expected length of "+T+", or uncompressed "+x+", got "+I)}}}),p=b=>Ki(Wi(b,e.nByteLength));function g(b){const I=s>>be;return b>I}function w(b){return g(b)?o(-b):b}const y=(b,I,$)=>Xt(b.slice(I,$));class d{constructor(I,$,A){this.r=I,this.s=$,this.recovery=A,this.assertValidity()}static fromCompact(I){const $=e.nByteLength;return I=Ke("compactSignature",I,$*2),new d(y(I,0,$),y(I,$,2*$))}static fromDER(I){const{r:$,s:A}=xt.toSig(Ke("DER",I));return new d($,A)}assertValidity(){Nt("r",this.r,be,s),Nt("s",this.s,be,s)}addRecoveryBit(I){return new d(this.r,this.s,I)}recoverPublicKey(I){const{r:$,s:A,recovery:T}=this,x=O(Ke("msgHash",I));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");const q=T===2||T===3?$+e.n:$;if(q>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const k=(T&1)===0?"02":"03",L=c.fromHex(k+p(q)),M=a(q),F=o(-x*M),H=o(A*M),K=c.BASE.multiplyAndAddUnsafe(L,F,H);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new d(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Gi(this.toDERHex())}toDERHex(){return xt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Gi(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const m={isValidPrivateKey(b){try{return h(b),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const b=fl(e.n);return zp(e.randomBytes(b),e.n)},precompute(b=8,I=c.BASE){return I._setWindowSize(b),I.multiply(BigInt(3)),I}};function f(b,I=!0){return c.fromPrivateKey(b).toRawBytes(I)}function E(b){const I=ri(b),$=typeof b=="string",A=(I||$)&&b.length;return I?A===r||A===n:$?A===2*r||A===2*n:b instanceof c}function _(b,I,$=!0){if(E(b))throw new Error("first arg must be private key");if(!E(I))throw new Error("second arg must be public key");return c.fromHex(I).multiply(h(b)).toRawBytes($)}const C=e.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const I=Xt(b),$=b.length*8-e.nBitLength;return $>0?I>>BigInt($):I},O=e.bits2int_modN||function(b){return o(C(b))},P=Zo(e.nBitLength);function R(b){return Nt("num < 2^"+e.nBitLength,b,Ot,P),Wi(b,e.nByteLength)}function S(b,I,$=U){if(["recovered","canonical"].some(G=>G in $))throw new Error("sign() legacy options not supported");const{hash:A,randomBytes:T}=e;let{lowS:x,prehash:q,extraEntropy:k}=$;x==null&&(x=!0),b=Ke("msgHash",b),Ba($),q&&(b=Ke("prehashed msgHash",A(b)));const L=O(b),M=h(I),F=[R(M),R(L)];if(k!=null&&k!==!1){const G=k===!0?T(t.BYTES):k;F.push(Ke("extraEntropy",G))}const H=js(...F),K=L;function Z(G){const W=C(G);if(!u(W))return;const Be=a(W),ue=c.BASE.multiply(W).toAffine(),ae=o(ue.x);if(ae===Ot)return;const he=o(Be*o(K+ae*M));if(he===Ot)return;let Xe=(ue.x===ae?0:2)|Number(ue.y&be),dt=he;return x&&g(he)&&(dt=w(he),Xe^=1),new d(ae,dt,Xe)}return{seed:H,k2sig:Z}}const U={lowS:e.lowS,prehash:!1},N={lowS:e.lowS,prehash:!1};function B(b,I,$=U){const{seed:A,k2sig:T}=S(b,I,$),x=e;return hl(x.hash.outputLen,x.nByteLength,x.hmac)(A,T)}c.BASE._setWindowSize(8);function j(b,I,$,A=N){const T=b;I=Ke("msgHash",I),$=Ke("publicKey",$);const{lowS:x,prehash:q,format:k}=A;if(Ba(A),"strict"in A)throw new Error("options.strict was renamed to lowS");if(k!==void 0&&k!=="compact"&&k!=="der")throw new Error("format must be compact or der");const L=typeof T=="string"||ri(T),M=!L&&!k&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!L&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,H;try{if(M&&(F=new d(T.r,T.s)),L){try{k!=="compact"&&(F=d.fromDER(T))}catch(he){if(!(he instanceof xt.Err))throw he}!F&&k!=="der"&&(F=d.fromCompact(T))}H=c.fromHex($)}catch{return!1}if(!F||x&&F.hasHighS())return!1;q&&(I=e.hash(I));const{r:K,s:Z}=F,G=O(I),W=a(Z),Be=o(G*W),ue=o(K*W),ae=c.BASE.multiplyAndAddUnsafe(H,Be,ue)?.toAffine();return ae?o(ae.x)===K:!1}return{CURVE:e,getPublicKey:f,getSharedSecret:_,sign:B,verify:j,ProjectivePoint:c,Signature:d,utils:m}}function hf(i){return{hash:i,hmac:(e,...t)=>al(i,e,Ld(...t)),randomBytes:Qh}}function lf(i,e){const t=s=>cf({...i,...hf(s)});return{...t(e),create:t}}const ml=dl(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),uf=ml.create(BigInt("-3")),df=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");lf({a:uf,b:df,Fp:ml,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},xp);function Jo(i){return i.includes(":")}function _s(i){return Jo(i)?i.split(":")[0]:i}const pf={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}};function no(i,e){const{message:t,code:s}=pf[i];return{message:t,code:s}}function Mi(i,e){return!!Array.isArray(i)}function fn(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}var ff=Object.defineProperty,gf=(i,e,t)=>e in i?ff(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ja=(i,e,t)=>gf(i,typeof e!="symbol"?e+"":e,t);let yf=class extends v.IEvents{constructor(e){super(),this.opts=e,ja(this,"protocol","wc"),ja(this,"version",2)}};var wf=Object.defineProperty,mf=(i,e,t)=>e in i?wf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bf=(i,e,t)=>mf(i,e+"",t);let vf=class extends v.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,bf(this,"records",new Map)}},Ef=class{constructor(e,t){this.logger=e,this.core=t}};class $f extends v.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}let If=class extends v.IEvents{constructor(e){super()}},Sf=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},xf=class extends v.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},Pf=class extends v.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},_f=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},Of=class{constructor(e,t){this.projectId=e,this.logger=t}},Af=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var Rf=Object.defineProperty,Nf=(i,e,t)=>e in i?Rf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qa=(i,e,t)=>Nf(i,typeof e!="symbol"?e+"":e,t);let Tf=class{constructor(e){this.opts=e,qa(this,"protocol","wc"),qa(this,"version",2)}},Cf=class{constructor(e){this.client=e}};function Bf(i){if(i.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<i.length;h++){const l=i.charAt(h),u=l.charCodeAt(0);if(e[u]!==255)throw new TypeError(l+" is ambiguous");e[u]=h}const t=i.length,s=i.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let l=0,u=0,p=0;const g=h.length;for(;p!==g&&h[p]===0;)p++,l++;const w=(g-p)*n+1>>>0,y=new Uint8Array(w);for(;p!==g;){let f=h[p],E=0;for(let _=w-1;(f!==0||E<u)&&_!==-1;_--,E++)f+=256*y[_]>>>0,y[_]=f%t>>>0,f=f/t>>>0;if(f!==0)throw new Error("Non-zero carry");u=E,p++}let d=w-u;for(;d!==w&&y[d]===0;)d++;let m=s.repeat(l);for(;d<w;++d)m+=i.charAt(y[d]);return m}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,u=0,p=0;for(;h[l]===s;)u++,l++;const g=(h.length-l)*r+1>>>0,w=new Uint8Array(g);for(;l<h.length;){const f=h.charCodeAt(l);if(f>255)return;let E=e[f];if(E===255)return;let _=0;for(let C=g-1;(E!==0||_<p)&&C!==-1;C--,_++)E+=t*w[C]>>>0,w[C]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");p=_,l++}let y=g-p;for(;y!==g&&w[y]===0;)y++;const d=new Uint8Array(u+(g-y));let m=u;for(;y!==g;)d[m++]=w[y++];return d}function c(h){const l=a(h);if(l)return l;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Uf="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";Bf(Uf);const jf="ReactNative",ut={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},qf="js";function Or(){return typeof z.process$1<"u"&&typeof z.process$1.versions<"u"&&typeof z.process$1.versions.node<"u"}function li(){return!v.cjsExports$2.getDocument()&&!!v.cjsExports$2.getNavigator()&&navigator.product===jf}function kf(){return li()&&typeof z.global<"u"&&typeof(z.global==null?void 0:z.global.Platform)<"u"&&(z.global==null?void 0:z.global.Platform.OS)==="android"}function Lf(){return li()&&typeof z.global<"u"&&typeof(z.global==null?void 0:z.global.Platform)<"u"&&(z.global==null?void 0:z.global.Platform.OS)==="ios"}function Ws(){return!Or()&&!!v.cjsExports$2.getNavigator()&&!!v.cjsExports$2.getDocument()}function Mr(){return li()?ut.reactNative:Or()?ut.node:Ws()?ut.browser:ut.unknown}function ka(){var i;try{return li()&&typeof z.global<"u"&&typeof(z.global==null?void 0:z.global.Application)<"u"?(i=z.global.Application)==null?void 0:i.applicationId:void 0}catch{return}}function Df(i,e){const t=new URLSearchParams(i);for(const s of Object.keys(e).sort())if(e.hasOwnProperty(s)){const r=e[s];r!==void 0&&t.set(s,r)}return t.toString()}function Ff(){return v.cjsExports.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Mf(){if(Mr()===ut.reactNative&&typeof z.global<"u"&&typeof(z.global==null?void 0:z.global.Platform)<"u"){const{OS:t,Version:s}=z.global.Platform;return[t,s].join("-")}const i=v.detect();if(i===null)return"unknown";const e=i.os?i.os.replace(" ","").toLowerCase():"unknown";return i.type==="browser"?[e,i.name,i.version].join("-"):[e,i.version].join("-")}function zf(){var i;const e=Mr();return e===ut.browser?[e,((i=v.cjsExports$2.getLocation())==null?void 0:i.host)||"unknown"].join(":"):e}function bl(i,e,t){const s=Mf(),r=zf();return[[i,e].join("-"),[qf,t].join("-"),s,r].join("/")}function Hf({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=bl(i,e,s),u={auth:r,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=Df(h[1]||"",u);return h[0]+"?"+p}function oo(i){return Object.fromEntries(i.entries())}function ao(i){return new Map(Object.entries(i))}function Vf(i=v.cjsExports$1.FIVE_MINUTES,e){const t=v.cjsExports$1.toMiliseconds(i||v.cjsExports$1.FIVE_MINUTES);let s,r,n,o;return{resolve:a=>{n&&s&&(clearTimeout(n),s(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const h=new Error(e);o=Promise.reject(h),c(h)},t),s=a,r=c})}}function Dt(i,e,t){return new Promise(async(s,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await i;s(o)}catch(o){r(o)}clearTimeout(n)})}function vl(i,e){if(typeof e=="string"&&e.startsWith(`${i}:`))return e;if(i.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(i.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: ${i}`)}function Kf(i){return vl("topic",i)}function Gf(i){return vl("id",i)}function Wf(i){const[e,t]=i.split(":"),s={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")s.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))s.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return s}function Ns(i,e){return v.cjsExports$1.fromMiliseconds(Date.now()+v.cjsExports$1.toMiliseconds(i))}function La(i){return Date.now()>=v.cjsExports$1.toMiliseconds(i)}function gn(i,e){return`${i}${e?`:${e}`:""}`}function Da(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function El(){return typeof z.process$1<"u"&&z.process$1.env.IS_VITEST==="true"}function $l(i){return z.Buffer.from(i,"base64").toString("utf-8")}function Zf(i){return new Promise(e=>setTimeout(e,i))}function qs(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Jf(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Zs(i,...e){if(!Jf(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Yo(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");qs(i.outputLen),qs(i.blockLen)}function Zi(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Il(i,e){Zs(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ar=BigInt(2**32-1),Fa=BigInt(32);function Yf(i,e=!1){return e?{h:Number(i&ar),l:Number(i>>Fa&ar)}:{h:Number(i>>Fa&ar)|0,l:Number(i&ar)|0}}function Qf(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=Yf(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Xf=(i,e,t)=>i<<t|e>>>32-t,eg=(i,e,t)=>e<<t|i>>>32-t,tg=(i,e,t)=>e<<t-32|i>>>64-t,ig=(i,e,t)=>i<<t-32|e>>>64-t,gi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function sg(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function yn(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function ft(i,e){return i<<32-e|i>>>e}const Ma=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function rg(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function za(i){for(let e=0;e<i.length;e++)i[e]=rg(i[e])}function ng(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function Ji(i){return typeof i=="string"&&(i=ng(i)),Zs(i),i}function og(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Zs(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}let Qo=class{clone(){return this._cloneInto()}};function Sl(i){const e=s=>i().update(Ji(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function hs(i=32){if(gi&&typeof gi.getRandomValues=="function")return gi.getRandomValues(new Uint8Array(i));if(gi&&typeof gi.randomBytes=="function")return gi.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const xl=[],Pl=[],_l=[],ag=BigInt(0),ws=BigInt(1),cg=BigInt(2),hg=BigInt(7),lg=BigInt(256),ug=BigInt(113);for(let i=0,e=ws,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],xl.push(2*(5*s+t)),Pl.push((i+1)*(i+2)/2%64);let r=ag;for(let n=0;n<7;n++)e=(e<<ws^(e>>hg)*ug)%lg,e&cg&&(r^=ws<<(ws<<BigInt(n))-ws);_l.push(r)}const[dg,pg]=Qf(_l,!0),Ha=(i,e,t)=>t>32?tg(i,e,t):Xf(i,e,t),Va=(i,e,t)=>t>32?ig(i,e,t):eg(i,e,t);function fg(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=Ha(h,l,1)^t[a],p=Va(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Pl[o],c=Ha(r,n,a),h=Va(r,n,a),l=xl[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=dg[s],i[1]^=pg[s]}t.fill(0)}let gg=class Ol extends Qo{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,qs(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=sg(this.state)}keccak(){Ma||za(this.state32),fg(this.state32,this.rounds),Ma||za(this.state32),this.posOut=0,this.pos=0}update(e){Zi(this);const{blockLen:t,state:s}=this;e=Ji(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Zi(this,!1),Zs(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 qs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Il(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:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Ol(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const yg=(i,e,t)=>Sl(()=>new gg(e,i,t));yg(1,136,256/8);function wn(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Al(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Je(i,...e){if(!Al(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Ka(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function wg(i,e){Je(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Ga(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const Mt=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),mg=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),bg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!bg)throw new Error("Non little-endian hardware is not supported");function vg(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function co(i){if(typeof i=="string")i=vg(i);else if(Al(i))i=ho(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function Eg(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function $g(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}const Ig=(i,e)=>{function t(s,...r){if(Je(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?Je(h):Je(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&Je(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");Je(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Je(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(Je(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(h,l)}}}return Object.assign(t,i),t};function Wa(i,e,t=!0){if(e===void 0)return new Uint8Array(i);if(e.length!==i)throw new Error("invalid output length, expected "+i+", got: "+e.length);if(t&&!Sg(e))throw new Error("invalid output, must be aligned");return e}function Za(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);i.setUint32(e+4,o,s),i.setUint32(e+0,a,s)}function Sg(i){return i.byteOffset%4===0}function ho(i){return Uint8Array.from(i)}function Yi(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const Rl=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),xg=Rl("expand 16-byte k"),Pg=Rl("expand 32-byte k"),_g=Mt(xg),Og=Mt(Pg);function X(i,e){return i<<e|i>>>32-e}function lo(i){return i.byteOffset%4===0}const cr=64,Ag=16,Nl=2**32-1,Ja=new Uint32Array;function Rg(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(cr),l=Mt(h),u=lo(r)&&lo(n),p=u?Mt(r):Ja,g=u?Mt(n):Ja;for(let w=0;w<c;o++){if(i(e,t,s,l,o,a),o>=Nl)throw new Error("arx: counter overflow");const y=Math.min(cr,c-w);if(u&&y===cr){const d=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let m=0,f;m<Ag;m++)f=d+m,g[f]=p[f]^l[m];w+=cr;continue}for(let d=0,m;d<y;d++)m=w+d,n[m]=r[m]^h[d];w+=y}}function Ng(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=Eg({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return wn(r),wn(o),Ga(n),Ga(t),(a,c,h,l,u=0)=>{Je(a),Je(c),Je(h);const p=h.length;if(l===void 0&&(l=new Uint8Array(p)),Je(l),wn(u),u<0||u>=Nl)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const g=[];let w=a.length,y,d;if(w===32)g.push(y=ho(a)),d=Og;else if(w===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),d=_g,g.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${w}`);lo(c)||g.push(c=ho(c));const m=Mt(y);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(d,m,Mt(c.subarray(0,16)),m),c=c.subarray(16)}const f=16-r;if(f!==c.length)throw new Error(`arx: nonce must be ${f} or 16 bytes`);if(f!==12){const _=new Uint8Array(12);_.set(c,n?0:12-c.length),c=_,g.push(c)}const E=Mt(c);return Rg(i,d,m,E,h,l,u,o),Yi(...g),l}}const Oe=(i,e)=>i[e++]&255|(i[e++]&255)<<8;let Tg=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=co(e),Je(e,32);const t=Oe(e,0),s=Oe(e,2),r=Oe(e,4),n=Oe(e,6),o=Oe(e,8),a=Oe(e,10),c=Oe(e,12),h=Oe(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>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|c<<5)&8065,this.r[8]=(c>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Oe(e,16+2*l)}process(e,t,s=!1){const r=s?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],l=o[3],u=o[4],p=o[5],g=o[6],w=o[7],y=o[8],d=o[9],m=Oe(e,t+0),f=Oe(e,t+2),E=Oe(e,t+4),_=Oe(e,t+6),C=Oe(e,t+8),O=Oe(e,t+10),P=Oe(e,t+12),R=Oe(e,t+14);let S=n[0]+(m&8191),U=n[1]+((m>>>13|f<<3)&8191),N=n[2]+((f>>>10|E<<6)&8191),B=n[3]+((E>>>7|_<<9)&8191),j=n[4]+((_>>>4|C<<12)&8191),b=n[5]+(C>>>1&8191),I=n[6]+((C>>>14|O<<2)&8191),$=n[7]+((O>>>11|P<<5)&8191),A=n[8]+((P>>>8|R<<8)&8191),T=n[9]+(R>>>5|r),x=0,q=x+S*a+U*(5*d)+N*(5*y)+B*(5*w)+j*(5*g);x=q>>>13,q&=8191,q+=b*(5*p)+I*(5*u)+$*(5*l)+A*(5*h)+T*(5*c),x+=q>>>13,q&=8191;let k=x+S*c+U*a+N*(5*d)+B*(5*y)+j*(5*w);x=k>>>13,k&=8191,k+=b*(5*g)+I*(5*p)+$*(5*u)+A*(5*l)+T*(5*h),x+=k>>>13,k&=8191;let L=x+S*h+U*c+N*a+B*(5*d)+j*(5*y);x=L>>>13,L&=8191,L+=b*(5*w)+I*(5*g)+$*(5*p)+A*(5*u)+T*(5*l),x+=L>>>13,L&=8191;let M=x+S*l+U*h+N*c+B*a+j*(5*d);x=M>>>13,M&=8191,M+=b*(5*y)+I*(5*w)+$*(5*g)+A*(5*p)+T*(5*u),x+=M>>>13,M&=8191;let F=x+S*u+U*l+N*h+B*c+j*a;x=F>>>13,F&=8191,F+=b*(5*d)+I*(5*y)+$*(5*w)+A*(5*g)+T*(5*p),x+=F>>>13,F&=8191;let H=x+S*p+U*u+N*l+B*h+j*c;x=H>>>13,H&=8191,H+=b*a+I*(5*d)+$*(5*y)+A*(5*w)+T*(5*g),x+=H>>>13,H&=8191;let K=x+S*g+U*p+N*u+B*l+j*h;x=K>>>13,K&=8191,K+=b*c+I*a+$*(5*d)+A*(5*y)+T*(5*w),x+=K>>>13,K&=8191;let Z=x+S*w+U*g+N*p+B*u+j*l;x=Z>>>13,Z&=8191,Z+=b*h+I*c+$*a+A*(5*d)+T*(5*y),x+=Z>>>13,Z&=8191;let G=x+S*y+U*w+N*g+B*p+j*u;x=G>>>13,G&=8191,G+=b*l+I*h+$*c+A*a+T*(5*d),x+=G>>>13,G&=8191;let W=x+S*d+U*y+N*w+B*g+j*p;x=W>>>13,W&=8191,W+=b*u+I*l+$*h+A*c+T*a,x+=W>>>13,W&=8191,x=(x<<2)+x|0,x=x+q|0,q=x&8191,x=x>>>13,k+=x,n[0]=q,n[1]=k,n[2]=L,n[3]=M,n[4]=F,n[5]=H,n[6]=K,n[7]=Z,n[8]=G,n[9]=W}finalize(){const{h:e,pad:t}=this,s=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,s[0]=e[0]+5,r=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+r,r=s[a]>>>13,s[a]&=8191;s[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)s[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|s[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;Yi(s)}update(e){Ka(this);const{buffer:t,blockLen:s}=this;e=co(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o===s){for(;s<=r-n;n+=s)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Yi(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ka(this),wg(e,this),this.finished=!0;const{buffer:t,h:s}=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++]=s[o]>>>0,e[n++]=s[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}};function Cg(i){const e=(s,r)=>i(r).update(co(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const Bg=Cg(i=>new Tg(i));function Ug(i,e,t,s,r,n=20){let o=i[0],a=i[1],c=i[2],h=i[3],l=e[0],u=e[1],p=e[2],g=e[3],w=e[4],y=e[5],d=e[6],m=e[7],f=r,E=t[0],_=t[1],C=t[2],O=o,P=a,R=c,S=h,U=l,N=u,B=p,j=g,b=w,I=y,$=d,A=m,T=f,x=E,q=_,k=C;for(let M=0;M<n;M+=2)O=O+U|0,T=X(T^O,16),b=b+T|0,U=X(U^b,12),O=O+U|0,T=X(T^O,8),b=b+T|0,U=X(U^b,7),P=P+N|0,x=X(x^P,16),I=I+x|0,N=X(N^I,12),P=P+N|0,x=X(x^P,8),I=I+x|0,N=X(N^I,7),R=R+B|0,q=X(q^R,16),$=$+q|0,B=X(B^$,12),R=R+B|0,q=X(q^R,8),$=$+q|0,B=X(B^$,7),S=S+j|0,k=X(k^S,16),A=A+k|0,j=X(j^A,12),S=S+j|0,k=X(k^S,8),A=A+k|0,j=X(j^A,7),O=O+N|0,k=X(k^O,16),$=$+k|0,N=X(N^$,12),O=O+N|0,k=X(k^O,8),$=$+k|0,N=X(N^$,7),P=P+B|0,T=X(T^P,16),A=A+T|0,B=X(B^A,12),P=P+B|0,T=X(T^P,8),A=A+T|0,B=X(B^A,7),R=R+j|0,x=X(x^R,16),b=b+x|0,j=X(j^b,12),R=R+j|0,x=X(x^R,8),b=b+x|0,j=X(j^b,7),S=S+U|0,q=X(q^S,16),I=I+q|0,U=X(U^I,12),S=S+U|0,q=X(q^S,8),I=I+q|0,U=X(U^I,7);let L=0;s[L++]=o+O|0,s[L++]=a+P|0,s[L++]=c+R|0,s[L++]=h+S|0,s[L++]=l+U|0,s[L++]=u+N|0,s[L++]=p+B|0,s[L++]=g+j|0,s[L++]=w+b|0,s[L++]=y+I|0,s[L++]=d+$|0,s[L++]=m+A|0,s[L++]=f+T|0,s[L++]=E+x|0,s[L++]=_+q|0,s[L++]=C+k|0}const jg=Ng(Ug,{counterRight:!1,counterLength:4,allowShortKeys:!1}),qg=new Uint8Array(16),Ya=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(qg.subarray(t))},kg=new Uint8Array(32);function Qa(i,e,t,s,r){const n=i(e,t,kg),o=Bg.create(n);r&&Ya(o,r),Ya(o,s);const a=new Uint8Array(16),c=mg(a);Za(c,0,BigInt(r?r.length:0),!0),Za(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return Yi(n,a),h}const Lg=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=Wa(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=Qa(i,e,t,a,s);return n.set(c,o),Yi(c),n},decrypt(r,n){n=Wa(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Qa(i,e,t,o,s);if(!$g(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),Yi(c),n}}),Tl=Ig({blockSize:64,nonceLength:12,tagLength:16},Lg(jg));let Cl=class extends Qo{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Yo(e);const s=Ji(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(s.length>r?e.create().update(s).digest():s);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 Zi(this),this.iHash.update(e),this}digestInto(e){Zi(this),Zs(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:s,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=s._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const zr=(i,e,t)=>new Cl(i,e).update(t).digest();zr.create=(i,e)=>new Cl(i,e);function Dg(i,e,t){return Yo(i),t===void 0&&(t=new Uint8Array(i.outputLen)),zr(i,Ji(t),Ji(e))}const mn=new Uint8Array([0]),Xa=new Uint8Array;function Fg(i,e,t,s=32){if(Yo(i),qs(s),s>255*i.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(s/i.outputLen);t===void 0&&(t=Xa);const n=new Uint8Array(r*i.outputLen),o=zr.create(i,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let h=0;h<r;h++)mn[0]=h+1,a.update(h===0?Xa:c).update(t).update(mn).digestInto(c),n.set(c,i.outputLen*h),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),mn.fill(0),n.slice(0,s)}const Mg=(i,e,t,s,r)=>Fg(i,Dg(i,e,t),s,r);function zg(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=s?4:0,h=s?0:4;i.setUint32(e+c,o,s),i.setUint32(e+h,a,s)}function Hg(i,e,t){return i&e^~i&t}function Vg(i,e,t){return i&e^i&t^e&t}let Kg=class extends Qo{constructor(e,t,s,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=yn(this.buffer)}update(e){Zi(this);const{view:t,buffer:s,blockLen:r}=this;e=Ji(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const c=yn(e);for(;r<=n-o;o+=r)this.process(c,o);continue}s.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){Zi(this),Il(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(s,0),o=0);for(let u=o;u<r;u++)t[u]=0;zg(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=yn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,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(s),e}};const Gg=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]),jt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qt=new Uint32Array(64);let Wg=class extends Kg{constructor(){super(64,32,8,!1),this.A=jt[0]|0,this.B=jt[1]|0,this.C=jt[2]|0,this.D=jt[3]|0,this.E=jt[4]|0,this.F=jt[5]|0,this.G=jt[6]|0,this.H=jt[7]|0}get(){const{A:e,B:t,C:s,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,s,r,n,o,a,c]}set(e,t,s,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)qt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=qt[u-15],g=qt[u-2],w=ft(p,7)^ft(p,18)^p>>>3,y=ft(g,17)^ft(g,19)^g>>>10;qt[u]=y+qt[u-7]+w+qt[u-16]|0}let{A:s,B:r,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let u=0;u<64;u++){const p=ft(a,6)^ft(a,11)^ft(a,25),g=l+p+Hg(a,c,h)+Gg[u]+qt[u]|0,w=(ft(s,2)^ft(s,13)^ft(s,22))+Vg(s,r,n)|0;l=h,h=c,c=a,a=o+g|0,o=n,n=r,r=s,s=g+w|0}s=s+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(s,r,n,o,a,c,h,l)}roundClean(){qt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const Js=Sl(()=>new Wg);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hr=BigInt(0),Vr=BigInt(1),Zg=BigInt(2);function ni(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ys(i){if(!ni(i))throw new Error("Uint8Array expected")}function Qi(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const Jg=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Xi(i){Ys(i);let e="";for(let t=0;t<i.length;t++)e+=Jg[i[t]];return e}function ki(i){const e=i.toString(16);return e.length&1?"0"+e:e}function Xo(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?Hr:BigInt("0x"+i)}const Et={_0:48,_9:57,A:65,F:70,a:97,f:102};function ec(i){if(i>=Et._0&&i<=Et._9)return i-Et._0;if(i>=Et.A&&i<=Et.F)return i-(Et.A-10);if(i>=Et.a&&i<=Et.f)return i-(Et.a-10)}function es(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const s=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=ec(i.charCodeAt(n)),a=ec(i.charCodeAt(n+1));if(o===void 0||a===void 0){const c=i[n]+i[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}s[r]=o*16+a}return s}function ei(i){return Xo(Xi(i))}function ks(i){return Ys(i),Xo(Xi(Uint8Array.from(i).reverse()))}function ts(i,e){return es(i.toString(16).padStart(e*2,"0"))}function Kr(i,e){return ts(i,e).reverse()}function Yg(i){return es(ki(i))}function Ge(i,e,t){let s;if(typeof e=="string")try{s=es(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(ni(e))s=Uint8Array.from(e);else throw new Error(i+" must be hex string or Uint8Array");const r=s.length;if(typeof t=="number"&&r!==t)throw new Error(i+" of length "+t+" expected, got "+r);return s}function Ls(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Ys(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}function Qg(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}function Xg(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const bn=i=>typeof i=="bigint"&&Hr<=i;function Gr(i,e,t){return bn(i)&&bn(e)&&bn(t)&&e<=i&&i<t}function Tt(i,e,t,s){if(!Gr(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function Bl(i){let e;for(e=0;i>Hr;i>>=Vr,e+=1);return e}function ey(i,e){return i>>BigInt(e)&Vr}function ty(i,e,t){return i|(t?Vr:Hr)<<BigInt(e)}const ea=i=>(Zg<<BigInt(i-1))-Vr,vn=i=>new Uint8Array(i),tc=i=>Uint8Array.from(i);function Ul(i,e,t){if(typeof i!="number"||i<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let s=vn(i),r=vn(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=vn())=>{r=a(tc([0]),l),s=a(),l.length!==0&&(r=a(tc([1]),l),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const u=[];for(;l<e;){s=a();const p=s.slice();u.push(p),l+=s.length}return Ls(...u)};return(l,u)=>{o(),c(l);let p;for(;!(p=u(h()));)c();return o(),p}}const iy={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||ni(i),isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function ls(i,e,t={}){const s=(r,n,o)=>{const a=iy[n];if(typeof a!="function")throw new Error("invalid validator function");const c=i[r];if(!(o&&c===void 0)&&!a(c,i))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))s(r,n,!1);for(const[r,n]of Object.entries(t))s(r,n,!0);return i}const sy=()=>{throw new Error("not implemented")};function uo(i){const e=new WeakMap;return(t,...s)=>{const r=e.get(t);if(r!==void 0)return r;const n=i(t,...s);return e.set(t,n),n}}var ry=Object.freeze({__proto__:null,isBytes:ni,abytes:Ys,abool:Qi,bytesToHex:Xi,numberToHexUnpadded:ki,hexToNumber:Xo,hexToBytes:es,bytesToNumberBE:ei,bytesToNumberLE:ks,numberToBytesBE:ts,numberToBytesLE:Kr,numberToVarBytesBE:Yg,ensureBytes:Ge,concatBytes:Ls,equalBytes:Qg,utf8ToBytes:Xg,inRange:Gr,aInRange:Tt,bitLen:Bl,bitGet:ey,bitSet:ty,bitMask:ea,createHmacDrbg:Ul,validateObject:ls,notImplemented:sy,memoized:uo});const xe=BigInt(0),fe=BigInt(1),Wt=BigInt(2),ny=BigInt(3),po=BigInt(4),ic=BigInt(5),sc=BigInt(8);function De(i,e){const t=i%e;return t>=xe?t:e+t}function jl(i,e,t){if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(t<=xe)throw new Error("invalid modulus");if(t===fe)return xe;let s=fe;for(;e>xe;)e&fe&&(s=s*i%t),i=i*i%t,e>>=fe;return s}function ht(i,e,t){let s=i;for(;e-- >xe;)s*=s,s%=t;return s}function fo(i,e){if(i===xe)throw new Error("invert: expected non-zero number");if(e<=xe)throw new Error("invert: expected positive modulus, got "+e);let t=De(i,e),s=e,r=xe,n=fe;for(;t!==xe;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==fe)throw new Error("invert: does not exist");return De(r,e)}function oy(i){const e=(i-fe)/Wt;let t,s,r;for(t=i-fe,s=0;t%Wt===xe;t/=Wt,s++);for(r=Wt;r<i&&jl(r,e,i)!==i-fe;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+fe)/po;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(t+fe)/Wt;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=s,h=o.pow(o.mul(o.ONE,r),t),l=o.pow(a,n),u=o.pow(a,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let p=1;for(let w=o.sqr(u);p<c&&!o.eql(w,o.ONE);p++)w=o.sqr(w);const g=o.pow(h,fe<<BigInt(c-p-1));h=o.sqr(g),l=o.mul(l,g),u=o.mul(u,h),c=p}return l}}function ay(i){if(i%po===ny){const e=(i+fe)/po;return function(t,s){const r=t.pow(s,e);if(!t.eql(t.sqr(r),s))throw new Error("Cannot find square root");return r}}if(i%sc===ic){const e=(i-ic)/sc;return function(t,s){const r=t.mul(s,Wt),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,Wt),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),s))throw new Error("Cannot find square root");return c}}return oy(i)}const cy=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hy(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=cy.reduce((s,r)=>(s[r]="function",s),e);return ls(i,t)}function ly(i,e,t){if(t<xe)throw new Error("invalid exponent, negatives unsupported");if(t===xe)return i.ONE;if(t===fe)return e;let s=i.ONE,r=e;for(;t>xe;)t&fe&&(s=i.mul(s,r)),r=i.sqr(r),t>>=fe;return s}function uy(i,e){const t=new Array(e.length),s=e.reduce((n,o,a)=>i.is0(o)?n:(t[a]=n,i.mul(n,o)),i.ONE),r=i.inv(s);return e.reduceRight((n,o,a)=>i.is0(o)?n:(t[a]=i.mul(n,t[a]),i.mul(n,o)),r),t}function ql(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function kl(i,e,t=!1,s={}){if(i<=xe)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=ql(i,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:i,isLE:t,BITS:r,BYTES:n,MASK:ea(r),ZERO:xe,ONE:fe,create:c=>De(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return xe<=c&&c<i},is0:c=>c===xe,isOdd:c=>(c&fe)===fe,neg:c=>De(-c,i),eql:(c,h)=>c===h,sqr:c=>De(c*c,i),add:(c,h)=>De(c+h,i),sub:(c,h)=>De(c-h,i),mul:(c,h)=>De(c*h,i),pow:(c,h)=>ly(a,c,h),div:(c,h)=>De(c*fo(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>fo(c,i),sqrt:s.sqrt||(c=>(o||(o=ay(i)),o(a,c))),invertBatch:c=>uy(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?Kr(c,n):ts(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?ks(c):ei(c)}});return Object.freeze(a)}function Ll(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function Dl(i){const e=Ll(i);return e+Math.ceil(e/2)}function dy(i,e,t=!1){const s=i.length,r=Ll(e),n=Dl(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?ks(i):ei(i),a=De(o,e-fe)+fe;return t?Kr(a,r):ts(a,r)}const rc=BigInt(0),hr=BigInt(1);function En(i,e){const t=e.negate();return i?t:e}function Fl(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function $n(i,e){Fl(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function py(i,e){if(!Array.isArray(i))throw new Error("array expected");i.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function fy(i,e){if(!Array.isArray(i))throw new Error("array of scalars expected");i.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}const In=new WeakMap,Ml=new WeakMap;function Sn(i){return Ml.get(i)||1}function gy(i,e){return{constTimeNegate:En,hasPrecomputes(t){return Sn(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>rc;)s&hr&&(r=r.add(n)),n=n.double(),s>>=hr;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=$n(s,e),o=[];let a=t,c=a;for(let h=0;h<r;h++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,s,r){const{windows:n,windowSize:o}=$n(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),l=2**t,u=BigInt(t);for(let p=0;p<n;p++){const g=p*o;let w=Number(r&h);r>>=u,w>o&&(w-=l,r+=hr);const y=g,d=g+Math.abs(w)-1,m=p%2!==0,f=w<0;w===0?c=c.add(En(m,s[y])):a=a.add(En(f,s[d]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=$n(t,e),c=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let u=0;u<o;u++){const p=u*a;if(r===rc)break;let g=Number(r&c);if(r>>=l,g>a&&(g-=h,r+=hr),g===0)continue;let w=s[p+Math.abs(g)-1];g<0&&(w=w.negate()),n=n.add(w)}return n},getPrecomputes(t,s,r){let n=In.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&In.set(s,r(n))),n},wNAFCached(t,s,r){const n=Sn(t);return this.wNAF(n,this.getPrecomputes(n,t,r),s)},wNAFCachedUnsafe(t,s,r,n){const o=Sn(t);return o===1?this.unsafeLadder(t,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,r),s,n)},setWindowSize(t,s){Fl(s,e),Ml.set(t,s),In.delete(t)}}}function yy(i,e,t,s){if(py(t,i),fy(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=Bl(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r),h=Math.floor((e.BITS-1)/o)*o;let l=r;for(let u=h;u>=0;u-=o){c.fill(r);for(let g=0;g<s.length;g++){const w=s[g],y=Number(w>>BigInt(u)&BigInt(a));c[y]=c[y].add(t[g])}let p=r;for(let g=c.length-1,w=r;g>0;g--)w=w.add(c[g]),p=p.add(w);if(l=l.add(p),u!==0)for(let g=0;g<o;g++)l=l.double()}return l}function zl(i){return hy(i.Fp),ls(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ql(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const yi=BigInt(0),xn=BigInt(1);function wy(i){return ls(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function my(i){const e=wy(i),{P:t}=e,s=f=>De(f,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(f=>f),c=e.powPminus2||(f=>jl(f,t-BigInt(2),t));function h(f,E,_){const C=s(f*(E-_));return E=s(E-C),_=s(_+C),[E,_]}const l=(e.a-BigInt(2))/BigInt(4);function u(f,E){Tt("u",f,yi,t),Tt("scalar",E,yi,t);const _=E,C=f;let O=xn,P=yi,R=f,S=xn,U=yi,N;for(let j=BigInt(r-1);j>=yi;j--){const b=_>>j&xn;U^=b,N=h(U,O,R),O=N[0],R=N[1],N=h(U,P,S),P=N[0],S=N[1],U=b;const I=O+P,$=s(I*I),A=O-P,T=s(A*A),x=$-T,q=R+S,k=R-S,L=s(k*I),M=s(q*A),F=L+M,H=L-M;R=s(F*F),S=s(C*s(H*H)),O=s($*T),P=s(x*($+s(l*x)))}N=h(U,O,R),O=N[0],R=N[1],N=h(U,P,S),P=N[0],S=N[1];const B=c(P);return s(O*B)}function p(f){return Kr(s(f),n)}function g(f){const E=Ge("u coordinate",f,n);return o===32&&(E[31]&=127),ks(E)}function w(f){const E=Ge("scalar",f),_=E.length;if(_!==n&&_!==o){let C=""+n+" or "+o;throw new Error("invalid scalar, expected "+C+" bytes, got "+_)}return ks(a(E))}function y(f,E){const _=g(E),C=w(f),O=u(_,C);if(O===yi)throw new Error("invalid private or public key received");return p(O)}const d=p(e.Gu);function m(f){return y(f,d)}return{scalarMult:y,scalarMultBase:m,getSharedSecret:(f,E)=>y(f,E),getPublicKey:f=>m(f),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:d}}const go=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const by=BigInt(1),nc=BigInt(2),vy=BigInt(3),Ey=BigInt(5);BigInt(8);function $y(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=go,o=i*i%n*i%n,a=ht(o,nc,n)*o%n,c=ht(a,by,n)*i%n,h=ht(c,Ey,n)*c%n,l=ht(h,e,n)*h%n,u=ht(l,t,n)*l%n,p=ht(u,s,n)*u%n,g=ht(p,r,n)*p%n,w=ht(g,r,n)*p%n,y=ht(w,e,n)*h%n;return{pow_p_5_8:ht(y,nc,n)*i%n,b2:o}}function Iy(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}const yo=my({P:go,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=go,{pow_p_5_8:t,b2:s}=$y(i);return De(ht(t,vy,e)*s,e)},adjustScalarBytes:Iy,randomBytes:hs});function oc(i){i.lowS!==void 0&&Qi("lowS",i.lowS),i.prehash!==void 0&&Qi("prehash",i.prehash)}function Sy(i){const e=zl(i);ls(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:s,a:r}=e;if(t){if(!s.eql(r,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:xy,hexToBytes:Py}=ry;let _y=class extends Error{constructor(e=""){super(e)}};const Pt={Err:_y,_tlv:{encode:(i,e)=>{const{Err:t}=Pt;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const s=e.length/2,r=ki(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?ki(r.length/2|128):"";return ki(i)+n+r+e},decode(i,e){const{Err:t}=Pt;let s=0;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==i)throw new t("tlv.decode: wrong tlv");const r=e[s++],n=!!(r&128);let o=0;if(!n)o=r;else{const c=r&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const h=e.subarray(s,s+c);if(h.length!==c)throw new t("tlv.decode: length bytes not complete");if(h[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const l of h)o=o<<8|l;if(s+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(s,s+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(i){const{Err:e}=Pt;if(i<At)throw new e("integer: negative integers are not allowed");let t=ki(i);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(i){const{Err:e}=Pt;if(i[0]&128)throw new e("invalid signature integer: negative");if(i[0]===0&&!(i[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return xy(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=Pt,r=typeof i=="string"?Py(i):i;Ys(r);const{v:n,l:o}=s.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l}=s.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(h)}},hexFromSig(i){const{_tlv:e,_int:t}=Pt,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},At=BigInt(0),ve=BigInt(1);BigInt(2);const ac=BigInt(3);BigInt(4);function Oy(i){const e=Sy(i),{Fp:t}=e,s=kl(e.n,e.nBitLength),r=e.toBytes||((y,d,m)=>{const f=d.toAffine();return Ls(Uint8Array.from([4]),t.toBytes(f.x),t.toBytes(f.y))}),n=e.fromBytes||(y=>{const d=y.subarray(1),m=t.fromBytes(d.subarray(0,t.BYTES)),f=t.fromBytes(d.subarray(t.BYTES,2*t.BYTES));return{x:m,y:f}});function o(y){const{a:d,b:m}=e,f=t.sqr(y),E=t.mul(f,y);return t.add(t.add(E,t.mul(y,d)),m)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Gr(y,ve,e.n)}function c(y){const{allowedPrivateKeyLengths:d,nByteLength:m,wrapPrivateKey:f,n:E}=e;if(d&&typeof y!="bigint"){if(ni(y)&&(y=Xi(y)),typeof y!="string"||!d.includes(y.length))throw new Error("invalid private key");y=y.padStart(m*2,"0")}let _;try{_=typeof y=="bigint"?y:ei(Ge("private key",y,m))}catch{throw new Error("invalid private key, expected hex or "+m+" bytes, got "+typeof y)}return f&&(_=De(_,E)),Tt("private key",_,ve,E),_}function h(y){if(!(y instanceof p))throw new Error("ProjectivePoint expected")}const l=uo((y,d)=>{const{px:m,py:f,pz:E}=y;if(t.eql(E,t.ONE))return{x:m,y:f};const _=y.is0();d==null&&(d=_?t.ONE:t.inv(E));const C=t.mul(m,d),O=t.mul(f,d),P=t.mul(E,d);if(_)return{x:t.ZERO,y:t.ZERO};if(!t.eql(P,t.ONE))throw new Error("invZ was invalid");return{x:C,y:O}}),u=uo(y=>{if(y.is0()){if(e.allowInfinityPoint&&!t.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:d,y:m}=y.toAffine();if(!t.isValid(d)||!t.isValid(m))throw new Error("bad point: x or y not FE");const f=t.sqr(m),E=o(d);if(!t.eql(f,E))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class p{constructor(d,m,f){if(this.px=d,this.py=m,this.pz=f,d==null||!t.isValid(d))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(f==null||!t.isValid(f))throw new Error("z required");Object.freeze(this)}static fromAffine(d){const{x:m,y:f}=d||{};if(!d||!t.isValid(m)||!t.isValid(f))throw new Error("invalid affine point");if(d instanceof p)throw new Error("projective point not allowed");const E=_=>t.eql(_,t.ZERO);return E(m)&&E(f)?p.ZERO:new p(m,f,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){const m=t.invertBatch(d.map(f=>f.pz));return d.map((f,E)=>f.toAffine(m[E])).map(p.fromAffine)}static fromHex(d){const m=p.fromAffine(n(Ge("pointHex",d)));return m.assertValidity(),m}static fromPrivateKey(d){return p.BASE.multiply(c(d))}static msm(d,m){return yy(p,s,d,m)}_setWindowSize(d){w.setWindowSize(this,d)}assertValidity(){u(this)}hasEvenY(){const{y:d}=this.toAffine();if(t.isOdd)return!t.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){h(d);const{px:m,py:f,pz:E}=this,{px:_,py:C,pz:O}=d,P=t.eql(t.mul(m,O),t.mul(_,E)),R=t.eql(t.mul(f,O),t.mul(C,E));return P&&R}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:d,b:m}=e,f=t.mul(m,ac),{px:E,py:_,pz:C}=this;let O=t.ZERO,P=t.ZERO,R=t.ZERO,S=t.mul(E,E),U=t.mul(_,_),N=t.mul(C,C),B=t.mul(E,_);return B=t.add(B,B),R=t.mul(E,C),R=t.add(R,R),O=t.mul(d,R),P=t.mul(f,N),P=t.add(O,P),O=t.sub(U,P),P=t.add(U,P),P=t.mul(O,P),O=t.mul(B,O),R=t.mul(f,R),N=t.mul(d,N),B=t.sub(S,N),B=t.mul(d,B),B=t.add(B,R),R=t.add(S,S),S=t.add(R,S),S=t.add(S,N),S=t.mul(S,B),P=t.add(P,S),N=t.mul(_,C),N=t.add(N,N),S=t.mul(N,B),O=t.sub(O,S),R=t.mul(N,U),R=t.add(R,R),R=t.add(R,R),new p(O,P,R)}add(d){h(d);const{px:m,py:f,pz:E}=this,{px:_,py:C,pz:O}=d;let P=t.ZERO,R=t.ZERO,S=t.ZERO;const U=e.a,N=t.mul(e.b,ac);let B=t.mul(m,_),j=t.mul(f,C),b=t.mul(E,O),I=t.add(m,f),$=t.add(_,C);I=t.mul(I,$),$=t.add(B,j),I=t.sub(I,$),$=t.add(m,E);let A=t.add(_,O);return $=t.mul($,A),A=t.add(B,b),$=t.sub($,A),A=t.add(f,E),P=t.add(C,O),A=t.mul(A,P),P=t.add(j,b),A=t.sub(A,P),S=t.mul(U,$),P=t.mul(N,b),S=t.add(P,S),P=t.sub(j,S),S=t.add(j,S),R=t.mul(P,S),j=t.add(B,B),j=t.add(j,B),b=t.mul(U,b),$=t.mul(N,$),j=t.add(j,b),b=t.sub(B,b),b=t.mul(U,b),$=t.add($,b),B=t.mul(j,$),R=t.add(R,B),B=t.mul(A,$),P=t.mul(I,P),P=t.sub(P,B),B=t.mul(I,j),S=t.mul(A,S),S=t.add(S,B),new p(P,R,S)}subtract(d){return this.add(d.negate())}is0(){return this.equals(p.ZERO)}wNAF(d){return w.wNAFCached(this,d,p.normalizeZ)}multiplyUnsafe(d){const{endo:m,n:f}=e;Tt("scalar",d,At,f);const E=p.ZERO;if(d===At)return E;if(this.is0()||d===ve)return this;if(!m||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,d,p.normalizeZ);let{k1neg:_,k1:C,k2neg:O,k2:P}=m.splitScalar(d),R=E,S=E,U=this;for(;C>At||P>At;)C&ve&&(R=R.add(U)),P&ve&&(S=S.add(U)),U=U.double(),C>>=ve,P>>=ve;return _&&(R=R.negate()),O&&(S=S.negate()),S=new p(t.mul(S.px,m.beta),S.py,S.pz),R.add(S)}multiply(d){const{endo:m,n:f}=e;Tt("scalar",d,ve,f);let E,_;if(m){const{k1neg:C,k1:O,k2neg:P,k2:R}=m.splitScalar(d);let{p:S,f:U}=this.wNAF(O),{p:N,f:B}=this.wNAF(R);S=w.constTimeNegate(C,S),N=w.constTimeNegate(P,N),N=new p(t.mul(N.px,m.beta),N.py,N.pz),E=S.add(N),_=U.add(B)}else{const{p:C,f:O}=this.wNAF(d);E=C,_=O}return p.normalizeZ([E,_])[0]}multiplyAndAddUnsafe(d,m,f){const E=p.BASE,_=(O,P)=>P===At||P===ve||!O.equals(E)?O.multiplyUnsafe(P):O.multiply(P),C=_(this,m).add(_(d,f));return C.is0()?void 0:C}toAffine(d){return l(this,d)}isTorsionFree(){const{h:d,isTorsionFree:m}=e;if(d===ve)return!0;if(m)return m(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:d,clearCofactor:m}=e;return d===ve?this:m?m(p,this):this.multiplyUnsafe(e.h)}toRawBytes(d=!0){return Qi("isCompressed",d),this.assertValidity(),r(p,this,d)}toHex(d=!0){return Qi("isCompressed",d),Xi(this.toRawBytes(d))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const g=e.nBitLength,w=gy(p,e.endo?Math.ceil(g/2):g);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Ay(i){const e=zl(i);return ls(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Ry(i){const e=Ay(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(b){return De(b,s)}function a(b){return fo(b,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=Oy({...e,toBytes(b,I,$){const A=I.toAffine(),T=t.toBytes(A.x),x=Ls;return Qi("isCompressed",$),$?x(Uint8Array.from([I.hasEvenY()?2:3]),T):x(Uint8Array.from([4]),T,t.toBytes(A.y))},fromBytes(b){const I=b.length,$=b[0],A=b.subarray(1);if(I===r&&($===2||$===3)){const T=ei(A);if(!Gr(T,ve,t.ORDER))throw new Error("Point is not on curve");const x=l(T);let q;try{q=t.sqrt(x)}catch(L){const M=L instanceof Error?": "+L.message:"";throw new Error("Point is not on curve"+M)}const k=(q&ve)===ve;return($&1)===1!==k&&(q=t.neg(q)),{x:T,y:q}}else if(I===n&&$===4){const T=t.fromBytes(A.subarray(0,t.BYTES)),x=t.fromBytes(A.subarray(t.BYTES,2*t.BYTES));return{x:T,y:x}}else{const T=r,x=n;throw new Error("invalid Point, expected length of "+T+", or uncompressed "+x+", got "+I)}}}),p=b=>Xi(ts(b,e.nByteLength));function g(b){const I=s>>ve;return b>I}function w(b){return g(b)?o(-b):b}const y=(b,I,$)=>ei(b.slice(I,$));class d{constructor(I,$,A){this.r=I,this.s=$,this.recovery=A,this.assertValidity()}static fromCompact(I){const $=e.nByteLength;return I=Ge("compactSignature",I,$*2),new d(y(I,0,$),y(I,$,2*$))}static fromDER(I){const{r:$,s:A}=Pt.toSig(Ge("DER",I));return new d($,A)}assertValidity(){Tt("r",this.r,ve,s),Tt("s",this.s,ve,s)}addRecoveryBit(I){return new d(this.r,this.s,I)}recoverPublicKey(I){const{r:$,s:A,recovery:T}=this,x=O(Ge("msgHash",I));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");const q=T===2||T===3?$+e.n:$;if(q>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const k=(T&1)===0?"02":"03",L=c.fromHex(k+p(q)),M=a(q),F=o(-x*M),H=o(A*M),K=c.BASE.multiplyAndAddUnsafe(L,F,H);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new d(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return es(this.toDERHex())}toDERHex(){return Pt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return es(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const m={isValidPrivateKey(b){try{return h(b),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const b=Dl(e.n);return dy(e.randomBytes(b),e.n)},precompute(b=8,I=c.BASE){return I._setWindowSize(b),I.multiply(BigInt(3)),I}};function f(b,I=!0){return c.fromPrivateKey(b).toRawBytes(I)}function E(b){const I=ni(b),$=typeof b=="string",A=(I||$)&&b.length;return I?A===r||A===n:$?A===2*r||A===2*n:b instanceof c}function _(b,I,$=!0){if(E(b))throw new Error("first arg must be private key");if(!E(I))throw new Error("second arg must be public key");return c.fromHex(I).multiply(h(b)).toRawBytes($)}const C=e.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const I=ei(b),$=b.length*8-e.nBitLength;return $>0?I>>BigInt($):I},O=e.bits2int_modN||function(b){return o(C(b))},P=ea(e.nBitLength);function R(b){return Tt("num < 2^"+e.nBitLength,b,At,P),ts(b,e.nByteLength)}function S(b,I,$=U){if(["recovered","canonical"].some(G=>G in $))throw new Error("sign() legacy options not supported");const{hash:A,randomBytes:T}=e;let{lowS:x,prehash:q,extraEntropy:k}=$;x==null&&(x=!0),b=Ge("msgHash",b),oc($),q&&(b=Ge("prehashed msgHash",A(b)));const L=O(b),M=h(I),F=[R(M),R(L)];if(k!=null&&k!==!1){const G=k===!0?T(t.BYTES):k;F.push(Ge("extraEntropy",G))}const H=Ls(...F),K=L;function Z(G){const W=C(G);if(!u(W))return;const Be=a(W),ue=c.BASE.multiply(W).toAffine(),ae=o(ue.x);if(ae===At)return;const he=o(Be*o(K+ae*M));if(he===At)return;let Xe=(ue.x===ae?0:2)|Number(ue.y&ve),dt=he;return x&&g(he)&&(dt=w(he),Xe^=1),new d(ae,dt,Xe)}return{seed:H,k2sig:Z}}const U={lowS:e.lowS,prehash:!1},N={lowS:e.lowS,prehash:!1};function B(b,I,$=U){const{seed:A,k2sig:T}=S(b,I,$),x=e;return Ul(x.hash.outputLen,x.nByteLength,x.hmac)(A,T)}c.BASE._setWindowSize(8);function j(b,I,$,A=N){const T=b;I=Ge("msgHash",I),$=Ge("publicKey",$);const{lowS:x,prehash:q,format:k}=A;if(oc(A),"strict"in A)throw new Error("options.strict was renamed to lowS");if(k!==void 0&&k!=="compact"&&k!=="der")throw new Error("format must be compact or der");const L=typeof T=="string"||ni(T),M=!L&&!k&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!L&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,H;try{if(M&&(F=new d(T.r,T.s)),L){try{k!=="compact"&&(F=d.fromDER(T))}catch(he){if(!(he instanceof Pt.Err))throw he}!F&&k!=="der"&&(F=d.fromCompact(T))}H=c.fromHex($)}catch{return!1}if(!F||x&&F.hasHighS())return!1;q&&(I=e.hash(I));const{r:K,s:Z}=F,G=O(I),W=a(Z),Be=o(G*W),ue=o(K*W),ae=c.BASE.multiplyAndAddUnsafe(H,Be,ue)?.toAffine();return ae?o(ae.x)===K:!1}return{CURVE:e,getPublicKey:f,getSharedSecret:_,sign:B,verify:j,ProjectivePoint:c,Signature:d,utils:m}}function Ny(i){return{hash:i,hmac:(e,...t)=>zr(i,e,og(...t)),randomBytes:hs}}function Ty(i,e){const t=s=>Ry({...i,...Ny(s)});return{...t(e),create:t}}const Hl=kl(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Cy=Hl.create(BigInt("-3")),By=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Uy=Ty({a:Cy,b:By,Fp:Hl,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Js),Vl="base10",je="base16",ti="base64pad",ta="base64url",Qs="utf8",Kl=0,us=1,Wr=2,jy=0,cc=1,Ts=12,ia=32;function qy(){const i=yo.utils.randomPrivateKey(),e=yo.getPublicKey(i);return{privateKey:v.toString(i,je),publicKey:v.toString(e,je)}}function wo(){const i=hs(ia);return v.toString(i,je)}function ky(i,e){const t=yo.getSharedSecret(v.fromString(i,je),v.fromString(e,je)),s=Mg(Js,t,void 0,void 0,ia);return v.toString(s,je)}function Ly(i){const e=Js(v.fromString(i,je));return v.toString(e,je)}function $r(i){const e=Js(v.fromString(i,Qs));return v.toString(e,je)}function Gl(i){return v.fromString(`${i}`,Vl)}function oi(i){return Number(v.toString(i,Vl))}function Wl(i){return i.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Zl(i){const e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Dy(i){const e=Gl(typeof i.type<"u"?i.type:Kl);if(oi(e)===us&&typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof i.senderPublicKey<"u"?v.fromString(i.senderPublicKey,je):void 0,s=typeof i.iv<"u"?v.fromString(i.iv,je):hs(Ts),r=v.fromString(i.symKey,je),n=Tl(r,s).encrypt(v.fromString(i.message,Qs)),o=Jl({type:e,sealed:n,iv:s,senderPublicKey:t});return i.encoding===ta?Wl(o):o}function Fy(i){const e=v.fromString(i.symKey,je),{sealed:t,iv:s}=Ds({encoded:i.encoded,encoding:i.encoding}),r=Tl(e,s).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return v.toString(r,Qs)}function My(i,e){const t=Gl(Wr),s=hs(Ts),r=v.fromString(i,Qs),n=Jl({type:t,sealed:r,iv:s});return e===ta?Wl(n):n}function zy(i,e){const{sealed:t}=Ds({encoded:i,encoding:e});return v.toString(t,Qs)}function Jl(i){if(oi(i.type)===Wr)return v.toString(v.concat([i.type,i.sealed]),ti);if(oi(i.type)===us){if(typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return v.toString(v.concat([i.type,i.senderPublicKey,i.iv,i.sealed]),ti)}return v.toString(v.concat([i.type,i.iv,i.sealed]),ti)}function Ds(i){const e=(i.encoding||ti)===ta?Zl(i.encoded):i.encoded,t=v.fromString(e,ti),s=t.slice(jy,cc),r=cc;if(oi(s)===us){const c=r+ia,h=c+Ts,l=t.slice(r,c),u=t.slice(c,h),p=t.slice(h);return{type:s,sealed:p,iv:u,senderPublicKey:l}}if(oi(s)===Wr){const c=t.slice(r),h=hs(Ts);return{type:s,sealed:c,iv:h}}const n=r+Ts,o=t.slice(r,n),a=t.slice(n);return{type:s,sealed:a,iv:o}}function Hy(i,e){const t=Ds({encoded:i,encoding:e?.encoding});return Yl({type:oi(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?v.toString(t.senderPublicKey,je):void 0,receiverPublicKey:e?.receiverPublicKey})}function Yl(i){const e=i?.type||Kl;if(e===us){if(typeof i?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof i?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:i?.senderPublicKey,receiverPublicKey:i?.receiverPublicKey}}function hc(i){return i.type===us&&typeof i.senderPublicKey=="string"&&typeof i.receiverPublicKey=="string"}function lc(i){return i.type===Wr}function Vy(i){const e=z.Buffer.from(i.x,"base64"),t=z.Buffer.from(i.y,"base64");return v.concat([new Uint8Array([4]),e,t])}function Ky(i,e){const[t,s,r]=i.split("."),n=z.Buffer.from(Zl(r),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${t}.${s}`,h=Js(c),l=Vy(e);if(!Uy.verify(v.concat([o,a]),h,l))throw new Error("Invalid signature");return v.sn(i).payload}const Gy="irn";function Ar(i){return i?.relay||{protocol:Gy}}function Os(i){const e=v.C[i];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${i}`);return e}function Wy(i,e="-"){const t={},s="relay"+e;return Object.keys(i).forEach(r=>{if(r.startsWith(s)){const n=r.replace(s,""),o=i[r];t[n]=o}}),t}function uc(i){if(!i.includes("wc:")){const h=$l(i);h!=null&&h.includes("wc:")&&(i=h)}i=i.includes("wc://")?i.replace("wc://",""):i,i=i.includes("wc:")?i.replace("wc:",""):i;const e=i.indexOf(":"),t=i.indexOf("?")!==-1?i.indexOf("?"):void 0,s=i.substring(0,e),r=i.substring(e+1,t).split("@"),n=typeof t<"u"?i.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((h,l)=>{a[l]=h});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:s,topic:Zy(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:Wy(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Zy(i){return i.startsWith("//")?i.substring(2):i}function Jy(i,e="-"){const t="relay",s={};return Object.keys(i).forEach(r=>{const n=r,o=t+e+n;i[n]&&(s[o]=i[n])}),s}function dc(i){const e=new URLSearchParams,t=Jy(i.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",i.symKey),i.expiryTimestamp&&e.set("expiryTimestamp",i.expiryTimestamp.toString()),i.methods&&e.set("methods",i.methods.join(","));const s=e.toString();return`${i.protocol}:${i.topic}@${i.version}?${s}`}const Yy={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}},Qy={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 se(i,e){const{message:t,code:s}=Qy[i];return{message:e?`${t} ${e}`:t,code:s}}function As(i,e){const{message:t,code:s}=Yy[i];return{message:e?`${t} ${e}`:t,code:s}}function mo(i){return typeof i>"u"}function Ql(i,e){return typeof i=="string"&&!!i.trim().length}function Xy(i){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(Ql(i,!1)){if(e(i))return!0;const t=$l(i);return e(t)}}catch{}return!1}function ew(i){var e;return(e=i?.proposer)==null?void 0:e.publicKey}function tw(i){return i?.topic}function Pn(i){return typeof i<"u"&&typeof i!==null}function pc(){const i=Mr();return new Promise(e=>{switch(i){case ut.browser:e(iw());break;case ut.reactNative:e(sw());break;case ut.node:e(rw());break;default:e(!0)}})}function iw(){return Ws()&&navigator?.onLine}async function sw(){return li()&&typeof z.global<"u"&&z.global!=null&&z.global.NetInfo?(await(z.global==null?void 0:z.global.NetInfo.fetch()))?.isConnected:!0}function rw(){return!0}function nw(i){switch(Mr()){case ut.browser:ow(i);break;case ut.reactNative:aw(i);break}}function ow(i){!li()&&Ws()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function aw(i){li()&&typeof z.global<"u"&&z.global!=null&&z.global.NetInfo&&z.global?.NetInfo.addEventListener(e=>i(e?.isConnected))}function cw(){var i;return Ws()&&v.cjsExports$2.getDocument()?((i=v.cjsExports$2.getDocument())==null?void 0:i.visibilityState)==="visible":!0}const Xl="wc",eu=2,bo="core",bt=`${Xl}@2:${bo}:`,hw={logger:"error"},lw={database:":memory:"},uw="crypto",fc="client_ed25519_seed",dw=v.cjsExports$1.ONE_DAY,pw="keychain",fw="0.3",gw="messages",yw="0.3",gc=v.cjsExports$1.SIX_HOURS,ww="publisher",tu="irn",mw="error",iu="wss://relay.walletconnect.org",bw="relayer",Ie={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"},vw="_subscription",et={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Ew=.1,vo="2.21.1",le={link_mode:"link_mode",relay:"relay"},Ir={inbound:"inbound",outbound:"outbound"},$w="0.3",Iw="WALLETCONNECT_CLIENT_ID",yc="WALLETCONNECT_LINK_MODE_APPS",Ve={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Sw="subscription",xw="0.3",Pw="pairing",_w="0.3",ms={wc_pairingDelete:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:v.cjsExports$1.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:v.cjsExports$1.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:0},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:0}}},Zt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},rt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Ow="history",Aw="0.3",Rw="expirer",it={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Nw="0.3",Tw="verify-api",Cw="https://verify.walletconnect.com",su="https://verify.walletconnect.org",Cs=su,Bw=`${Cs}/v3`,Uw=[Cw,su],jw="echo",qw="https://echo.walletconnect.com",mt={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},St={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"},nt={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"},Ht={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"},Vt={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"},bs={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"},kw=.1,Lw="event-client",Dw=86400,Fw="https://pulse.walletconnect.org/batch";function Mw(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var r=0;r<i.length;r++){var n=i.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=i.length,c=i.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.byteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var y=0,d=0,m=0,f=w.length;m!==f&&w[m]===0;)m++,y++;for(var E=(f-m)*l+1>>>0,_=new Uint8Array(E);m!==f;){for(var C=w[m],O=0,P=E-1;(C!==0||O<d)&&P!==-1;P--,O++)C+=256*_[P]>>>0,_[P]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");d=O,m++}for(var R=E-d;R!==E&&_[R]===0;)R++;for(var S=c.repeat(y);R<E;++R)S+=i.charAt(_[R]);return S}function p(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var y=0;if(w[y]!==" "){for(var d=0,m=0;w[y]===c;)d++,y++;for(var f=(w.length-y)*h+1>>>0,E=new Uint8Array(f);w[y];){var _=t[w.charCodeAt(y)];if(_===255)return;for(var C=0,O=f-1;(_!==0||C<m)&&O!==-1;O--,C++)_+=a*E[O]>>>0,E[O]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");m=C,y++}if(w[y]!==" "){for(var P=f-m;P!==f&&E[P]===0;)P++;for(var R=new Uint8Array(d+(f-P)),S=d;P!==f;)R[S++]=E[P++];return R}}}function g(w){var y=p(w);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:g}}var zw=Mw,Hw=zw;const ru=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},Vw=i=>new TextEncoder().encode(i),Kw=i=>new TextDecoder().decode(i);let Gw=class{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ww=class{constructor(e,t,s){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=s}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 nu(this,e)}},Zw=class{constructor(e){this.decoders=e}or(e){return nu(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const nu=(i,e)=>new Zw({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});let Jw=class{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Gw(e,t,s),this.decoder=new Ww(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Zr=({name:i,prefix:e,encode:t,decode:s})=>new Jw(i,e,t,s),Xs=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=Hw(t,e);return Zr({prefix:i,name:e,encode:s,decode:n=>ru(r(n))})},Yw=(i,e,t,s)=>{const r={};for(let l=0;l<e.length;++l)r[e[l]]=l;let n=i.length;for(;i[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const u=r[i[l]];if(u===void 0)throw new SyntaxError(`Non-${s} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Qw=(i,e,t)=>{const s=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),s)for(;n.length*t&7;)n+="=";return n},Te=({name:i,prefix:e,bitsPerChar:t,alphabet:s})=>Zr({prefix:e,name:i,encode(r){return Qw(r,s,t)},decode(r){return Yw(r,s,t,i)}}),Xw=Zr({prefix:"\0",name:"identity",encode:i=>Kw(i),decode:i=>Vw(i)});var em=Object.freeze({__proto__:null,identity:Xw});const tm=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var im=Object.freeze({__proto__:null,base2:tm});const sm=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var rm=Object.freeze({__proto__:null,base8:sm});const nm=Xs({prefix:"9",name:"base10",alphabet:"0123456789"});var om=Object.freeze({__proto__:null,base10:nm});const am=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),cm=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hm=Object.freeze({__proto__:null,base16:am,base16upper:cm});const lm=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),um=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),dm=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pm=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fm=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gm=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ym=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wm=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),mm=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var bm=Object.freeze({__proto__:null,base32:lm,base32upper:um,base32pad:dm,base32padupper:pm,base32hex:fm,base32hexupper:gm,base32hexpad:ym,base32hexpadupper:wm,base32z:mm});const vm=Xs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Em=Xs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $m=Object.freeze({__proto__:null,base36:vm,base36upper:Em});const Im=Xs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sm=Xs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xm=Object.freeze({__proto__:null,base58btc:Im,base58flickr:Sm});const Pm=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_m=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Om=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Am=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Rm=Object.freeze({__proto__:null,base64:Pm,base64pad:_m,base64url:Om,base64urlpad:Am});const ou=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Nm=ou.reduce((i,e,t)=>(i[t]=e,i),[]),Tm=ou.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function Cm(i){return i.reduce((e,t)=>(e+=Nm[t],e),"")}function Bm(i){const e=[];for(const t of i){const s=Tm[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const Um=Zr({prefix:"🚀",name:"base256emoji",encode:Cm,decode:Bm});var jm=Object.freeze({__proto__:null,base256emoji:Um}),qm=au,wc=128,km=-128,Lm=Math.pow(2,31);function au(i,e,t){e=e||[],t=t||0;for(var s=t;i>=Lm;)e[t++]=i&255|wc,i/=128;for(;i&km;)e[t++]=i&255|wc,i>>>=7;return e[t]=i|0,au.bytes=t-s+1,e}var Dm=Eo,Fm=128,mc=127;function Eo(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw Eo.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&mc)<<r:(o&mc)*Math.pow(2,r),r+=7}while(o>=Fm);return Eo.bytes=n-s,t}var Mm=Math.pow(2,7),zm=Math.pow(2,14),Hm=Math.pow(2,21),Vm=Math.pow(2,28),Km=Math.pow(2,35),Gm=Math.pow(2,42),Wm=Math.pow(2,49),Zm=Math.pow(2,56),Jm=Math.pow(2,63),Ym=function(i){return i<Mm?1:i<zm?2:i<Hm?3:i<Vm?4:i<Km?5:i<Gm?6:i<Wm?7:i<Zm?8:i<Jm?9:10},Qm={encode:qm,decode:Dm,encodingLength:Ym},cu=Qm;const bc=(i,e,t=0)=>(cu.encode(i,e,t),e),vc=i=>cu.encodingLength(i),$o=(i,e)=>{const t=e.byteLength,s=vc(i),r=s+vc(t),n=new Uint8Array(r+t);return bc(i,n,0),bc(t,n,s),n.set(e,r),new Xm(i,t,e,n)};let Xm=class{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}};const hu=({name:i,code:e,encode:t})=>new eb(i,e,t);class eb{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?$o(this.code,t):t.then(s=>$o(this.code,s))}else throw Error("Unknown type, must be binary type")}}const lu=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),tb=hu({name:"sha2-256",code:18,encode:lu("SHA-256")}),ib=hu({name:"sha2-512",code:19,encode:lu("SHA-512")});var sb=Object.freeze({__proto__:null,sha256:tb,sha512:ib});const uu=0,rb="identity",du=ru,nb=i=>$o(uu,du(i)),ob={code:uu,name:rb,encode:du,digest:nb};var ab=Object.freeze({__proto__:null,identity:ob});new TextEncoder,new TextDecoder;const Ec={...em,...im,...rm,...om,...hm,...bm,...$m,...xm,...Rm,...jm};({...sb,...ab});function cb(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function pu(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const $c=pu("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),_n=pu("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=cb(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),hb={utf8:$c,"utf-8":$c,hex:Ec.base16,latin1:_n,ascii:_n,binary:_n,...Ec};function lb(i,e="utf8"){const t=hb[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(i,"utf8"):t.decoder.decode(`${t.prefix}${i}`)}var ub=Object.defineProperty,db=(i,e,t)=>e in i?ub(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,gt=(i,e,t)=>db(i,typeof e!="symbol"?e+"":e,t);let pb=class{constructor(e,t){this.core=e,this.logger=t,gt(this,"keychain",new Map),gt(this,"name",pw),gt(this,"version",fw),gt(this,"initialized",!1),gt(this,"storagePrefix",bt),gt(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),gt(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),gt(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),gt(this,"get",s=>{this.isInitialized();const r=this.keychain.get(s);if(typeof r>"u"){const{message:n}=se("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(n)}return r}),gt(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=v.E(t,this.name)}get context(){return v.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,oo(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ao(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var fb=Object.defineProperty,gb=(i,e,t)=>e in i?fb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ae=(i,e,t)=>gb(i,typeof e!="symbol"?e+"":e,t);let yb=class{constructor(e,t,s){this.core=e,this.logger=t,Ae(this,"name",uw),Ae(this,"keychain"),Ae(this,"randomSessionIdentifier",wo()),Ae(this,"initialized",!1),Ae(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ae(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ae(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=v.Po(r);return v.Qe(n.publicKey)}),Ae(this,"generateKeyPair",()=>{this.isInitialized();const r=qy();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ae(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=v.Po(n),a=this.randomSessionIdentifier,c=dw;return await v.Qo(a,r,c,o)}),Ae(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=ky(a,n);return this.setSymKey(c,o)}),Ae(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||Ly(r);return await this.keychain.set(o,r),o}),Ae(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ae(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ae(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Yl(o),c=v.safeJsonStringify(n);if(lc(a))return My(c,o?.encoding);if(hc(a)){const p=a.senderPublicKey,g=a.receiverPublicKey;r=await this.generateSharedKey(p,g)}const h=this.getSymKey(r),{type:l,senderPublicKey:u}=a;return Dy({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o?.encoding})}),Ae(this,"decode",async(r,n,o)=>{this.isInitialized();const a=Hy(n,o);if(lc(a)){const c=zy(n,o?.encoding);return v.safeJsonParse(c)}if(hc(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=Fy({symKey:c,encoded:n,encoding:o?.encoding});return v.safeJsonParse(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ae(this,"getPayloadType",(r,n=ti)=>{const o=Ds({encoded:r,encoding:n});return oi(o.type)}),Ae(this,"getPayloadSenderPublicKey",(r,n=ti)=>{const o=Ds({encoded:r,encoding:n});return o.senderPublicKey?v.toString(o.senderPublicKey,je):void 0}),this.core=e,this.logger=v.E(t,this.name),this.keychain=s||new pb(this.core,this.logger)}get context(){return v.y(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(fc)}catch{e=wo(),await this.keychain.set(fc,e)}return lb(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var wb=Object.defineProperty,mb=Object.defineProperties,bb=Object.getOwnPropertyDescriptors,Ic=Object.getOwnPropertySymbols,vb=Object.prototype.hasOwnProperty,Eb=Object.prototype.propertyIsEnumerable,Io=(i,e,t)=>e in i?wb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,$b=(i,e)=>{for(var t in e||(e={}))vb.call(e,t)&&Io(i,t,e[t]);if(Ic)for(var t of Ic(e))Eb.call(e,t)&&Io(i,t,e[t]);return i},Ib=(i,e)=>mb(i,bb(e)),ze=(i,e,t)=>Io(i,typeof e!="symbol"?e+"":e,t);let Sb=class extends Ef{constructor(e,t){super(e,t),this.logger=e,this.core=t,ze(this,"messages",new Map),ze(this,"messagesWithoutClientAck",new Map),ze(this,"name",gw),ze(this,"version",yw),ze(this,"initialized",!1),ze(this,"storagePrefix",bt),ze(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const s=await this.getRelayerMessages();typeof s<"u"&&(this.messages=s);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(s){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(s)}finally{this.initialized=!0}}}),ze(this,"set",async(s,r,n)=>{this.isInitialized();const o=$r(r);let a=this.messages.get(s);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(s,a),n===Ir.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,Ib($b({},c),{[o]:r}))}return await this.persist(),o}),ze(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),ze(this,"getWithoutAck",s=>{this.isInitialized();const r={};for(const n of s){const o=this.messagesWithoutClientAck.get(n)||{};r[n]=Object.values(o)}return r}),ze(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=$r(r);return typeof n[o]<"u"}),ze(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=$r(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),ze(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=v.E(e,this.name),this.core=t}get context(){return v.y(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,oo(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,oo(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ao(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?ao(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var xb=Object.defineProperty,Pb=Object.defineProperties,_b=Object.getOwnPropertyDescriptors,Sc=Object.getOwnPropertySymbols,Ob=Object.prototype.hasOwnProperty,Ab=Object.prototype.propertyIsEnumerable,So=(i,e,t)=>e in i?xb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,lr=(i,e)=>{for(var t in e||(e={}))Ob.call(e,t)&&So(i,t,e[t]);if(Sc)for(var t of Sc(e))Ab.call(e,t)&&So(i,t,e[t]);return i},On=(i,e)=>Pb(i,_b(e)),ot=(i,e,t)=>So(i,typeof e!="symbol"?e+"":e,t);class Rb extends $f{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ot(this,"events",new v.eventsExports.EventEmitter),ot(this,"name",ww),ot(this,"queue",new Map),ot(this,"publishTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_MINUTE)),ot(this,"initialPublishTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_SECOND*15)),ot(this,"needsTransportRestart",!1),ot(this,"publish",async(s,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:s,message:r,opts:n}});const a=n?.ttl||gc,c=Ar(n),h=n?.prompt||!1,l=n?.tag||0,u=n?.id||v.getBigIntRpcId().toString(),p={topic:s,message:r,opts:{ttl:a,relay:c,prompt:h,tag:l,id:u,attestation:n?.attestation,tvf:n?.tvf}},g=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const w=new Promise(async y=>{const d=({id:f})=>{p.opts.id===f&&(this.removeRequestFromQueue(f),this.relayer.events.removeListener(Ie.publish,d),y(p))};this.relayer.events.on(Ie.publish,d);const m=Dt(new Promise((f,E)=>{this.rpcPublish({topic:s,message:r,ttl:a,prompt:h,tag:l,id:u,attestation:n?.attestation,tvf:n?.tvf}).then(f).catch(_=>{this.logger.warn(_,_?.message),E(_)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await m,this.events.removeListener(Ie.publish,d)}catch(f){this.queue.set(u,On(lr({},p),{attempt:1})),this.logger.warn(f,f?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:s,message:r,opts:n}}),await Dt(w,this.publishTimeout,g)}catch(w){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(w),(o=n?.internal)!=null&&o.throwOnFailedPublish)throw w}finally{this.queue.delete(u)}}),ot(this,"on",(s,r)=>{this.events.on(s,r)}),ot(this,"once",(s,r)=>{this.events.once(s,r)}),ot(this,"off",(s,r)=>{this.events.off(s,r)}),ot(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=v.E(t,this.name),this.registerEventListeners()}get context(){return v.y(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=gc,prompt:h,tag:l,id:u,attestation:p,tvf:g}=e,w={method:Os(Ar().protocol).publish,params:lr({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:p},g),id:u};mo((t=w.params)==null?void 0:t.prompt)&&((s=w.params)==null||delete s.prompt),mo((r=w.params)==null?void 0:r.tag)&&((n=w.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w});const y=await this.relayer.request(w);return this.relayer.events.emit(Ie.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,On(lr({},e),{attempt:s}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${s}`),await this.rpcPublish(On(lr({},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(v.r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ie.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ie.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var Nb=Object.defineProperty,Tb=(i,e,t)=>e in i?Nb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,wi=(i,e,t)=>Tb(i,typeof e!="symbol"?e+"":e,t);class Cb{constructor(){wi(this,"map",new Map),wi(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),wi(this,"get",e=>this.map.get(e)||[]),wi(this,"exists",(e,t)=>this.get(e).includes(t)),wi(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const r=s.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),wi(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Bb=Object.defineProperty,Ub=Object.defineProperties,jb=Object.getOwnPropertyDescriptors,xc=Object.getOwnPropertySymbols,qb=Object.prototype.hasOwnProperty,kb=Object.prototype.propertyIsEnumerable,xo=(i,e,t)=>e in i?Bb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vs=(i,e)=>{for(var t in e||(e={}))qb.call(e,t)&&xo(i,t,e[t]);if(xc)for(var t of xc(e))kb.call(e,t)&&xo(i,t,e[t]);return i},An=(i,e)=>Ub(i,jb(e)),re=(i,e,t)=>xo(i,typeof e!="symbol"?e+"":e,t);let Lb=class extends xf{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,re(this,"subscriptions",new Map),re(this,"topicMap",new Cb),re(this,"events",new v.eventsExports.EventEmitter),re(this,"name",Sw),re(this,"version",xw),re(this,"pending",new Map),re(this,"cached",[]),re(this,"initialized",!1),re(this,"storagePrefix",bt),re(this,"subscribeTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_MINUTE)),re(this,"initialSubscribeTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_SECOND*15)),re(this,"clientId"),re(this,"batchSubscribeTopicsLimit",500),re(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),re(this,"subscribe",async(s,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:s,opts:r}});try{const n=Ar(r),o={topic:s,relay:n,transportType:r?.transportType};this.pending.set(s,o);const a=await this.rpcSubscribe(s,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:s,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),re(this,"unsubscribe",async(s,r)=>{this.isInitialized(),typeof r?.id<"u"?await this.unsubscribeById(s,r.id,r):await this.unsubscribeByTopic(s,r)}),re(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),re(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),re(this,"on",(s,r)=>{this.events.on(s,r)}),re(this,"once",(s,r)=>{this.events.once(s,r)}),re(this,"off",(s,r)=>{this.events.off(s,r)}),re(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),re(this,"start",async()=>{await this.onConnect()}),re(this,"stop",async()=>{await this.onDisconnect()}),re(this,"restart",async()=>{await this.restore(),await this.onRestart()}),re(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const s=[];this.pending.forEach(r=>{s.push(r)}),await this.batchSubscribe(s)}),re(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(v.r.pulse,async()=>{await this.checkPending()}),this.events.on(Ve.created,async s=>{const r=Ve.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(Ve.deleted,async s=>{const r=Ve.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=v.E(t,this.name),this.clientId=""}get context(){return v.y(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 s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const r=Ar(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=As("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:s}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,s){var r;(!s||s?.transportType===le.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Os(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=s?.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(s?.transportType===le.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_SECOND)),a;const c=new Promise(async l=>{const u=p=>{p.topic===e&&(this.events.removeListener(Ve.created,u),l(p.id))};this.events.on(Ve.created,u);try{const p=await Dt(new Promise((g,w)=>{this.relayer.request(n).catch(y=>{this.logger.warn(y,y?.message),w(y)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Ve.created,u),l(p)}catch{}}),h=await Dt(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ie.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Os(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await Dt(new Promise(r=>{this.relayer.request(s).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Ie.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Os(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let r;try{r=await await Dt(new Promise((n,o)=>{this.relayer.request(s).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Ie.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:Os(s.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,An(vs({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,vs({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),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,vs({},t)),this.topicMap.set(t.topic,e),this.events.emit(Ve.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:s}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(Ve.deleted,An(vs({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ve.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let s=0;s<t;s++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(Ve.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=se("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=>An(vs({},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 Zf(v.cjsExports$1.toMiliseconds(v.cjsExports$1.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}=se("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 $r(e+await this.getClientId())}};var Db=Object.defineProperty,Pc=Object.getOwnPropertySymbols,Fb=Object.prototype.hasOwnProperty,Mb=Object.prototype.propertyIsEnumerable,Po=(i,e,t)=>e in i?Db(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,_c=(i,e)=>{for(var t in e||(e={}))Fb.call(e,t)&&Po(i,t,e[t]);if(Pc)for(var t of Pc(e))Mb.call(e,t)&&Po(i,t,e[t]);return i},ee=(i,e,t)=>Po(i,typeof e!="symbol"?e+"":e,t);let zb=class extends If{constructor(e){super(e),ee(this,"protocol","wc"),ee(this,"version",2),ee(this,"core"),ee(this,"logger"),ee(this,"events",new v.eventsExports.EventEmitter),ee(this,"provider"),ee(this,"messages"),ee(this,"subscriber"),ee(this,"publisher"),ee(this,"name",bw),ee(this,"transportExplicitlyClosed",!1),ee(this,"initialized",!1),ee(this,"connectionAttemptInProgress",!1),ee(this,"relayUrl"),ee(this,"projectId"),ee(this,"packageName"),ee(this,"bundleId"),ee(this,"hasExperiencedNetworkDisruption",!1),ee(this,"pingTimeout"),ee(this,"heartBeatTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.THIRTY_SECONDS+v.cjsExports$1.FIVE_SECONDS)),ee(this,"reconnectTimeout"),ee(this,"connectPromise"),ee(this,"reconnectInProgress",!1),ee(this,"requestsInFlight",[]),ee(this,"connectTimeout",v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_SECOND*15)),ee(this,"request",async t=>{var s,r;this.logger.debug("Publishing Request Payload");const n=t.id||v.getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(s=t.params)==null?void 0:s.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(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),ee(this,"resetPingTimeout",()=>{Or()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,s,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(s=(t=this.provider)==null?void 0:t.connection)==null?void 0:s.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),ee(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),ee(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Ie.connect)}),ee(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ee(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(Ie.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ee(this,"registerProviderListeners",()=>{this.provider.on(et.payload,this.onPayloadHandler),this.provider.on(et.connect,this.onConnectHandler),this.provider.on(et.disconnect,this.onDisconnectHandler),this.provider.on(et.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?v.E(e.logger,this.name):v.Ot(v.k({level:e.logger||mw})),this.messages=new Sb(this.logger,e.core),this.subscriber=new Lb(this,this.logger),this.publisher=new Rb(this,this.logger),this.relayUrl=e?.relayUrl||iu,this.projectId=e.projectId,kf()?this.packageName=ka():Lf()&&(this.bundleId=ka()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return v.y(this.logger)}get connected(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===1||!1}get connecting(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:le.relay},Ir.outbound)}async subscribe(e,t){var s,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((s=t?.internal)==null?void 0:s.throwOnFailedPublish)>"u"?!0:(r=t?.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const h=l=>{l.topic===e&&(this.subscriber.off(Ve.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Ve.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,_c({internal:{throwOnFailedPublish:o}},t)).catch(p=>{o&&u(p)})||a,l()})]),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 Dt(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,s)=>{await this.connect(e).then(t).catch(s).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 pc())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((s,r)=>s.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const s of t)try{await this.onMessageEvent(s)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+r?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:s}=e;if(!t.sessionExists){const r=Ns(v.cjsExports$1.FIVE_MINUTES),n={topic:s,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,n)}this.events.emit(Ie.message,e),await this.recordMessageEvent(e,Ir.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(s,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(et.disconnect,n),await Dt(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(et.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(et.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(et.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,s()})}catch(s){await this.subscriber.stop();const r=s;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(s=>setTimeout(s,v.cjsExports$1.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,s,r,n;if(Or())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(s=this.provider)==null?void 0:s.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new v.o(new v.f(Hf({sdkVersion:vo,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:s,message:r}=e;await this.messages.set(s,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||s.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,s);return r&&this.logger.warn(`Ignoring duplicate message: ${s}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),v.isJsonRpcRequest(e)){if(!e.method.endsWith(vw))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:le.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(_c({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else v.isJsonRpcResponse(e)&&this.events.emit(Ie.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Ir.inbound),this.events.emit(Ie.message,e))}async acknowledgePayload(e){const t=v.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(et.payload,this.onPayloadHandler),this.provider.off(et.connect,this.onConnectHandler),this.provider.off(et.disconnect,this.onDisconnectHandler),this.provider.off(et.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await pc();nw(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(s=>this.logger.error(s,s?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(v.r.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&cw())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Ie.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},v.cjsExports$1.toMiliseconds(Ew)))))}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}};function Hb(){}function Oc(i){if(!i||typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(i)==="[object Object]":!1}function Ac(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Rc(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Vb="[object RegExp]",Kb="[object String]",Gb="[object Number]",Wb="[object Boolean]",Nc="[object Arguments]",Zb="[object Symbol]",Jb="[object Date]",Yb="[object Map]",Qb="[object Set]",Xb="[object Array]",e1="[object Function]",t1="[object ArrayBuffer]",Rn="[object Object]",i1="[object Error]",s1="[object DataView]",r1="[object Uint8Array]",n1="[object Uint8ClampedArray]",o1="[object Uint16Array]",a1="[object Uint32Array]",c1="[object BigUint64Array]",h1="[object Int8Array]",l1="[object Int16Array]",u1="[object Int32Array]",d1="[object BigInt64Array]",p1="[object Float32Array]",f1="[object Float64Array]";function g1(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function y1(i,e,t){return Rs(i,e,void 0,void 0,void 0,void 0,t)}function Rs(i,e,t,s,r,n,o){const a=o(i,e,t,s,r,n);if(a!==void 0)return a;if(typeof i==typeof e)switch(typeof i){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return i===e;case"number":return i===e||Object.is(i,e);case"function":return i===e;case"object":return Bs(i,e,n,o)}return Bs(i,e,n,o)}function Bs(i,e,t,s){if(Object.is(i,e))return!0;let r=Rc(i),n=Rc(e);if(r===Nc&&(r=Rn),n===Nc&&(n=Rn),r!==n)return!1;switch(r){case Kb:return i.toString()===e.toString();case Gb:{const c=i.valueOf(),h=e.valueOf();return g1(c,h)}case Wb:case Jb:case Zb:return Object.is(i.valueOf(),e.valueOf());case Vb:return i.source===e.source&&i.flags===e.flags;case e1:return i===e}t=t??new Map;const o=t.get(i),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(i,e),t.set(e,i);try{switch(r){case Yb:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!Rs(h,e.get(c),c,i,e,t,s))return!1;return!0}case Qb:{if(i.size!==e.size)return!1;const c=Array.from(i.values()),h=Array.from(e.values());for(let l=0;l<c.length;l++){const u=c[l],p=h.findIndex(g=>Rs(u,g,void 0,i,e,t,s));if(p===-1)return!1;h.splice(p,1)}return!0}case Xb:case r1:case n1:case o1:case a1:case c1:case h1:case l1:case u1:case d1:case p1:case f1:{if(typeof z.Buffer<"u"&&z.Buffer.isBuffer(i)!==z.Buffer.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!Rs(i[c],e[c],c,i,e,t,s))return!1;return!0}case t1:return i.byteLength!==e.byteLength?!1:Bs(new Uint8Array(i),new Uint8Array(e),t,s);case s1:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:Bs(new Uint8Array(i),new Uint8Array(e),t,s);case i1:return i.name===e.name&&i.message===e.message;case Rn:{if(!(Bs(i.constructor,e.constructor,t,s)||Oc(i)&&Oc(e)))return!1;const c=[...Object.keys(i),...Ac(i)],h=[...Object.keys(e),...Ac(e)];if(c.length!==h.length)return!1;for(let l=0;l<c.length;l++){const u=c[l],p=i[u];if(!Object.hasOwn(e,u))return!1;const g=e[u];if(!Rs(p,g,u,i,e,t,s))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function w1(i,e){return y1(i,e,Hb)}var m1=Object.defineProperty,Tc=Object.getOwnPropertySymbols,b1=Object.prototype.hasOwnProperty,v1=Object.prototype.propertyIsEnumerable,_o=(i,e,t)=>e in i?m1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Cc=(i,e)=>{for(var t in e||(e={}))b1.call(e,t)&&_o(i,t,e[t]);if(Tc)for(var t of Tc(e))v1.call(e,t)&&_o(i,t,e[t]);return i},qe=(i,e,t)=>_o(i,typeof e!="symbol"?e+"":e,t);let ui=class extends Sf{constructor(e,t,s,r=bt,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,qe(this,"map",new Map),qe(this,"version",$w),qe(this,"cached",[]),qe(this,"initialized",!1),qe(this,"getKey"),qe(this,"storagePrefix",bt),qe(this,"recentlyDeleted",[]),qe(this,"recentlyDeletedLimit",200),qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!mo(o)?this.map.set(this.getKey(o),o):ew(o)?this.map.set(o.id,o):tw(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),qe(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())}),qe(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),qe(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>w1(a[c],o[c]))):this.values)),qe(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Cc(Cc({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),qe(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=v.E(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return v.y(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}=se("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:s}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}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}=se("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}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var E1=Object.defineProperty,$1=(i,e,t)=>e in i?E1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,J=(i,e,t)=>$1(i,typeof e!="symbol"?e+"":e,t);let I1=class{constructor(e,t){this.core=e,this.logger=t,J(this,"name",Pw),J(this,"version",_w),J(this,"events",new v.Nt),J(this,"pairings"),J(this,"initialized",!1),J(this,"storagePrefix",bt),J(this,"ignoredPayloadTypes",[us]),J(this,"registeredMethods",[]),J(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),J(this,"register",({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]}),J(this,"create",async s=>{this.isInitialized();const r=wo(),n=await this.core.crypto.setSymKey(r),o=Ns(v.cjsExports$1.FIVE_MINUTES),a={protocol:tu},c={topic:n,expiry:o,relay:a,active:!1,methods:s?.methods},h=dc({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:s?.methods});return this.events.emit(Zt.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:s?.transportType}),{topic:n,uri:h}}),J(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s?.uri,trace:[mt.pairing_started]}});this.isValidPair(s,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=uc(s.uri);r.props.properties.topic=n,r.addTrace(mt.pairing_uri_validation_success),r.addTrace(mt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(mt.existing_pairing),l.active)throw r.setError(St.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(mt.pairing_not_expired)}const u=c||Ns(v.cjsExports$1.FIVE_MINUTES),p={topic:n,relay:a,expiry:u,active:!1,methods:h};this.core.expirer.set(n,u),await this.pairings.set(n,p),r.addTrace(mt.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(Zt.create,p),r.addTrace(mt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(mt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(St.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(g){throw r.setError(St.subscribe_pairing_topic_failure),g}return r.addTrace(mt.subscribe_pairing_topic_success),p}),J(this,"activate",async({topic:s})=>{this.isInitialized();const r=Ns(v.cjsExports$1.FIVE_MINUTES);this.core.expirer.set(s,r),await this.pairings.update(s,{active:!0,expiry:r})}),J(this,"ping",async s=>{this.isInitialized(),await this.isValidPing(s),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=s;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Vf();this.events.once(gn("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),J(this,"updateExpiry",async({topic:s,expiry:r})=>{this.isInitialized(),await this.pairings.update(s,{expiry:r})}),J(this,"updateMetadata",async({topic:s,metadata:r})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:r})}),J(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),J(this,"disconnect",async s=>{this.isInitialized(),await this.isValidDisconnect(s);const{topic:r}=s;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",As("USER_DISCONNECTED")),await this.deletePairing(r))}),J(this,"formatUriFromPairing",s=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=s,c=this.core.crypto.keychain.get(r);return dc({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),J(this,"sendRequest",async(s,r,n)=>{const o=v.formatJsonRpcRequest(r,n),a=await this.core.crypto.encode(s,o),c=ms[r].req;return this.core.history.set(s,o),this.core.relayer.publish(s,a,c),o.id}),J(this,"sendResult",async(s,r,n)=>{const o=v.formatJsonRpcResult(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=ms[c].res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),J(this,"sendError",async(s,r,n)=>{const o=v.formatJsonRpcError(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=ms[c]?ms[c].res:ms.unregistered_method.res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),J(this,"deletePairing",async(s,r)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,As("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),r?Promise.resolve():this.core.expirer.del(s)])}),J(this,"cleanup",async()=>{const s=this.pairings.getAll().filter(r=>La(r.expiry));await Promise.all(s.map(r=>this.deletePairing(r.topic)))}),J(this,"onRelayEventRequest",async s=>{const{topic:r,payload:n}=s;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)}}),J(this,"onRelayEventResponse",async s=>{const{topic:r,payload:n}=s,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)}}),J(this,"onPairingPingRequest",async(s,r)=>{const{id:n}=r;try{this.isValidPing({topic:s}),await this.sendResult(n,s,!0),this.events.emit(Zt.ping,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),J(this,"onPairingPingResponse",(s,r)=>{const{id:n}=r;setTimeout(()=>{v.isJsonRpcResult(r)?this.events.emit(gn("pairing_ping",n),{}):v.isJsonRpcError(r)&&this.events.emit(gn("pairing_ping",n),{error:r.error})},500)}),J(this,"onPairingDeleteRequest",async(s,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(Zt.delete,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),J(this,"onUnknownRpcMethodRequest",async(s,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=As("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,s,a),this.logger.error(a)}catch(a){await this.sendError(n,s,a),this.logger.error(a)}}),J(this,"onUnknownRpcMethodResponse",s=>{this.registeredMethods.includes(s)||this.logger.error(As("WC_METHOD_UNSUPPORTED",s))}),J(this,"isValidPair",(s,r)=>{var n;if(!Pn(s)){const{message:a}=se("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(St.malformed_pairing_uri),new Error(a)}if(!Xy(s.uri)){const{message:a}=se("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(St.malformed_pairing_uri),new Error(a)}const o=uc(s?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=se("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(St.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=se("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(St.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&v.cjsExports$1.toMiliseconds(o?.expiryTimestamp)<Date.now()){r.setError(St.pairing_expired);const{message:a}=se("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),J(this,"isValidPing",async s=>{if(!Pn(s)){const{message:n}=se("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),J(this,"isValidDisconnect",async s=>{if(!Pn(s)){const{message:n}=se("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),J(this,"isValidPairingTopic",async s=>{if(!Ql(s)){const{message:r}=se("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(r)}if(!this.pairings.keys.includes(s)){const{message:r}=se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(r)}if(La(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:r}=se("EXPIRED",`pairing topic: ${s}`);throw new Error(r)}}),this.core=e,this.logger=v.E(t,this.name),this.pairings=new ui(this.core,this.logger,this.name,this.storagePrefix)}get context(){return v.y(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ie.message,async e=>{const{topic:t,message:s,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==le.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);v.isJsonRpcRequest(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):v.isJsonRpcResponse(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,s)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(it.expired,async e=>{const{topic:t}=Wf(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Zt.expire,{topic:t}))})}};var S1=Object.defineProperty,x1=(i,e,t)=>e in i?S1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Re=(i,e,t)=>x1(i,typeof e!="symbol"?e+"":e,t);let P1=class extends vf{constructor(e,t){super(e,t),this.core=e,this.logger=t,Re(this,"records",new Map),Re(this,"events",new v.eventsExports.EventEmitter),Re(this,"name",Ow),Re(this,"version",Aw),Re(this,"cached",[]),Re(this,"initialized",!1),Re(this,"storagePrefix",bt),Re(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.records.set(s.id,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Re(this,"set",(s,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:s,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:s,request:{method:r.method,params:r.params||null},chainId:n,expiry:Ns(v.cjsExports$1.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(rt.created,o)}),Re(this,"resolve",async s=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:s}),!this.records.has(s.id))return;const r=await this.getRecord(s.id);typeof r.response>"u"&&(r.response=v.isJsonRpcError(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(rt.updated,r))}),Re(this,"get",async(s,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:s,id:r}),await this.getRecord(r))),Re(this,"delete",(s,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===s){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(rt.deleted,n)}}),this.persist()}),Re(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),Re(this,"on",(s,r)=>{this.events.on(s,r)}),Re(this,"once",(s,r)=>{this.events.once(s,r)}),Re(this,"off",(s,r)=>{this.events.off(s,r)}),Re(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=v.E(t,this.name)}get context(){return v.y(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 s={topic:t.topic,request:v.formatJsonRpcRequest(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),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:s}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(rt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=se("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(rt.created,e=>{const t=rt.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(rt.updated,e=>{const t=rt.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(rt.deleted,e=>{const t=rt.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(v.r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{v.cjsExports$1.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(rt.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var _1=Object.defineProperty,O1=(i,e,t)=>e in i?_1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ce=(i,e,t)=>O1(i,typeof e!="symbol"?e+"":e,t);let A1=class extends Pf{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ce(this,"expirations",new Map),Ce(this,"events",new v.eventsExports.EventEmitter),Ce(this,"name",Rw),Ce(this,"version",Nw),Ce(this,"cached",[]),Ce(this,"initialized",!1),Ce(this,"storagePrefix",bt),Ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.expirations.set(s.target,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ce(this,"has",s=>{try{const r=this.formatTarget(s);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ce(this,"set",(s,r)=>{this.isInitialized();const n=this.formatTarget(s),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(it.created,{target:n,expiration:o})}),Ce(this,"get",s=>{this.isInitialized();const r=this.formatTarget(s);return this.getExpiration(r)}),Ce(this,"del",s=>{if(this.isInitialized(),this.has(s)){const r=this.formatTarget(s),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(it.deleted,{target:r,expiration:n})}}),Ce(this,"on",(s,r)=>{this.events.on(s,r)}),Ce(this,"once",(s,r)=>{this.events.once(s,r)}),Ce(this,"off",(s,r)=>{this.events.off(s,r)}),Ce(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=v.E(t,this.name)}get context(){return v.y(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 Kf(e);if(typeof e=="number")return Gf(e);const{message:t}=se("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(it.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=se("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:s}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(s),new Error(s)}return t}checkExpiry(e,t){const{expiry:s}=t;v.cjsExports$1.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(it.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(v.r.pulse,()=>this.checkExpirations()),this.events.on(it.created,e=>{const t=it.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(it.expired,e=>{const t=it.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(it.deleted,e=>{const t=it.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}};var R1=Object.defineProperty,N1=(i,e,t)=>e in i?R1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ye=(i,e,t)=>N1(i,typeof e!="symbol"?e+"":e,t);let T1=class extends _f{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,ye(this,"name",Tw),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",Bw),ye(this,"storagePrefix",bt),ye(this,"version",eu),ye(this,"publicKey"),ye(this,"fetchPromise"),ye(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&v.cjsExports$1.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ye(this,"register",async r=>{if(!Ws()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const h=v.cjsExports$2.getDocument(),l=this.startAbortTimer(v.cjsExports$1.ONE_SECOND*5),u=await new Promise((p,g)=>{const w=()=>{window.removeEventListener("message",d),h.body.removeChild(y),g("attestation aborted")};this.abortController.signal.addEventListener("abort",w);const y=h.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",w,{signal:this.abortController.signal});const d=m=>{if(m.data&&typeof m.data=="string")try{const f=JSON.parse(m.data);if(f.type==="verify_attestation"){if(v.sn(f.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(y),this.abortController.signal.removeEventListener("abort",w),window.removeEventListener("message",d),p(f.attestation===null?"":f.attestation)}}catch(f){this.logger.warn(f)}};h.body.appendChild(y),window.addEventListener("message",d,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),ye(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(v.sn(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(r?.verifyUrl);return this.fetchAttestation(o,c)}),ye(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(v.cjsExports$1.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}),ye(this,"getVerifyUrl",r=>{let n=r||Cs;return Uw.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Cs}`),n=Cs),n}),ye(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(v.cjsExports$1.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)}}),ye(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),ye(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ye(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")}}),ye(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ye(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}),ye(this,"validateAttestation",(r,n)=>{const o=Ky(r,n.publicKey),a={hasExpired:v.cjsExports$1.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=v.E(t,this.name),this.abortController=new AbortController,this.isDevEnv=El(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return v.y(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),v.cjsExports$1.toMiliseconds(e))}};var C1=Object.defineProperty,B1=(i,e,t)=>e in i?C1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Bc=(i,e,t)=>B1(i,typeof e!="symbol"?e+"":e,t);let U1=class extends Of{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Bc(this,"context",jw),Bc(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${qw}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=v.E(t,this.context)}};var j1=Object.defineProperty,Uc=Object.getOwnPropertySymbols,q1=Object.prototype.hasOwnProperty,k1=Object.prototype.propertyIsEnumerable,Oo=(i,e,t)=>e in i?j1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Es=(i,e)=>{for(var t in e||(e={}))q1.call(e,t)&&Oo(i,t,e[t]);if(Uc)for(var t of Uc(e))k1.call(e,t)&&Oo(i,t,e[t]);return i},we=(i,e,t)=>Oo(i,typeof e!="symbol"?e+"":e,t);class L1 extends Af{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,we(this,"context",Lw),we(this,"storagePrefix",bt),we(this,"storageVersion",kw),we(this,"events",new Map),we(this,"shouldPersist",!1),we(this,"init",async()=>{if(!El())try{const r={eventId:Da(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:bl(this.core.relayer.protocol,this.core.relayer.version,vo)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),we(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,h=Da(),l=this.core.projectId||"",u=Date.now(),p=Es({eventId:h,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(h));return this.telemetryEnabled&&(this.events.set(h,p),this.shouldPersist=!0),p}),we(this,"getEvent",r=>{const{eventId:n,topic:o}=r;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Es(Es({},a),this.setMethods(a.eventId))}),we(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),we(this,"setEventListeners",()=>{this.core.heartbeat.on(v.r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{v.cjsExports$1.fromMiliseconds(Date.now())-v.cjsExports$1.fromMiliseconds(r.timestamp)>Dw&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),we(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),we(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)}),we(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)}),we(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),we(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,Es(Es({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),we(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)}}),we(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Fw}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${vo}${n}`,{method:"POST",body:JSON.stringify(r)})}),we(this,"getAppDomain",()=>Ff().url),this.logger=v.E(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var D1=Object.defineProperty,jc=Object.getOwnPropertySymbols,F1=Object.prototype.hasOwnProperty,M1=Object.prototype.propertyIsEnumerable,Ao=(i,e,t)=>e in i?D1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qc=(i,e)=>{for(var t in e||(e={}))F1.call(e,t)&&Ao(i,t,e[t]);if(jc)for(var t of jc(e))M1.call(e,t)&&Ao(i,t,e[t]);return i},ce=(i,e,t)=>Ao(i,typeof e!="symbol"?e+"":e,t);let z1=class fu extends yf{constructor(e){var t;super(e),ce(this,"protocol",Xl),ce(this,"version",eu),ce(this,"name",bo),ce(this,"relayUrl"),ce(this,"projectId"),ce(this,"customStoragePrefix"),ce(this,"events",new v.eventsExports.EventEmitter),ce(this,"logger"),ce(this,"heartbeat"),ce(this,"relayer"),ce(this,"crypto"),ce(this,"storage"),ce(this,"history"),ce(this,"expirer"),ce(this,"pairing"),ce(this,"verify"),ce(this,"echoClient"),ce(this,"linkModeSupportedApps"),ce(this,"eventClient"),ce(this,"initialized",!1),ce(this,"logChunkController"),ce(this,"on",(a,c)=>this.events.on(a,c)),ce(this,"once",(a,c)=>this.events.once(a,c)),ce(this,"off",(a,c)=>this.events.off(a,c)),ce(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ce(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:le.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(e?.customStoragePrefix);if(s)try{return this.customStoragePrefix=s.customStoragePrefix,this.logger=s.logger,this.heartbeat=s.heartbeat,this.crypto=s.crypto,this.history=s.history,this.expirer=s.expirer,this.storage=s.storage,this.relayer=s.relayer,this.pairing=s.pairing,this.verify=s.verify,this.echoClient=s.echoClient,this.linkModeSupportedApps=s.linkModeSupportedApps,this.eventClient=s.eventClient,this.initialized=s.initialized,this.logChunkController=s.logChunkController,s}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||iu,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=v.k({level:typeof e?.logger=="string"&&e.logger?e.logger:hw.logger,name:bo}),{logger:n,chunkLoggerController:o}=v.A({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=v.E(n,this.name),this.heartbeat=new v.i,this.crypto=new yb(this,this.logger,e?.keychain),this.history=new P1(this,this.logger),this.expirer=new A1(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new v.h(qc(qc({},lw),e?.storageOptions)),this.relayer=new zb({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new I1(this,this.logger),this.verify=new T1(this,this.logger,this.storage),this.echoClient=new U1(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new L1(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new fu(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(Iw,s),t}get context(){return v.y(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(yc,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(yc)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,s=`${t}_count`;return globalThis[s]=(globalThis[s]||0)+1,globalThis[s]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[s]} times.`),globalThis[t]}catch(t){console.warn("Failed to get global WalletConnect core",t);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${((t=e.opts)==null?void 0:t.customStoragePrefix)||""}`;globalThis[s]=e}catch(s){console.warn("Failed to set global WalletConnect core",s)}}isGlobalCoreDisabled(){try{return typeof z.process$1<"u"&&z.process$1.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const H1=z1;function Fs(i,{strict:e=!0}={}){return!i||typeof i!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(i):i.startsWith("0x")}function kc(i){return Fs(i,{strict:!1})?Math.ceil((i.length-2)/2):i.length}const gu="2.23.2";let Nn={getDocsUrl:({docsBaseUrl:i,docsPath:e="",docsSlug:t})=>e?`${i??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${gu}`};class ai extends Error{constructor(e,t={}){const s=t.cause instanceof ai?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof ai&&t.cause.docsPath||t.docsPath,n=Nn.getDocsUrl?.({...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...s?[`Details: ${s}`]:[],...Nn.version?[`Version: ${Nn.version}`]:[]].join(`
2
+ `);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=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=gu}walk(e){return yu(this,e)}}function yu(i,e){return e?.(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?yu(i.cause,e):e?null:i}class wu extends ai{constructor({size:e,targetSize:t,type:s}){super(`${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function ds(i,{dir:e,size:t=32}={}){return typeof i=="string"?V1(i,{dir:e,size:t}):K1(i,{dir:e,size:t})}function V1(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new wu({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function K1(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new wu({size:i.length,targetSize:t,type:"bytes"});const s=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";s[n?r:t-r-1]=i[n?r:i.length-r-1]}return s}class G1 extends ai{constructor({max:e,min:t,signed:s,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${s?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class W1 extends ai{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ps(i,{size:e}){if(kc(i)>e)throw new W1({givenSize:kc(i),maxSize:e})}function Ro(i,e={}){const{signed:t}=e;e.size&&ps(i,{size:e.size});const s=BigInt(i);if(!t)return s;const r=(i.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return s<=n?s:s-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function Z1(i,e={}){return Number(Ro(i,e))}const J1=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function No(i,e={}){return typeof i=="number"||typeof i=="bigint"?bu(i,e):typeof i=="string"?X1(i,e):typeof i=="boolean"?Y1(i,e):mu(i,e)}function Y1(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?(ps(t,{size:e.size}),ds(t,{size:e.size})):t}function mu(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=J1[i[r]];const s=`0x${t}`;return typeof e.size=="number"?(ps(s,{size:e.size}),ds(s,{dir:"right",size:e.size})):s}function bu(i,e={}){const{signed:t,size:s}=e,r=BigInt(i);let n;s?t?n=(1n<<BigInt(s)*8n-1n)-1n:n=2n**(BigInt(s)*8n)-1n:typeof i=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof i=="bigint"?"n":"";throw new G1({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:s,value:`${i}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(s*8))+BigInt(r):r).toString(16)}`;return s?ds(a,{size:s}):a}const Q1=new TextEncoder;function X1(i,e={}){const t=Q1.encode(i);return mu(t,e)}const e0=new TextEncoder;function t0(i,e={}){return typeof i=="number"||typeof i=="bigint"?s0(i,e):typeof i=="boolean"?i0(i,e):Fs(i)?vu(i,e):Eu(i,e)}function i0(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?(ps(t,{size:e.size}),ds(t,{size:e.size})):t}const $t={zero:48,nine:57,A:65,F:70,a:97,f:102};function Lc(i){if(i>=$t.zero&&i<=$t.nine)return i-$t.zero;if(i>=$t.A&&i<=$t.F)return i-($t.A-10);if(i>=$t.a&&i<=$t.f)return i-($t.a-10)}function vu(i,e={}){let t=i;e.size&&(ps(t,{size:e.size}),t=ds(t,{dir:"right",size:e.size}));let s=t.slice(2);s.length%2&&(s=`0${s}`);const r=s.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=Lc(s.charCodeAt(a++)),h=Lc(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new ai(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function s0(i,e){const t=bu(i,e);return vu(t)}function Eu(i,e={}){const t=e0.encode(i);return typeof e.size=="number"?(ps(t,{size:e.size}),ds(t,{dir:"right",size:e.size})):t}function Rr(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function r0(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function er(i,...e){if(!r0(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function n0(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Rr(i.outputLen),Rr(i.blockLen)}function To(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function $u(i,e){er(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ur=BigInt(2**32-1),Dc=BigInt(32);function o0(i,e=!1){return e?{h:Number(i&ur),l:Number(i>>Dc&ur)}:{h:Number(i>>Dc&ur)|0,l:Number(i&ur)|0}}function a0(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=o0(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const c0=(i,e,t)=>i<<t|e>>>32-t,h0=(i,e,t)=>e<<t|i>>>32-t,l0=(i,e,t)=>e<<t-32|i>>>64-t,u0=(i,e,t)=>i<<t-32|e>>>64-t,mi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function d0(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function p0(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function f0(i,e){return i<<32-e|i>>>e}const Fc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function g0(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Mc(i){for(let e=0;e<i.length;e++)i[e]=g0(i[e])}function y0(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function sa(i){return typeof i=="string"&&(i=y0(i)),er(i),i}function w0(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];er(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}class Iu{clone(){return this._cloneInto()}}function Su(i){const e=s=>i().update(sa(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function m0(i=32){if(mi&&typeof mi.getRandomValues=="function")return mi.getRandomValues(new Uint8Array(i));if(mi&&typeof mi.randomBytes=="function")return mi.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const xu=[],Pu=[],_u=[],b0=BigInt(0),$s=BigInt(1),v0=BigInt(2),E0=BigInt(7),$0=BigInt(256),I0=BigInt(113);for(let i=0,e=$s,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],xu.push(2*(5*s+t)),Pu.push((i+1)*(i+2)/2%64);let r=b0;for(let n=0;n<7;n++)e=(e<<$s^(e>>E0)*I0)%$0,e&v0&&(r^=$s<<($s<<BigInt(n))-$s);_u.push(r)}const[S0,x0]=a0(_u,!0),zc=(i,e,t)=>t>32?l0(i,e,t):c0(i,e,t),Hc=(i,e,t)=>t>32?u0(i,e,t):h0(i,e,t);function P0(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=zc(h,l,1)^t[a],p=Hc(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Pu[o],c=zc(r,n,a),h=Hc(r,n,a),l=xu[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=S0[s],i[1]^=x0[s]}t.fill(0)}class ra extends Iu{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Rr(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=d0(this.state)}keccak(){Fc||Mc(this.state32),P0(this.state32,this.rounds),Fc||Mc(this.state32),this.posOut=0,this.pos=0}update(e){To(this);const{blockLen:t,state:s}=this;e=sa(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){To(this,!1),er(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 Rr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($u(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:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new ra(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const _0=(i,e,t)=>Su(()=>new ra(e,i,t)),O0=_0(1,136,256/8);function Ou(i,e){const t=e||"hex",s=O0(Fs(i,{strict:!1})?t0(i):i);return t==="bytes"?s:No(s)}class A0 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 s=this.keys().next().value;s&&this.delete(s)}return this}}const Tn=new A0(8192);function R0(i,e){if(Tn.has(`${i}.${e}`))return Tn.get(`${i}.${e}`);const t=i.substring(2).toLowerCase(),s=Ou(Eu(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)s[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(s[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Tn.set(`${i}.${e}`,n),n}function N0(i){const e=Ou(`0x${i.substring(4)}`).substring(26);return R0(`0x${e}`)}async function T0({hash:i,signature:e}){const t=Fs(i)?i:No(i),{secp256k1:s}=await Promise.resolve().then(()=>require("./secp256k1-BxlHgrPu.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:u,yParity:p}=e,g=Number(p??u),w=Vc(g);return new s.Signature(Ro(h),Ro(l)).addRecoveryBit(w)}const o=Fs(e)?e:No(e),a=Z1(`0x${o.slice(130)}`),c=Vc(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Vc(i){if(i===0||i===1)return i;if(i===27)return 0;if(i===28)return 1;throw new Error("Invalid yParityOrV value")}async function C0({hash:i,signature:e}){return N0(await T0({hash:i,signature:e}))}function B0(i){if(i.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<i.length;h++){const l=i.charAt(h),u=l.charCodeAt(0);if(e[u]!==255)throw new TypeError(l+" is ambiguous");e[u]=h}const t=i.length,s=i.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let l=0,u=0,p=0;const g=h.length;for(;p!==g&&h[p]===0;)p++,l++;const w=(g-p)*n+1>>>0,y=new Uint8Array(w);for(;p!==g;){let f=h[p],E=0;for(let _=w-1;(f!==0||E<u)&&_!==-1;_--,E++)f+=256*y[_]>>>0,y[_]=f%t>>>0,f=f/t>>>0;if(f!==0)throw new Error("Non-zero carry");u=E,p++}let d=w-u;for(;d!==w&&y[d]===0;)d++;let m=s.repeat(l);for(;d<w;++d)m+=i.charAt(y[d]);return m}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,u=0,p=0;for(;h[l]===s;)u++,l++;const g=(h.length-l)*r+1>>>0,w=new Uint8Array(g);for(;l<h.length;){const f=h.charCodeAt(l);if(f>255)return;let E=e[f];if(E===255)return;let _=0;for(let C=g-1;(E!==0||_<p)&&C!==-1;C--,_++)E+=t*w[C]>>>0,w[C]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");p=_,l++}let y=g-p;for(;y!==g&&w[y]===0;)y++;const d=new Uint8Array(u+(g-y));let m=u;for(;y!==g;)d[m++]=w[y++];return d}function c(h){const l=a(h);if(l)return l;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var U0="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const j0=B0(U0),q0=":";function Sr(i){const[e,t]=i.split(q0);return{namespace:e,reference:t}}function Au(i,e){return i.includes(":")?[i]:e.chains||[]}var k0=Object.defineProperty,L0=Object.defineProperties,D0=Object.getOwnPropertyDescriptors,Kc=Object.getOwnPropertySymbols,F0=Object.prototype.hasOwnProperty,M0=Object.prototype.propertyIsEnumerable,Gc=(i,e,t)=>e in i?k0(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wc=(i,e)=>{for(var t in e||(e={}))F0.call(e,t)&&Gc(i,t,e[t]);if(Kc)for(var t of Kc(e))M0.call(e,t)&&Gc(i,t,e[t]);return i},z0=(i,e)=>L0(i,D0(e));const H0="ReactNative",Li={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"};function Ru(){return typeof z.process$1<"u"&&typeof z.process$1.versions<"u"&&typeof z.process$1.versions.node<"u"}function Nu(){return!v.cjsExports$2.getDocument()&&!!v.cjsExports$2.getNavigator()&&navigator.product===H0}function Tu(){return!Ru()&&!!v.cjsExports$2.getNavigator()&&!!v.cjsExports$2.getDocument()}function V0(){return Nu()?Li.reactNative:Ru()?Li.node:Tu()?Li.browser:Li.unknown}function K0(i){var e,t;const s=G0();try{return i!=null&&i.url&&s.url&&new URL(i.url).host!==new URL(s.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${i.url} differs from the actual page url:${s.url}. This is probably unintended and can lead to issues.`),i.url=s.url),(e=i?.icons)!=null&&e.length&&i.icons.length>0&&(i.icons=i.icons.filter(r=>r!=="")),z0(Wc(Wc({},s),i),{url:i?.url||s.url,name:i?.name||s.name,description:i?.description||s.description,icons:(t=i?.icons)!=null&&t.length&&i.icons.length>0?i.icons:s.icons})}catch(r){return console.warn("Error populating app metadata",r),i||s}}function G0(){return v.cjsExports.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Qt(i,e){return i.filter(t=>e.includes(t)).length===i.length}function bi(i=v.cjsExports$1.FIVE_MINUTES,e){const t=v.cjsExports$1.toMiliseconds(i||v.cjsExports$1.FIVE_MINUTES);let s,r,n,o;return{resolve:a=>{n&&s&&(clearTimeout(n),s(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const h=new Error(e);o=Promise.reject(h),c(h)},t),s=a,r=c})}}function W0(i){const[e,t]=i.split(":"),s={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")s.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))s.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return s}function ke(i,e){return v.cjsExports$1.fromMiliseconds(Date.now()+v.cjsExports$1.toMiliseconds(i))}function vi(i){return Date.now()>=v.cjsExports$1.toMiliseconds(i)}function ne(i,e){return`${i}${e?`:${e}`:""}`}function ii(i=[],e=[]){return[...new Set([...i,...e])]}async function Z0({id:i,topic:e,wcDeepLink:t}){var s;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r?.href;if(typeof n!="string")return;const o=J0(n,i,e),a=V0();if(a===Li.browser){if(!((s=v.cjsExports$2.getDocument())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Y0(o)}else a===Li.reactNative&&typeof(z.global==null?void 0:z.global.Linking)<"u"&&await z.global.Linking.openURL(o)}catch(r){console.error(r)}}function J0(i,e,t){const s=`requestId=${e}&sessionTopic=${t}`;i.endsWith("/")&&(i=i.slice(0,-1));let r=`${i}`;if(i.startsWith("https://t.me")){const n=i.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${iv(s,!0)}`}else r=`${r}/wc?${s}`;return r}function Y0(i){let e="_self";tv()?e="_top":(ev()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function Q0(i,e){let t="";try{if(Tu()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function Zc(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function X0(){return typeof z.process$1<"u"&&z.process$1.env.IS_VITEST==="true"}function ev(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function tv(){try{return window.self!==window.top}catch{return!1}}function iv(i,e=!1){const t=z.Buffer.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Nr(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function sv(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function tr(i,...e){if(!sv(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function rv(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Nr(i.outputLen),Nr(i.blockLen)}function is(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Cu(i,e){tr(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const dr=BigInt(2**32-1),Jc=BigInt(32);function nv(i,e=!1){return e?{h:Number(i&dr),l:Number(i>>Jc&dr)}:{h:Number(i>>Jc&dr)|0,l:Number(i&dr)|0}}function ov(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=nv(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const av=(i,e,t)=>i<<t|e>>>32-t,cv=(i,e,t)=>e<<t|i>>>32-t,hv=(i,e,t)=>e<<t-32|i>>>64-t,lv=(i,e,t)=>i<<t-32|e>>>64-t,Ei=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function uv(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Cn(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function yt(i,e){return i<<32-e|i>>>e}const Yc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function dv(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Qc(i){for(let e=0;e<i.length;e++)i[e]=dv(i[e])}function pv(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function Jr(i){return typeof i=="string"&&(i=pv(i)),tr(i),i}function fv(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];tr(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}let na=class{clone(){return this._cloneInto()}};function Bu(i){const e=s=>i().update(Jr(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Uu(i=32){if(Ei&&typeof Ei.getRandomValues=="function")return Ei.getRandomValues(new Uint8Array(i));if(Ei&&typeof Ei.randomBytes=="function")return Ei.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const ju=[],qu=[],ku=[],gv=BigInt(0),Is=BigInt(1),yv=BigInt(2),wv=BigInt(7),mv=BigInt(256),bv=BigInt(113);for(let i=0,e=Is,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],ju.push(2*(5*s+t)),qu.push((i+1)*(i+2)/2%64);let r=gv;for(let n=0;n<7;n++)e=(e<<Is^(e>>wv)*bv)%mv,e&yv&&(r^=Is<<(Is<<BigInt(n))-Is);ku.push(r)}const[vv,Ev]=ov(ku,!0),Xc=(i,e,t)=>t>32?hv(i,e,t):av(i,e,t),eh=(i,e,t)=>t>32?lv(i,e,t):cv(i,e,t);function $v(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=Xc(h,l,1)^t[a],p=eh(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=qu[o],c=Xc(r,n,a),h=eh(r,n,a),l=ju[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=vv[s],i[1]^=Ev[s]}t.fill(0)}class oa extends na{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Nr(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=uv(this.state)}keccak(){Yc||Qc(this.state32),$v(this.state32,this.rounds),Yc||Qc(this.state32),this.posOut=0,this.pos=0}update(e){is(this);const{blockLen:t,state:s}=this;e=Jr(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){is(this,!1),tr(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 Nr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Cu(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:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new oa(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Iv=(i,e,t)=>Bu(()=>new oa(e,i,t)),Sv=Iv(1,136,256/8),xv="https://rpc.walletconnect.org/v1";function Lu(i){const e=`Ethereum Signed Message:
3
3
  ${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+z.Buffer.from(Sv(t)).toString("hex")}async function Pv(i,e,t,s,r,n){switch(t.t){case"eip191":return await _v(i,e,t.s);case"eip1271":return await Ov(i,e,t.s,s,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function _v(i,e,t){return(await C0({hash:Lu(e),signature:t})).toLowerCase()===i.toLowerCase()}async function Ov(i,e,t,s,r,n){const o=Sr(s);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${s}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",h="0000000000000000000000000000000000000000000000000000000000000041",l=t.substring(2),u=Lu(e).substring(2),p=a+u+c+h+l,g=await fetch(`${n||xv}/?chainId=${s}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:Av(),jsonrpc:"2.0",method:"eth_call",params:[{to:i,data:p},"latest"]})}),{result:w}=await g.json();return w?w.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Av(){return Date.now()+Math.floor(Math.random()*1e3)}function Rv(i){const e=atob(i),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);const s=t[0];if(s===0)throw new Error("No signatures found");const r=1+s*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=z.Buffer.from(i,"base64").slice(1,65);return j0.encode(n)}var Nv=Object.defineProperty,Tv=Object.defineProperties,Cv=Object.getOwnPropertyDescriptors,th=Object.getOwnPropertySymbols,Bv=Object.prototype.hasOwnProperty,Uv=Object.prototype.propertyIsEnumerable,ih=(i,e,t)=>e in i?Nv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,jv=(i,e)=>{for(var t in e||(e={}))Bv.call(e,t)&&ih(i,t,e[t]);if(th)for(var t of th(e))Uv.call(e,t)&&ih(i,t,e[t]);return i},qv=(i,e)=>Tv(i,Cv(e));const kv="did:pkh:",aa=i=>i?.split(":"),Lv=i=>{const e=i&&aa(i);if(e)return i.includes(kv)?e[3]:e[1]},Co=i=>{const e=i&&aa(i);if(e)return e[2]+":"+e[3]},Tr=i=>{const e=i&&aa(i);if(e)return e.pop()};async function sh(i){const{cacao:e,projectId:t}=i,{s,p:r}=e,n=Du(r,r.iss),o=Tr(r.iss);return await Pv(o,n,s,Co(r.iss),t)}const Du=(i,e)=>{const t=`${i.domain} wants you to sign in with your Ethereum account:`,s=Tr(e);if(!i.aud&&!i.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=i.statement||void 0;const n=`URI: ${i.aud||i.uri}`,o=`Version: ${i.version}`,a=`Chain ID: ${Lv(e)}`,c=`Nonce: ${i.nonce}`,h=`Issued At: ${i.iat}`,l=i.exp?`Expiration Time: ${i.exp}`:void 0,u=i.nbf?`Not Before: ${i.nbf}`:void 0,p=i.requestId?`Request ID: ${i.requestId}`:void 0,g=i.resources?`Resources:${i.resources.map(y=>`
4
4
  - ${y}`).join("")}`:void 0,w=xr(i.resources);if(w){const y=Ms(w);r=Wv(r,y)}return[t,s,"",r,"",n,o,a,c,h,l,u,p,g].filter(y=>y!=null).join(`
5
5
  `)};function Dv(i){return z.Buffer.from(JSON.stringify(i)).toString("base64")}function Fv(i){return JSON.parse(z.Buffer.from(i,"base64").toString("utf-8"))}function ci(i){if(!i)throw new Error("No recap provided, value is undefined");if(!i.att)throw new Error("No `att` property found");const e=Object.keys(i.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const s=i.att[t];if(Array.isArray(s))throw new Error(`Resource must be an object: ${t}`);if(typeof s!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(s).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(s).forEach(r=>{const n=s[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 Mv(i,e,t,s={}){return t?.sort((r,n)=>r.localeCompare(n)),{att:{[i]:zv(e,t,s)}}}function zv(i,e,t={}){e=e?.sort((r,n)=>r.localeCompare(n));const s=e.map(r=>({[`${i}/${r}`]:[t]}));return Object.assign({},...s)}function Fu(i){return ci(i),`urn:recap:${Dv(i).replace(/=/g,"")}`}function Ms(i){const e=Fv(i.replace("urn:recap:",""));return ci(e),e}function Hv(i,e,t){const s=Mv(i,e,t);return Fu(s)}function Vv(i){return i&&i.includes("urn:recap:")}function Kv(i,e){const t=Ms(i),s=Ms(e),r=Gv(t,s);return Fu(r)}function Gv(i,e){ci(i),ci(e);const t=Object.keys(i.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),s={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=i.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,h;s.att[r]=qv(jv({},s.att[r]),{[a]:((c=i.att[r])==null?void 0:c[a])||((h=e.att[r])==null?void 0:h[a])})})}),s}function Wv(i="",e){ci(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(i.includes(t))return i;const s=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,p)=>u.action.localeCompare(p.action));const h={};c.forEach(u=>{h[u.ability]||(h[u.ability]=[]),h[u.ability].push(u.action)});const l=Object.keys(h).map(u=>(r++,`(${r}) '${u}': '${h[u].join("', '")}' for '${a}'.`));s.push(l.join(", ").replace(".,","."))});const n=s.join(" "),o=`${t}${n}`;return`${i?i+" ":""}${o}`}function rh(i){var e;const t=Ms(i);ci(t);const s=(e=t.att)==null?void 0:e.eip155;return s?Object.keys(s).map(r=>r.split("/")[1]):[]}function nh(i){const e=Ms(i);ci(e);const t=[];return Object.values(e.att).forEach(s=>{Object.values(s).forEach(r=>{var n;(n=r?.[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function xr(i){if(!i)return;const e=i?.[i.length-1];return Vv(e)?e:void 0}function Bn(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Mu(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ye(i,...e){if(!Mu(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function oh(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Zv(i,e){Ye(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function ah(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const zt=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),Jv=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Yv=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Yv)throw new Error("Non little-endian hardware is not supported");function Qv(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function Bo(i){if(typeof i=="string")i=Qv(i);else if(Mu(i))i=Uo(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function Xv(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function eE(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}const tE=(i,e)=>{function t(s,...r){if(Ye(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?Ye(h):Ye(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&Ye(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");Ye(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ye(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(Ye(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(h,l)}}}return Object.assign(t,i),t};function ch(i,e,t=!0){if(e===void 0)return new Uint8Array(i);if(e.length!==i)throw new Error("invalid output length, expected "+i+", got: "+e.length);if(t&&!iE(e))throw new Error("invalid output, must be aligned");return e}function hh(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);i.setUint32(e+4,o,s),i.setUint32(e+0,a,s)}function iE(i){return i.byteOffset%4===0}function Uo(i){return Uint8Array.from(i)}function ss(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const zu=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),sE=zu("expand 16-byte k"),rE=zu("expand 32-byte k"),nE=zt(sE),oE=zt(rE);function te(i,e){return i<<e|i>>>32-e}function jo(i){return i.byteOffset%4===0}const pr=64,aE=16,Hu=2**32-1,lh=new Uint32Array;function cE(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(pr),l=zt(h),u=jo(r)&&jo(n),p=u?zt(r):lh,g=u?zt(n):lh;for(let w=0;w<c;o++){if(i(e,t,s,l,o,a),o>=Hu)throw new Error("arx: counter overflow");const y=Math.min(pr,c-w);if(u&&y===pr){const d=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let m=0,f;m<aE;m++)f=d+m,g[f]=p[f]^l[m];w+=pr;continue}for(let d=0,m;d<y;d++)m=w+d,n[m]=r[m]^h[d];w+=y}}function hE(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=Xv({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return Bn(r),Bn(o),ah(n),ah(t),(a,c,h,l,u=0)=>{Ye(a),Ye(c),Ye(h);const p=h.length;if(l===void 0&&(l=new Uint8Array(p)),Ye(l),Bn(u),u<0||u>=Hu)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const g=[];let w=a.length,y,d;if(w===32)g.push(y=Uo(a)),d=oE;else if(w===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),d=nE,g.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${w}`);jo(c)||g.push(c=Uo(c));const m=zt(y);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(d,m,zt(c.subarray(0,16)),m),c=c.subarray(16)}const f=16-r;if(f!==c.length)throw new Error(`arx: nonce must be ${f} or 16 bytes`);if(f!==12){const _=new Uint8Array(12);_.set(c,n?0:12-c.length),c=_,g.push(c)}const E=zt(c);return cE(i,d,m,E,h,l,u,o),ss(...g),l}}const Ne=(i,e)=>i[e++]&255|(i[e++]&255)<<8;class lE{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=Bo(e),Ye(e,32);const t=Ne(e,0),s=Ne(e,2),r=Ne(e,4),n=Ne(e,6),o=Ne(e,8),a=Ne(e,10),c=Ne(e,12),h=Ne(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>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|c<<5)&8065,this.r[8]=(c>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Ne(e,16+2*l)}process(e,t,s=!1){const r=s?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],l=o[3],u=o[4],p=o[5],g=o[6],w=o[7],y=o[8],d=o[9],m=Ne(e,t+0),f=Ne(e,t+2),E=Ne(e,t+4),_=Ne(e,t+6),C=Ne(e,t+8),O=Ne(e,t+10),P=Ne(e,t+12),R=Ne(e,t+14);let S=n[0]+(m&8191),U=n[1]+((m>>>13|f<<3)&8191),N=n[2]+((f>>>10|E<<6)&8191),B=n[3]+((E>>>7|_<<9)&8191),j=n[4]+((_>>>4|C<<12)&8191),b=n[5]+(C>>>1&8191),I=n[6]+((C>>>14|O<<2)&8191),$=n[7]+((O>>>11|P<<5)&8191),A=n[8]+((P>>>8|R<<8)&8191),T=n[9]+(R>>>5|r),x=0,q=x+S*a+U*(5*d)+N*(5*y)+B*(5*w)+j*(5*g);x=q>>>13,q&=8191,q+=b*(5*p)+I*(5*u)+$*(5*l)+A*(5*h)+T*(5*c),x+=q>>>13,q&=8191;let k=x+S*c+U*a+N*(5*d)+B*(5*y)+j*(5*w);x=k>>>13,k&=8191,k+=b*(5*g)+I*(5*p)+$*(5*u)+A*(5*l)+T*(5*h),x+=k>>>13,k&=8191;let L=x+S*h+U*c+N*a+B*(5*d)+j*(5*y);x=L>>>13,L&=8191,L+=b*(5*w)+I*(5*g)+$*(5*p)+A*(5*u)+T*(5*l),x+=L>>>13,L&=8191;let M=x+S*l+U*h+N*c+B*a+j*(5*d);x=M>>>13,M&=8191,M+=b*(5*y)+I*(5*w)+$*(5*g)+A*(5*p)+T*(5*u),x+=M>>>13,M&=8191;let F=x+S*u+U*l+N*h+B*c+j*a;x=F>>>13,F&=8191,F+=b*(5*d)+I*(5*y)+$*(5*w)+A*(5*g)+T*(5*p),x+=F>>>13,F&=8191;let H=x+S*p+U*u+N*l+B*h+j*c;x=H>>>13,H&=8191,H+=b*a+I*(5*d)+$*(5*y)+A*(5*w)+T*(5*g),x+=H>>>13,H&=8191;let K=x+S*g+U*p+N*u+B*l+j*h;x=K>>>13,K&=8191,K+=b*c+I*a+$*(5*d)+A*(5*y)+T*(5*w),x+=K>>>13,K&=8191;let Z=x+S*w+U*g+N*p+B*u+j*l;x=Z>>>13,Z&=8191,Z+=b*h+I*c+$*a+A*(5*d)+T*(5*y),x+=Z>>>13,Z&=8191;let G=x+S*y+U*w+N*g+B*p+j*u;x=G>>>13,G&=8191,G+=b*l+I*h+$*c+A*a+T*(5*d),x+=G>>>13,G&=8191;let W=x+S*d+U*y+N*w+B*g+j*p;x=W>>>13,W&=8191,W+=b*u+I*l+$*h+A*c+T*a,x+=W>>>13,W&=8191,x=(x<<2)+x|0,x=x+q|0,q=x&8191,x=x>>>13,k+=x,n[0]=q,n[1]=k,n[2]=L,n[3]=M,n[4]=F,n[5]=H,n[6]=K,n[7]=Z,n[8]=G,n[9]=W}finalize(){const{h:e,pad:t}=this,s=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,s[0]=e[0]+5,r=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+r,r=s[a]>>>13,s[a]&=8191;s[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)s[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|s[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;ss(s)}update(e){oh(this);const{buffer:t,blockLen:s}=this;e=Bo(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o===s){for(;s<=r-n;n+=s)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){ss(this.h,this.r,this.buffer,this.pad)}digestInto(e){oh(this),Zv(e,this),this.finished=!0;const{buffer:t,h:s}=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++]=s[o]>>>0,e[n++]=s[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}}function uE(i){const e=(s,r)=>i(r).update(Bo(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const dE=uE(i=>new lE(i));function pE(i,e,t,s,r,n=20){let o=i[0],a=i[1],c=i[2],h=i[3],l=e[0],u=e[1],p=e[2],g=e[3],w=e[4],y=e[5],d=e[6],m=e[7],f=r,E=t[0],_=t[1],C=t[2],O=o,P=a,R=c,S=h,U=l,N=u,B=p,j=g,b=w,I=y,$=d,A=m,T=f,x=E,q=_,k=C;for(let M=0;M<n;M+=2)O=O+U|0,T=te(T^O,16),b=b+T|0,U=te(U^b,12),O=O+U|0,T=te(T^O,8),b=b+T|0,U=te(U^b,7),P=P+N|0,x=te(x^P,16),I=I+x|0,N=te(N^I,12),P=P+N|0,x=te(x^P,8),I=I+x|0,N=te(N^I,7),R=R+B|0,q=te(q^R,16),$=$+q|0,B=te(B^$,12),R=R+B|0,q=te(q^R,8),$=$+q|0,B=te(B^$,7),S=S+j|0,k=te(k^S,16),A=A+k|0,j=te(j^A,12),S=S+j|0,k=te(k^S,8),A=A+k|0,j=te(j^A,7),O=O+N|0,k=te(k^O,16),$=$+k|0,N=te(N^$,12),O=O+N|0,k=te(k^O,8),$=$+k|0,N=te(N^$,7),P=P+B|0,T=te(T^P,16),A=A+T|0,B=te(B^A,12),P=P+B|0,T=te(T^P,8),A=A+T|0,B=te(B^A,7),R=R+j|0,x=te(x^R,16),b=b+x|0,j=te(j^b,12),R=R+j|0,x=te(x^R,8),b=b+x|0,j=te(j^b,7),S=S+U|0,q=te(q^S,16),I=I+q|0,U=te(U^I,12),S=S+U|0,q=te(q^S,8),I=I+q|0,U=te(U^I,7);let L=0;s[L++]=o+O|0,s[L++]=a+P|0,s[L++]=c+R|0,s[L++]=h+S|0,s[L++]=l+U|0,s[L++]=u+N|0,s[L++]=p+B|0,s[L++]=g+j|0,s[L++]=w+b|0,s[L++]=y+I|0,s[L++]=d+$|0,s[L++]=m+A|0,s[L++]=f+T|0,s[L++]=E+x|0,s[L++]=_+q|0,s[L++]=C+k|0}const fE=hE(pE,{counterRight:!1,counterLength:4,allowShortKeys:!1}),gE=new Uint8Array(16),uh=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(gE.subarray(t))},yE=new Uint8Array(32);function dh(i,e,t,s,r){const n=i(e,t,yE),o=dE.create(n);r&&uh(o,r),uh(o,s);const a=new Uint8Array(16),c=Jv(a);hh(c,0,BigInt(r?r.length:0),!0),hh(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return ss(n,a),h}const wE=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=ch(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=dh(i,e,t,a,s);return n.set(c,o),ss(c),n},decrypt(r,n){n=ch(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=dh(i,e,t,o,s);if(!eE(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),ss(c),n}});tE({blockSize:64,nonceLength:12,tagLength:16},wE(fE));class Vu extends na{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,rv(e);const s=Jr(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(s.length>r?e.create().update(s).digest():s);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 is(this),this.iHash.update(e),this}digestInto(e){is(this),tr(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:s,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=s._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ku=(i,e,t)=>new Vu(i,e).update(t).digest();Ku.create=(i,e)=>new Vu(i,e);function mE(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=s?4:0,h=s?0:4;i.setUint32(e+c,o,s),i.setUint32(e+h,a,s)}function bE(i,e,t){return i&e^~i&t}function vE(i,e,t){return i&e^i&t^e&t}let EE=class extends na{constructor(e,t,s,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Cn(this.buffer)}update(e){is(this);const{view:t,buffer:s,blockLen:r}=this;e=Jr(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const c=Cn(e);for(;r<=n-o;o+=r)this.process(c,o);continue}s.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){is(this),Cu(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(s,0),o=0);for(let u=o;u<r;u++)t[u]=0;mE(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=Cn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,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(s),e}};const $E=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]),kt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Lt=new Uint32Array(64);class IE extends EE{constructor(){super(64,32,8,!1),this.A=kt[0]|0,this.B=kt[1]|0,this.C=kt[2]|0,this.D=kt[3]|0,this.E=kt[4]|0,this.F=kt[5]|0,this.G=kt[6]|0,this.H=kt[7]|0}get(){const{A:e,B:t,C:s,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,s,r,n,o,a,c]}set(e,t,s,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Lt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=Lt[u-15],g=Lt[u-2],w=yt(p,7)^yt(p,18)^p>>>3,y=yt(g,17)^yt(g,19)^g>>>10;Lt[u]=y+Lt[u-7]+w+Lt[u-16]|0}let{A:s,B:r,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let u=0;u<64;u++){const p=yt(a,6)^yt(a,11)^yt(a,25),g=l+p+bE(a,c,h)+$E[u]+Lt[u]|0,w=(yt(s,2)^yt(s,13)^yt(s,22))+vE(s,r,n)|0;l=h,h=c,c=a,a=o+g|0,o=n,n=r,r=s,s=g+w|0}s=s+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(s,r,n,o,a,c,h,l)}roundClean(){Lt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const ca=Bu(()=>new IE);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Yr=BigInt(0),Qr=BigInt(1),SE=BigInt(2);function hi(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ir(i){if(!hi(i))throw new Error("Uint8Array expected")}function rs(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const xE=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function ns(i){ir(i);let e="";for(let t=0;t<i.length;t++)e+=xE[i[t]];return e}function Di(i){const e=i.toString(16);return e.length&1?"0"+e:e}function ha(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?Yr:BigInt("0x"+i)}const It={_0:48,_9:57,A:65,F:70,a:97,f:102};function ph(i){if(i>=It._0&&i<=It._9)return i-It._0;if(i>=It.A&&i<=It.F)return i-(It.A-10);if(i>=It.a&&i<=It.f)return i-(It.a-10)}function os(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const s=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=ph(i.charCodeAt(n)),a=ph(i.charCodeAt(n+1));if(o===void 0||a===void 0){const c=i[n]+i[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}s[r]=o*16+a}return s}function si(i){return ha(ns(i))}function zs(i){return ir(i),ha(ns(Uint8Array.from(i).reverse()))}function as(i,e){return os(i.toString(16).padStart(e*2,"0"))}function Xr(i,e){return as(i,e).reverse()}function PE(i){return os(Di(i))}function We(i,e,t){let s;if(typeof e=="string")try{s=os(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(hi(e))s=Uint8Array.from(e);else throw new Error(i+" must be hex string or Uint8Array");const r=s.length;if(typeof t=="number"&&r!==t)throw new Error(i+" of length "+t+" expected, got "+r);return s}function Hs(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];ir(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}function _E(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}function OE(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const Un=i=>typeof i=="bigint"&&Yr<=i;function en(i,e,t){return Un(i)&&Un(e)&&Un(t)&&e<=i&&i<t}function Ct(i,e,t,s){if(!en(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function Gu(i){let e;for(e=0;i>Yr;i>>=Qr,e+=1);return e}function AE(i,e){return i>>BigInt(e)&Qr}function RE(i,e,t){return i|(t?Qr:Yr)<<BigInt(e)}const la=i=>(SE<<BigInt(i-1))-Qr,jn=i=>new Uint8Array(i),fh=i=>Uint8Array.from(i);function Wu(i,e,t){if(typeof i!="number"||i<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let s=jn(i),r=jn(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=jn())=>{r=a(fh([0]),l),s=a(),l.length!==0&&(r=a(fh([1]),l),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const u=[];for(;l<e;){s=a();const p=s.slice();u.push(p),l+=s.length}return Hs(...u)};return(l,u)=>{o(),c(l);let p;for(;!(p=u(h()));)c();return o(),p}}const NE={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||hi(i),isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function fs(i,e,t={}){const s=(r,n,o)=>{const a=NE[n];if(typeof a!="function")throw new Error("invalid validator function");const c=i[r];if(!(o&&c===void 0)&&!a(c,i))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))s(r,n,!1);for(const[r,n]of Object.entries(t))s(r,n,!0);return i}const TE=()=>{throw new Error("not implemented")};function qo(i){const e=new WeakMap;return(t,...s)=>{const r=e.get(t);if(r!==void 0)return r;const n=i(t,...s);return e.set(t,n),n}}var CE=Object.freeze({__proto__:null,isBytes:hi,abytes:ir,abool:rs,bytesToHex:ns,numberToHexUnpadded:Di,hexToNumber:ha,hexToBytes:os,bytesToNumberBE:si,bytesToNumberLE:zs,numberToBytesBE:as,numberToBytesLE:Xr,numberToVarBytesBE:PE,ensureBytes:We,concatBytes:Hs,equalBytes:_E,utf8ToBytes:OE,inRange:en,aInRange:Ct,bitLen:Gu,bitGet:AE,bitSet:RE,bitMask:la,createHmacDrbg:Wu,validateObject:fs,notImplemented:TE,memoized:qo});const Pe=BigInt(0),ge=BigInt(1),Jt=BigInt(2),BE=BigInt(3),ko=BigInt(4),gh=BigInt(5),yh=BigInt(8);function Fe(i,e){const t=i%e;return t>=Pe?t:e+t}function Zu(i,e,t){if(e<Pe)throw new Error("invalid exponent, negatives unsupported");if(t<=Pe)throw new Error("invalid modulus");if(t===ge)return Pe;let s=ge;for(;e>Pe;)e&ge&&(s=s*i%t),i=i*i%t,e>>=ge;return s}function lt(i,e,t){let s=i;for(;e-- >Pe;)s*=s,s%=t;return s}function Lo(i,e){if(i===Pe)throw new Error("invert: expected non-zero number");if(e<=Pe)throw new Error("invert: expected positive modulus, got "+e);let t=Fe(i,e),s=e,r=Pe,n=ge;for(;t!==Pe;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==ge)throw new Error("invert: does not exist");return Fe(r,e)}function UE(i){const e=(i-ge)/Jt;let t,s,r;for(t=i-ge,s=0;t%Jt===Pe;t/=Jt,s++);for(r=Jt;r<i&&Zu(r,e,i)!==i-ge;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+ge)/ko;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(t+ge)/Jt;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=s,h=o.pow(o.mul(o.ONE,r),t),l=o.pow(a,n),u=o.pow(a,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let p=1;for(let w=o.sqr(u);p<c&&!o.eql(w,o.ONE);p++)w=o.sqr(w);const g=o.pow(h,ge<<BigInt(c-p-1));h=o.sqr(g),l=o.mul(l,g),u=o.mul(u,h),c=p}return l}}function jE(i){if(i%ko===BE){const e=(i+ge)/ko;return function(t,s){const r=t.pow(s,e);if(!t.eql(t.sqr(r),s))throw new Error("Cannot find square root");return r}}if(i%yh===gh){const e=(i-gh)/yh;return function(t,s){const r=t.mul(s,Jt),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,Jt),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),s))throw new Error("Cannot find square root");return c}}return UE(i)}const qE=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function kE(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=qE.reduce((s,r)=>(s[r]="function",s),e);return fs(i,t)}function LE(i,e,t){if(t<Pe)throw new Error("invalid exponent, negatives unsupported");if(t===Pe)return i.ONE;if(t===ge)return e;let s=i.ONE,r=e;for(;t>Pe;)t&ge&&(s=i.mul(s,r)),r=i.sqr(r),t>>=ge;return s}function DE(i,e){const t=new Array(e.length),s=e.reduce((n,o,a)=>i.is0(o)?n:(t[a]=n,i.mul(n,o)),i.ONE),r=i.inv(s);return e.reduceRight((n,o,a)=>i.is0(o)?n:(t[a]=i.mul(n,t[a]),i.mul(n,o)),r),t}function Ju(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function Yu(i,e,t=!1,s={}){if(i<=Pe)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=Ju(i,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:i,isLE:t,BITS:r,BYTES:n,MASK:la(r),ZERO:Pe,ONE:ge,create:c=>Fe(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Pe<=c&&c<i},is0:c=>c===Pe,isOdd:c=>(c&ge)===ge,neg:c=>Fe(-c,i),eql:(c,h)=>c===h,sqr:c=>Fe(c*c,i),add:(c,h)=>Fe(c+h,i),sub:(c,h)=>Fe(c-h,i),mul:(c,h)=>Fe(c*h,i),pow:(c,h)=>LE(a,c,h),div:(c,h)=>Fe(c*Lo(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>Lo(c,i),sqrt:s.sqrt||(c=>(o||(o=jE(i)),o(a,c))),invertBatch:c=>DE(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?Xr(c,n):as(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?zs(c):si(c)}});return Object.freeze(a)}function Qu(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function Xu(i){const e=Qu(i);return e+Math.ceil(e/2)}function FE(i,e,t=!1){const s=i.length,r=Qu(e),n=Xu(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?zs(i):si(i),a=Fe(o,e-ge)+ge;return t?Xr(a,r):as(a,r)}const wh=BigInt(0),fr=BigInt(1);function qn(i,e){const t=e.negate();return i?t:e}function ed(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function kn(i,e){ed(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function ME(i,e){if(!Array.isArray(i))throw new Error("array expected");i.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function zE(i,e){if(!Array.isArray(i))throw new Error("array of scalars expected");i.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}const Ln=new WeakMap,td=new WeakMap;function Dn(i){return td.get(i)||1}function HE(i,e){return{constTimeNegate:qn,hasPrecomputes(t){return Dn(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>wh;)s&fr&&(r=r.add(n)),n=n.double(),s>>=fr;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=kn(s,e),o=[];let a=t,c=a;for(let h=0;h<r;h++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,s,r){const{windows:n,windowSize:o}=kn(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),l=2**t,u=BigInt(t);for(let p=0;p<n;p++){const g=p*o;let w=Number(r&h);r>>=u,w>o&&(w-=l,r+=fr);const y=g,d=g+Math.abs(w)-1,m=p%2!==0,f=w<0;w===0?c=c.add(qn(m,s[y])):a=a.add(qn(f,s[d]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=kn(t,e),c=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let u=0;u<o;u++){const p=u*a;if(r===wh)break;let g=Number(r&c);if(r>>=l,g>a&&(g-=h,r+=fr),g===0)continue;let w=s[p+Math.abs(g)-1];g<0&&(w=w.negate()),n=n.add(w)}return n},getPrecomputes(t,s,r){let n=Ln.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&Ln.set(s,r(n))),n},wNAFCached(t,s,r){const n=Dn(t);return this.wNAF(n,this.getPrecomputes(n,t,r),s)},wNAFCachedUnsafe(t,s,r,n){const o=Dn(t);return o===1?this.unsafeLadder(t,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,r),s,n)},setWindowSize(t,s){ed(s,e),td.set(t,s),Ln.delete(t)}}}function VE(i,e,t,s){if(ME(t,i),zE(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=Gu(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r),h=Math.floor((e.BITS-1)/o)*o;let l=r;for(let u=h;u>=0;u-=o){c.fill(r);for(let g=0;g<s.length;g++){const w=s[g],y=Number(w>>BigInt(u)&BigInt(a));c[y]=c[y].add(t[g])}let p=r;for(let g=c.length-1,w=r;g>0;g--)w=w.add(c[g]),p=p.add(w);if(l=l.add(p),u!==0)for(let g=0;g<o;g++)l=l.double()}return l}function id(i){return kE(i.Fp),fs(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ju(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const $i=BigInt(0),Fn=BigInt(1);function KE(i){return fs(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function GE(i){const e=KE(i),{P:t}=e,s=f=>Fe(f,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(f=>f),c=e.powPminus2||(f=>Zu(f,t-BigInt(2),t));function h(f,E,_){const C=s(f*(E-_));return E=s(E-C),_=s(_+C),[E,_]}const l=(e.a-BigInt(2))/BigInt(4);function u(f,E){Ct("u",f,$i,t),Ct("scalar",E,$i,t);const _=E,C=f;let O=Fn,P=$i,R=f,S=Fn,U=$i,N;for(let j=BigInt(r-1);j>=$i;j--){const b=_>>j&Fn;U^=b,N=h(U,O,R),O=N[0],R=N[1],N=h(U,P,S),P=N[0],S=N[1],U=b;const I=O+P,$=s(I*I),A=O-P,T=s(A*A),x=$-T,q=R+S,k=R-S,L=s(k*I),M=s(q*A),F=L+M,H=L-M;R=s(F*F),S=s(C*s(H*H)),O=s($*T),P=s(x*($+s(l*x)))}N=h(U,O,R),O=N[0],R=N[1],N=h(U,P,S),P=N[0],S=N[1];const B=c(P);return s(O*B)}function p(f){return Xr(s(f),n)}function g(f){const E=We("u coordinate",f,n);return o===32&&(E[31]&=127),zs(E)}function w(f){const E=We("scalar",f),_=E.length;if(_!==n&&_!==o){let C=""+n+" or "+o;throw new Error("invalid scalar, expected "+C+" bytes, got "+_)}return zs(a(E))}function y(f,E){const _=g(E),C=w(f),O=u(_,C);if(O===$i)throw new Error("invalid private or public key received");return p(O)}const d=p(e.Gu);function m(f){return y(f,d)}return{scalarMult:y,scalarMultBase:m,getSharedSecret:(f,E)=>y(f,E),getPublicKey:f=>m(f),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:d}}const Do=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const WE=BigInt(1),mh=BigInt(2),ZE=BigInt(3),JE=BigInt(5);BigInt(8);function YE(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=Do,o=i*i%n*i%n,a=lt(o,mh,n)*o%n,c=lt(a,WE,n)*i%n,h=lt(c,JE,n)*c%n,l=lt(h,e,n)*h%n,u=lt(l,t,n)*l%n,p=lt(u,s,n)*u%n,g=lt(p,r,n)*p%n,w=lt(g,r,n)*p%n,y=lt(w,e,n)*h%n;return{pow_p_5_8:lt(y,mh,n)*i%n,b2:o}}function QE(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}GE({P:Do,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=Do,{pow_p_5_8:t,b2:s}=YE(i);return Fe(lt(t,ZE,e)*s,e)},adjustScalarBytes:QE,randomBytes:Uu});function bh(i){i.lowS!==void 0&&rs("lowS",i.lowS),i.prehash!==void 0&&rs("prehash",i.prehash)}function XE(i){const e=id(i);fs(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:s,a:r}=e;if(t){if(!s.eql(r,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:e2,hexToBytes:t2}=CE;class i2 extends Error{constructor(e=""){super(e)}}const _t={Err:i2,_tlv:{encode:(i,e)=>{const{Err:t}=_t;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const s=e.length/2,r=Di(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?Di(r.length/2|128):"";return Di(i)+n+r+e},decode(i,e){const{Err:t}=_t;let s=0;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==i)throw new t("tlv.decode: wrong tlv");const r=e[s++],n=!!(r&128);let o=0;if(!n)o=r;else{const c=r&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const h=e.subarray(s,s+c);if(h.length!==c)throw new t("tlv.decode: length bytes not complete");if(h[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const l of h)o=o<<8|l;if(s+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(s,s+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(i){const{Err:e}=_t;if(i<Rt)throw new e("integer: negative integers are not allowed");let t=Di(i);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(i){const{Err:e}=_t;if(i[0]&128)throw new e("invalid signature integer: negative");if(i[0]===0&&!(i[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return e2(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=_t,r=typeof i=="string"?t2(i):i;ir(r);const{v:n,l:o}=s.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l}=s.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(h)}},hexFromSig(i){const{_tlv:e,_int:t}=_t,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},Rt=BigInt(0),Ee=BigInt(1);BigInt(2);const vh=BigInt(3);BigInt(4);function s2(i){const e=XE(i),{Fp:t}=e,s=Yu(e.n,e.nBitLength),r=e.toBytes||((y,d,m)=>{const f=d.toAffine();return Hs(Uint8Array.from([4]),t.toBytes(f.x),t.toBytes(f.y))}),n=e.fromBytes||(y=>{const d=y.subarray(1),m=t.fromBytes(d.subarray(0,t.BYTES)),f=t.fromBytes(d.subarray(t.BYTES,2*t.BYTES));return{x:m,y:f}});function o(y){const{a:d,b:m}=e,f=t.sqr(y),E=t.mul(f,y);return t.add(t.add(E,t.mul(y,d)),m)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return en(y,Ee,e.n)}function c(y){const{allowedPrivateKeyLengths:d,nByteLength:m,wrapPrivateKey:f,n:E}=e;if(d&&typeof y!="bigint"){if(hi(y)&&(y=ns(y)),typeof y!="string"||!d.includes(y.length))throw new Error("invalid private key");y=y.padStart(m*2,"0")}let _;try{_=typeof y=="bigint"?y:si(We("private key",y,m))}catch{throw new Error("invalid private key, expected hex or "+m+" bytes, got "+typeof y)}return f&&(_=Fe(_,E)),Ct("private key",_,Ee,E),_}function h(y){if(!(y instanceof p))throw new Error("ProjectivePoint expected")}const l=qo((y,d)=>{const{px:m,py:f,pz:E}=y;if(t.eql(E,t.ONE))return{x:m,y:f};const _=y.is0();d==null&&(d=_?t.ONE:t.inv(E));const C=t.mul(m,d),O=t.mul(f,d),P=t.mul(E,d);if(_)return{x:t.ZERO,y:t.ZERO};if(!t.eql(P,t.ONE))throw new Error("invZ was invalid");return{x:C,y:O}}),u=qo(y=>{if(y.is0()){if(e.allowInfinityPoint&&!t.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:d,y:m}=y.toAffine();if(!t.isValid(d)||!t.isValid(m))throw new Error("bad point: x or y not FE");const f=t.sqr(m),E=o(d);if(!t.eql(f,E))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class p{constructor(d,m,f){if(this.px=d,this.py=m,this.pz=f,d==null||!t.isValid(d))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(f==null||!t.isValid(f))throw new Error("z required");Object.freeze(this)}static fromAffine(d){const{x:m,y:f}=d||{};if(!d||!t.isValid(m)||!t.isValid(f))throw new Error("invalid affine point");if(d instanceof p)throw new Error("projective point not allowed");const E=_=>t.eql(_,t.ZERO);return E(m)&&E(f)?p.ZERO:new p(m,f,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){const m=t.invertBatch(d.map(f=>f.pz));return d.map((f,E)=>f.toAffine(m[E])).map(p.fromAffine)}static fromHex(d){const m=p.fromAffine(n(We("pointHex",d)));return m.assertValidity(),m}static fromPrivateKey(d){return p.BASE.multiply(c(d))}static msm(d,m){return VE(p,s,d,m)}_setWindowSize(d){w.setWindowSize(this,d)}assertValidity(){u(this)}hasEvenY(){const{y:d}=this.toAffine();if(t.isOdd)return!t.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){h(d);const{px:m,py:f,pz:E}=this,{px:_,py:C,pz:O}=d,P=t.eql(t.mul(m,O),t.mul(_,E)),R=t.eql(t.mul(f,O),t.mul(C,E));return P&&R}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:d,b:m}=e,f=t.mul(m,vh),{px:E,py:_,pz:C}=this;let O=t.ZERO,P=t.ZERO,R=t.ZERO,S=t.mul(E,E),U=t.mul(_,_),N=t.mul(C,C),B=t.mul(E,_);return B=t.add(B,B),R=t.mul(E,C),R=t.add(R,R),O=t.mul(d,R),P=t.mul(f,N),P=t.add(O,P),O=t.sub(U,P),P=t.add(U,P),P=t.mul(O,P),O=t.mul(B,O),R=t.mul(f,R),N=t.mul(d,N),B=t.sub(S,N),B=t.mul(d,B),B=t.add(B,R),R=t.add(S,S),S=t.add(R,S),S=t.add(S,N),S=t.mul(S,B),P=t.add(P,S),N=t.mul(_,C),N=t.add(N,N),S=t.mul(N,B),O=t.sub(O,S),R=t.mul(N,U),R=t.add(R,R),R=t.add(R,R),new p(O,P,R)}add(d){h(d);const{px:m,py:f,pz:E}=this,{px:_,py:C,pz:O}=d;let P=t.ZERO,R=t.ZERO,S=t.ZERO;const U=e.a,N=t.mul(e.b,vh);let B=t.mul(m,_),j=t.mul(f,C),b=t.mul(E,O),I=t.add(m,f),$=t.add(_,C);I=t.mul(I,$),$=t.add(B,j),I=t.sub(I,$),$=t.add(m,E);let A=t.add(_,O);return $=t.mul($,A),A=t.add(B,b),$=t.sub($,A),A=t.add(f,E),P=t.add(C,O),A=t.mul(A,P),P=t.add(j,b),A=t.sub(A,P),S=t.mul(U,$),P=t.mul(N,b),S=t.add(P,S),P=t.sub(j,S),S=t.add(j,S),R=t.mul(P,S),j=t.add(B,B),j=t.add(j,B),b=t.mul(U,b),$=t.mul(N,$),j=t.add(j,b),b=t.sub(B,b),b=t.mul(U,b),$=t.add($,b),B=t.mul(j,$),R=t.add(R,B),B=t.mul(A,$),P=t.mul(I,P),P=t.sub(P,B),B=t.mul(I,j),S=t.mul(A,S),S=t.add(S,B),new p(P,R,S)}subtract(d){return this.add(d.negate())}is0(){return this.equals(p.ZERO)}wNAF(d){return w.wNAFCached(this,d,p.normalizeZ)}multiplyUnsafe(d){const{endo:m,n:f}=e;Ct("scalar",d,Rt,f);const E=p.ZERO;if(d===Rt)return E;if(this.is0()||d===Ee)return this;if(!m||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,d,p.normalizeZ);let{k1neg:_,k1:C,k2neg:O,k2:P}=m.splitScalar(d),R=E,S=E,U=this;for(;C>Rt||P>Rt;)C&Ee&&(R=R.add(U)),P&Ee&&(S=S.add(U)),U=U.double(),C>>=Ee,P>>=Ee;return _&&(R=R.negate()),O&&(S=S.negate()),S=new p(t.mul(S.px,m.beta),S.py,S.pz),R.add(S)}multiply(d){const{endo:m,n:f}=e;Ct("scalar",d,Ee,f);let E,_;if(m){const{k1neg:C,k1:O,k2neg:P,k2:R}=m.splitScalar(d);let{p:S,f:U}=this.wNAF(O),{p:N,f:B}=this.wNAF(R);S=w.constTimeNegate(C,S),N=w.constTimeNegate(P,N),N=new p(t.mul(N.px,m.beta),N.py,N.pz),E=S.add(N),_=U.add(B)}else{const{p:C,f:O}=this.wNAF(d);E=C,_=O}return p.normalizeZ([E,_])[0]}multiplyAndAddUnsafe(d,m,f){const E=p.BASE,_=(O,P)=>P===Rt||P===Ee||!O.equals(E)?O.multiplyUnsafe(P):O.multiply(P),C=_(this,m).add(_(d,f));return C.is0()?void 0:C}toAffine(d){return l(this,d)}isTorsionFree(){const{h:d,isTorsionFree:m}=e;if(d===Ee)return!0;if(m)return m(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:d,clearCofactor:m}=e;return d===Ee?this:m?m(p,this):this.multiplyUnsafe(e.h)}toRawBytes(d=!0){return rs("isCompressed",d),this.assertValidity(),r(p,this,d)}toHex(d=!0){return rs("isCompressed",d),ns(this.toRawBytes(d))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const g=e.nBitLength,w=HE(p,e.endo?Math.ceil(g/2):g);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function r2(i){const e=id(i);return fs(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function n2(i){const e=r2(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(b){return Fe(b,s)}function a(b){return Lo(b,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=s2({...e,toBytes(b,I,$){const A=I.toAffine(),T=t.toBytes(A.x),x=Hs;return rs("isCompressed",$),$?x(Uint8Array.from([I.hasEvenY()?2:3]),T):x(Uint8Array.from([4]),T,t.toBytes(A.y))},fromBytes(b){const I=b.length,$=b[0],A=b.subarray(1);if(I===r&&($===2||$===3)){const T=si(A);if(!en(T,Ee,t.ORDER))throw new Error("Point is not on curve");const x=l(T);let q;try{q=t.sqrt(x)}catch(L){const M=L instanceof Error?": "+L.message:"";throw new Error("Point is not on curve"+M)}const k=(q&Ee)===Ee;return($&1)===1!==k&&(q=t.neg(q)),{x:T,y:q}}else if(I===n&&$===4){const T=t.fromBytes(A.subarray(0,t.BYTES)),x=t.fromBytes(A.subarray(t.BYTES,2*t.BYTES));return{x:T,y:x}}else{const T=r,x=n;throw new Error("invalid Point, expected length of "+T+", or uncompressed "+x+", got "+I)}}}),p=b=>ns(as(b,e.nByteLength));function g(b){const I=s>>Ee;return b>I}function w(b){return g(b)?o(-b):b}const y=(b,I,$)=>si(b.slice(I,$));class d{constructor(I,$,A){this.r=I,this.s=$,this.recovery=A,this.assertValidity()}static fromCompact(I){const $=e.nByteLength;return I=We("compactSignature",I,$*2),new d(y(I,0,$),y(I,$,2*$))}static fromDER(I){const{r:$,s:A}=_t.toSig(We("DER",I));return new d($,A)}assertValidity(){Ct("r",this.r,Ee,s),Ct("s",this.s,Ee,s)}addRecoveryBit(I){return new d(this.r,this.s,I)}recoverPublicKey(I){const{r:$,s:A,recovery:T}=this,x=O(We("msgHash",I));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");const q=T===2||T===3?$+e.n:$;if(q>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const k=(T&1)===0?"02":"03",L=c.fromHex(k+p(q)),M=a(q),F=o(-x*M),H=o(A*M),K=c.BASE.multiplyAndAddUnsafe(L,F,H);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new d(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return os(this.toDERHex())}toDERHex(){return _t.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return os(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const m={isValidPrivateKey(b){try{return h(b),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const b=Xu(e.n);return FE(e.randomBytes(b),e.n)},precompute(b=8,I=c.BASE){return I._setWindowSize(b),I.multiply(BigInt(3)),I}};function f(b,I=!0){return c.fromPrivateKey(b).toRawBytes(I)}function E(b){const I=hi(b),$=typeof b=="string",A=(I||$)&&b.length;return I?A===r||A===n:$?A===2*r||A===2*n:b instanceof c}function _(b,I,$=!0){if(E(b))throw new Error("first arg must be private key");if(!E(I))throw new Error("second arg must be public key");return c.fromHex(I).multiply(h(b)).toRawBytes($)}const C=e.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const I=si(b),$=b.length*8-e.nBitLength;return $>0?I>>BigInt($):I},O=e.bits2int_modN||function(b){return o(C(b))},P=la(e.nBitLength);function R(b){return Ct("num < 2^"+e.nBitLength,b,Rt,P),as(b,e.nByteLength)}function S(b,I,$=U){if(["recovered","canonical"].some(G=>G in $))throw new Error("sign() legacy options not supported");const{hash:A,randomBytes:T}=e;let{lowS:x,prehash:q,extraEntropy:k}=$;x==null&&(x=!0),b=We("msgHash",b),bh($),q&&(b=We("prehashed msgHash",A(b)));const L=O(b),M=h(I),F=[R(M),R(L)];if(k!=null&&k!==!1){const G=k===!0?T(t.BYTES):k;F.push(We("extraEntropy",G))}const H=Hs(...F),K=L;function Z(G){const W=C(G);if(!u(W))return;const Be=a(W),ue=c.BASE.multiply(W).toAffine(),ae=o(ue.x);if(ae===Rt)return;const he=o(Be*o(K+ae*M));if(he===Rt)return;let Xe=(ue.x===ae?0:2)|Number(ue.y&Ee),dt=he;return x&&g(he)&&(dt=w(he),Xe^=1),new d(ae,dt,Xe)}return{seed:H,k2sig:Z}}const U={lowS:e.lowS,prehash:!1},N={lowS:e.lowS,prehash:!1};function B(b,I,$=U){const{seed:A,k2sig:T}=S(b,I,$),x=e;return Wu(x.hash.outputLen,x.nByteLength,x.hmac)(A,T)}c.BASE._setWindowSize(8);function j(b,I,$,A=N){const T=b;I=We("msgHash",I),$=We("publicKey",$);const{lowS:x,prehash:q,format:k}=A;if(bh(A),"strict"in A)throw new Error("options.strict was renamed to lowS");if(k!==void 0&&k!=="compact"&&k!=="der")throw new Error("format must be compact or der");const L=typeof T=="string"||hi(T),M=!L&&!k&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!L&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,H;try{if(M&&(F=new d(T.r,T.s)),L){try{k!=="compact"&&(F=d.fromDER(T))}catch(he){if(!(he instanceof _t.Err))throw he}!F&&k!=="der"&&(F=d.fromCompact(T))}H=c.fromHex($)}catch{return!1}if(!F||x&&F.hasHighS())return!1;q&&(I=e.hash(I));const{r:K,s:Z}=F,G=O(I),W=a(Z),Be=o(G*W),ue=o(K*W),ae=c.BASE.multiplyAndAddUnsafe(H,Be,ue)?.toAffine();return ae?o(ae.x)===K:!1}return{CURVE:e,getPublicKey:f,getSharedSecret:_,sign:B,verify:j,ProjectivePoint:c,Signature:d,utils:m}}function o2(i){return{hash:i,hmac:(e,...t)=>Ku(i,e,fv(...t)),randomBytes:Uu}}function a2(i,e){const t=s=>n2({...i,...o2(s)});return{...t(e),create:t}}const sd=Yu(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),c2=sd.create(BigInt("-3")),h2=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");a2({a:c2,b:h2,Fp:sd,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},ca);const Fo="base16",gr="base64pad",Ss="base64url",l2="utf8",Mn=1,u2=2;function zn(i){const e=ca(v.fromString(i,Fo));return v.toString(e,Fo)}function Ii(i){const e=ca(v.fromString(i,l2));return v.toString(e,Fo)}function yr(i,e,t){return`${i}?wc_ev=${t}&topic=${e}`}var d2=Object.defineProperty,p2=Object.defineProperties,f2=Object.getOwnPropertyDescriptors,Eh=Object.getOwnPropertySymbols,g2=Object.prototype.hasOwnProperty,y2=Object.prototype.propertyIsEnumerable,$h=(i,e,t)=>e in i?d2(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,w2=(i,e)=>{for(var t in e||(e={}))g2.call(e,t)&&$h(i,t,e[t]);if(Eh)for(var t of Eh(e))y2.call(e,t)&&$h(i,t,e[t]);return i},m2=(i,e)=>p2(i,f2(e));function gs(i){const e=[];return i.forEach(t=>{const[s,r]=t.split(":");e.push(`${s}:${r}`)}),e}function b2(i){const e=[];return Object.values(i).forEach(t=>{e.push(...gs(t.accounts))}),e}function v2(i,e){const t=[];return Object.values(i).forEach(s=>{gs(s.accounts).includes(e)&&t.push(...s.methods)}),t}function E2(i,e){const t=[];return Object.values(i).forEach(s=>{gs(s.accounts).includes(e)&&t.push(...s.events)}),t}function rd(i){return i.includes(":")}function $2(i){return rd(i)?i.split(":")[0]:i}function Ih(i){var e,t,s;const r={};if(!Vs(i))return r;for(const[n,o]of Object.entries(i)){const a=rd(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],l=$2(n);r[l]=m2(w2({},r[l]),{chains:ii(a,(e=r[l])==null?void 0:e.chains),methods:ii(c,(t=r[l])==null?void 0:t.methods),events:ii(h,(s=r[l])==null?void 0:s.events)})}return r}function I2(i){const e={};return i?.forEach(t=>{var s;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(s=e[r].chains)==null||s.push(`${r}:${n}`)}),e}function Sh(i,e){e=e.map(s=>s.replace("did:pkh:",""));const t=I2(e);for(const[s,r]of Object.entries(t))r.methods?r.methods=ii(r.methods,i):r.methods=i,r.events=["chainChanged","accountsChanged"];return t}function S2(i,e){var t,s,r,n,o,a;const c=Ih(i),h=Ih(e),l={},u=Object.keys(c).concat(Object.keys(h));for(const p of u)l[p]={chains:ii((t=c[p])==null?void 0:t.chains,(s=h[p])==null?void 0:s.chains),methods:ii((r=c[p])==null?void 0:r.methods,(n=h[p])==null?void 0:n.methods),events:ii((o=c[p])==null?void 0:o.events,(a=h[p])==null?void 0:a.events)};return l}const x2={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}},P2={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 V(i,e){const{message:t,code:s}=P2[i];return{message:e?`${t} ${e}`:t,code:s}}function de(i,e){const{message:t,code:s}=x2[i];return{message:e?`${t} ${e}`:t,code:s}}function sr(i,e){return!!Array.isArray(i)}function Vs(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}function Me(i){return typeof i>"u"}function $e(i,e){return e&&Me(i)?!0:typeof i=="string"&&!!i.trim().length}function ua(i,e){return e&&Me(i)?!0:typeof i=="number"&&!isNaN(i)}function _2(i,e){const{requiredNamespaces:t}=e,s=Object.keys(i.namespaces),r=Object.keys(t);let n=!0;return Qt(r,s)?(s.forEach(o=>{const{accounts:a,methods:c,events:h}=i.namespaces[o],l=gs(a),u=t[o];(!Qt(Au(o,u),l)||!Qt(u.methods,c)||!Qt(u.events,h))&&(n=!1)}),n):!1}function Cr(i){return $e(i,!1)&&i.includes(":")?i.split(":").length===2:!1}function O2(i){if($e(i,!1)&&i.includes(":")){const e=i.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Cr(t)}}return!1}function A2(i,e){let t=null;return $e(i?.publicKey,!1)||(t=V("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function xh(i){let e=!0;return sr(i)?i.length&&(e=i.every(t=>$e(t,!1))):e=!1,e}function R2(i,e,t){let s=null;return sr(e)&&e.length?e.forEach(r=>{s||Cr(r)||(s=de("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Cr(i)||(s=de("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"] }`)),s}function N2(i,e,t){let s=null;return Object.entries(i).forEach(([r,n])=>{if(s)return;const o=R2(r,Au(r,n),`${e} ${t}`);o&&(s=o)}),s}function T2(i,e){let t=null;return sr(i)?i.forEach(s=>{t||O2(s)||(t=de("UNSUPPORTED_ACCOUNTS",`${e}, account ${s} should be a string and conform to "namespace:chainId:address" format`))}):t=de("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function C2(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=T2(s?.accounts,`${e} namespace`);r&&(t=r)}),t}function B2(i,e){let t=null;return xh(i?.methods)?xh(i?.events)||(t=de("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=de("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function nd(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=B2(s,`${e}, namespace`);r&&(t=r)}),t}function U2(i,e,t){let s=null;if(i&&Vs(i)){const r=nd(i,e);r&&(s=r);const n=N2(i,e,t);n&&(s=n)}else s=V("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return s}function Hn(i,e){let t=null;if(i&&Vs(i)){const s=nd(i,e);s&&(t=s);const r=C2(i,e);r&&(t=r)}else t=V("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function od(i){return $e(i.protocol,!0)}function j2(i,e){let t=!1;return i?i&&sr(i)&&i.length&&i.forEach(s=>{t=od(s)}):t=!0,t}function q2(i){return typeof i=="number"}function at(i){return typeof i<"u"&&typeof i!==null}function k2(i){return!(!i||typeof i!="object"||!i.code||!ua(i.code,!1)||!i.message||!$e(i.message,!1))}function L2(i){return!(Me(i)||!$e(i.method,!1))}function D2(i){return!(Me(i)||Me(i.result)&&Me(i.error)||!ua(i.id,!1)||!$e(i.jsonrpc,!1))}function F2(i){return!(Me(i)||!$e(i.name,!1))}function Ph(i,e){return!(!Cr(e)||!b2(i).includes(e))}function M2(i,e,t){return $e(t,!1)?v2(i,e).includes(t):!1}function z2(i,e,t){return $e(t,!1)?E2(i,e).includes(t):!1}function _h(i,e,t){let s=null;const r=H2(i),n=V2(e),o=Object.keys(r),a=Object.keys(n),c=Oh(Object.keys(i)),h=Oh(Object.keys(e)),l=c.filter(u=>!h.includes(u));return l.length&&(s=V("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
@@ -8,4 +8,4 @@ ${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+z.Buffer.from(Sv(t)).toS
8
8
  Required: ${o.toString()}
9
9
  Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||s)return;const p=gs(e[u].accounts);p.includes(u)||(s=V("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${u}
10
10
  Required: ${u}
11
- Approved: ${p.toString()}`))}),o.forEach(u=>{s||(Qt(r[u].methods,n[u].methods)?Qt(r[u].events,n[u].events)||(s=V("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):s=V("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),s}function H2(i){const e={};return Object.keys(i).forEach(t=>{var s;t.includes(":")?e[t]=i[t]:(s=i[t].chains)==null||s.forEach(r=>{e[r]={methods:i[t].methods,events:i[t].events}})}),e}function Oh(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function V2(i){const e={};return Object.keys(i).forEach(t=>{t.includes(":")?e[t]=i[t]:gs(i[t].accounts)?.forEach(r=>{e[r]={accounts:i[t].accounts.filter(n=>n.includes(`${r}:`)),methods:i[t].methods,events:i[t].events}})}),e}function K2(i,e){return ua(i,!1)&&i<=e.max&&i>=e.min}const Vn={};class xs{static get(e){return Vn[e]}static set(e,t){Vn[e]=t}static delete(e){delete Vn[e]}}const ad="wc",cd=2,hd="client",da=`${ad}@${cd}:${hd}:`,Kn={name:hd,logger:"error"},Ah="WALLETCONNECT_DEEPLINK_CHOICE",G2="proposal",Rh="Proposal expired",W2="session",Si=v.cjsExports$1.SEVEN_DAYS,Z2="engine",me={wc_sessionPropose:{req:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1104},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1106},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1112},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1114},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:v.cjsExports$1.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:v.cjsExports$1.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1119}}},Gn={min:v.cjsExports$1.FIVE_MINUTES,max:v.cjsExports$1.SEVEN_DAYS},wt={idle:"IDLE",active:"ACTIVE"},Nh={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},J2="request",Y2=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Q2="wc",X2="auth",e$="authKeys",t$="pairingTopics",i$="requests",tn=`${Q2}@${1.5}:${X2}:`,Pr=`${tn}:PUB_KEY`;var s$=Object.defineProperty,r$=Object.defineProperties,n$=Object.getOwnPropertyDescriptors,Th=Object.getOwnPropertySymbols,o$=Object.prototype.hasOwnProperty,a$=Object.prototype.propertyIsEnumerable,Mo=(i,e,t)=>e in i?s$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oe=(i,e)=>{for(var t in e||(e={}))o$.call(e,t)&&Mo(i,t,e[t]);if(Th)for(var t of Th(e))a$.call(e,t)&&Mo(i,t,e[t]);return i},Ue=(i,e)=>r$(i,n$(e)),D=(i,e,t)=>Mo(i,typeof e!="symbol"?e+"":e,t);class c$ extends Cf{constructor(e){super(e),D(this,"name",Z2),D(this,"events",new v.Nt),D(this,"initialized",!1),D(this,"requestQueue",{state:wt.idle,queue:[]}),D(this,"sessionRequestQueue",{state:wt.idle,queue:[]}),D(this,"requestQueueDelay",v.cjsExports$1.ONE_SECOND),D(this,"expectedPairingMethodMap",new Map),D(this,"recentlyDeletedMap",new Map),D(this,"recentlyDeletedLimit",200),D(this,"relayMessageCache",[]),D(this,"pendingSessions",new Map),D(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(me)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},v.cjsExports$1.toMiliseconds(this.requestQueueDelay)))}),D(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=Ue(oe({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=S2(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h}=s;let l=r,u,p=!1;try{if(l){const O=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),p=O.active}}catch(O){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),O}if(!l||!p){const{topic:O,uri:P}=await this.client.core.pairing.create();l=O,u=P}if(!l){const{message:O}=V("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(O)}const g=await this.client.core.crypto.generateKeyPair(),w=me.wc_sessionPropose.req.ttl||v.cjsExports$1.FIVE_MINUTES,y=ke(w),d=Ue(oe(oe({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:tu}],proposer:{publicKey:g,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:v.payloadId()}),m=ne("session_connect",d.id),{reject:f,resolve:E,done:_}=bi(w,Rh),C=({id:O})=>{O===d.id&&(this.client.events.off("proposal_expire",C),this.pendingSessions.delete(d.id),this.events.emit(m,{error:{message:Rh,code:0}}))};return this.client.events.on("proposal_expire",C),this.events.once(m,({error:O,session:P})=>{this.client.events.off("proposal_expire",C),O?f(O):P&&E(P)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:d,throwOnFailedPublish:!0,clientRpcId:d.id}),await this.setProposal(d.id,d),{uri:u,approval:_}}),D(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(s){throw this.client.logger.error("pair() failed"),s}}),D(this,"approve",async t=>{var s,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(s=t?.id)==null?void 0:s.toString(),trace:[nt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(S){throw o.setError(Ht.no_internet_connection),S}try{await this.isValidProposalId(t?.id)}catch(S){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),o.setError(Ht.proposal_not_found),S}try{await this.isValidApprove(t)}catch(S){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Ht.session_approve_namespace_validation_failure),S}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=t,g=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:w,proposer:y,requiredNamespaces:d,optionalNamespaces:m}=g;let f=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:w});f||(f=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:nt.session_approve_started,properties:{topic:w,trace:[nt.session_approve_started,nt.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),_=y.publicKey,C=await this.client.core.crypto.generateSharedKey(E,_),O=oe(oe(oe({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:E,metadata:this.client.metadata},expiry:ke(Si)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),P=le.relay;f.addTrace(nt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(C,{transportType:P})}catch(S){throw f.setError(Ht.subscribe_session_topic_failure),S}f.addTrace(nt.subscribe_session_topic_success);const R=Ue(oe({},O),{topic:C,requiredNamespaces:d,optionalNamespaces:m,pairingTopic:w,acknowledged:!1,self:O.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:E,transportType:le.relay});await this.client.session.set(C,R),f.addTrace(nt.store_session);try{f.addTrace(nt.publishing_session_settle),await this.sendRequest({topic:C,method:"wc_sessionSettle",params:O,throwOnFailedPublish:!0}).catch(S=>{throw f?.setError(Ht.session_settle_publish_failure),S}),f.addTrace(nt.session_settle_publish_success),f.addTrace(nt.publishing_session_approve),await this.sendResult({id:a,topic:w,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(S=>{throw f?.setError(Ht.session_approve_publish_failure),S}),f.addTrace(nt.session_approve_publish_success)}catch(S){throw this.client.logger.error(S),this.client.session.delete(C,de("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(C),S}return this.client.core.eventClient.deleteEvent({eventId:f.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:y.metadata}),await this.client.proposal.delete(a,de("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(C,ke(Si)),{topic:C,acknowledged:()=>Promise.resolve(this.client.session.get(C))}}),D(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:s,reason:r}=t;let n;try{n=this.client.proposal.get(s).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${s}) failed`),o}n&&(await this.sendError({id:s,topic:n,error:r,rpcOpts:me.wc_sessionPropose.reject}),await this.client.proposal.delete(s,de("USER_DISCONNECTED")))}),D(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:s,namespaces:r}=t,{done:n,resolve:o,reject:a}=bi(),c=v.payloadId(),h=v.getBigIntRpcId().toString(),l=this.client.session.get(s).namespaces;return this.events.once(ne("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(s,{namespaces:r}),await this.sendRequest({topic:s,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(u=>{this.client.logger.error(u),this.client.session.update(s,{namespaces:l}),a(u)}),{acknowledged:n}}),D(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:s}=t,r=v.payloadId(),{done:n,resolve:o,reject:a}=bi();return this.events.once(ne("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,ke(Si)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),D(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:s,request:r,topic:n,expiry:o=me.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);a?.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const c=v.payloadId(),h=v.getBigIntRpcId().toString(),{done:l,resolve:u,reject:p}=bi(o,"Request expired. Please try again.");this.events.once(ne("session_request",c),({error:m,result:f})=>{m?p(m):u(f)});const g="wc_sessionRequest",w=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(w)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:{request:Ue(oe({},r),{expiryTimestamp:ke(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:w}).catch(m=>p(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const y={request:Ue(oe({},r),{expiryTimestamp:ke(o)}),chainId:s},d=this.shouldSetTVF(g,y);return await Promise.all([new Promise(async m=>{await this.sendRequest(oe({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:y,expiry:o,throwOnFailedPublish:!0},d&&{tvf:this.getTVFParams(c,y)})).catch(f=>p(f)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),m()}),new Promise(async m=>{var f;if(!((f=a.sessionConfig)!=null&&f.disableDeepLink)){const E=await Q0(this.client.core.storage,Ah);await Z0({id:c,topic:n,wcDeepLink:E})}m()}),l()]).then(m=>m[2])}),D(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:s,response:r}=t,{id:n}=r,o=this.client.session.get(s);o.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);v.isJsonRpcResult(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):v.isJsonRpcError(r)&&await this.sendError({id:n,topic:s,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),D(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:s}=t;if(this.client.session.keys.includes(s)){const r=v.payloadId(),n=v.getBigIntRpcId().toString(),{done:o,resolve:a,reject:c}=bi();this.events.once(ne("session_ping",r),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:s,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(s)&&(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:s}))}),D(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:s,event:r,chainId:n}=t,o=v.getBigIntRpcId().toString(),a=v.payloadId();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),D(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:s}=t;if(this.client.session.keys.includes(s))await this.sendRequest({topic:s,method:"wc_sessionDelete",params:de("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:s,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(s))await this.client.core.pairing.disconnect({topic:s});else{const{message:r}=V("MISMATCHED_TOPIC",`Session or pairing topic not found: ${s}`);throw new Error(r)}}),D(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(s=>_2(s,t)))),D(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),D(this,"authenticate",async(t,s)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=s&&this.client.core.linkModeSupportedApps.includes(s)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?le.link_mode:le.relay;o===le.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:p,exp:g,nbf:w,methods:y=[],expiry:d}=t,m=[...t.resources||[]],{topic:f,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:f,uri:E}});const _=await this.client.core.crypto.generateKeyPair(),C=zn(_);if(await Promise.all([this.client.auth.authKeys.set(Pr,{responseTopic:C,publicKey:_}),this.client.auth.pairingTopics.set(C,{topic:C,pairingTopic:f})]),await this.client.core.relayer.subscribe(C,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${f}`),y.length>0){const{namespace:x}=Sr(a[0]);let q=Hv(x,"request",y);xr(m)&&(q=Kv(q,m.pop())),m.push(q)}const O=d&&d>me.wc_sessionAuthenticate.req.ttl?d:me.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:p??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:g,nbf:w,resources:m},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:ke(O)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},S={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:f,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:ke(me.wc_sessionPropose.req.ttl),id:v.payloadId()},{done:U,resolve:N,reject:B}=bi(O,"Request expired"),j=v.payloadId(),b=ne("session_connect",S.id),I=ne("session_request",j),$=async({error:x,session:q})=>{this.events.off(I,A),x?B(x):q&&N({session:q})},A=async x=>{var q,k,L;if(await this.deletePendingAuthRequest(j,{message:"fulfilled",code:0}),x.error){const W=de("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return x.error.code===W.code?void 0:(this.events.off(b,$),B(x.error.message))}await this.deleteProposal(S.id),this.events.off(b,$);const{cacaos:M,responder:F}=x.result,H=[],K=[];for(const W of M){await sh({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(de("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Be}=W,ue=xr(Be.resources),ae=[Co(Be.iss)],he=Tr(Be.iss);if(ue){const Xe=rh(ue),dt=nh(ue);H.push(...Xe),ae.push(...dt)}for(const Xe of ae)K.push(`${Xe}:${he}`)}const Z=await this.client.core.crypto.generateSharedKey(_,F.publicKey);let G;H.length>0&&(G={topic:Z,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:F,controller:F.publicKey,expiry:ke(Si),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:f,namespaces:Sh([...new Set(H)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(Z,{transportType:o}),await this.client.session.set(Z,G),f&&await this.client.core.pairing.updateMetadata({topic:f,metadata:F.metadata}),G=this.client.session.get(Z)),(q=this.client.metadata.redirect)!=null&&q.linkMode&&(k=F.metadata.redirect)!=null&&k.linkMode&&(L=F.metadata.redirect)!=null&&L.universal&&s&&(this.client.core.addLinkModeSupportedApp(F.metadata.redirect.universal),this.client.session.update(Z,{transportType:le.link_mode})),N({auths:M,session:G})};this.events.once(b,$),this.events.once(I,A);let T;try{if(n){const x=v.formatJsonRpcRequest("wc_sessionAuthenticate",P,j);this.client.core.history.set(f,x);const q=await this.client.core.crypto.encode("",x,{type:u2,encoding:Ss});T=yr(s,f,q)}else await Promise.all([this.sendRequest({topic:f,method:"wc_sessionAuthenticate",params:P,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:j}),this.sendRequest({topic:f,method:"wc_sessionPropose",params:S,expiry:me.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:S.id})])}catch(x){throw this.events.off(b,$),this.events.off(I,A),x}return await this.setProposal(S.id,S),await this.setAuthRequest(j,{request:Ue(oe({},P),{verifyContext:{}}),pairingTopic:f,transportType:o}),{uri:T??E,response:U}}),D(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[Vt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(d){throw n.setError(bs.no_internet_connection),d}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(bs.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||le.relay;a===le.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=zn(c),u={type:Mn,receiverPublicKey:c,senderPublicKey:h},p=[],g=[];for(const d of r){if(!await sh({cacao:d,projectId:this.client.core.projectId})){n.setError(bs.invalid_cacao);const C=de("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:C,encodeOpts:u}),new Error(C.message)}n.addTrace(Vt.cacaos_verified);const{p:m}=d,f=xr(m.resources),E=[Co(m.iss)],_=Tr(m.iss);if(f){const C=rh(f),O=nh(f);p.push(...C),E.push(...O)}for(const C of E)g.push(`${C}:${_}`)}const w=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Vt.create_authenticated_session_topic);let y;if(p?.length>0){y={topic:w,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ke(Si),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Sh([...new Set(p)],[...new Set(g)]),transportType:a},n.addTrace(Vt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:a})}catch(d){throw n.setError(bs.subscribe_authenticated_session_topic_failure),d}n.addTrace(Vt.subscribe_authenticated_session_topic_success),await this.client.session.set(w,y),n.addTrace(Vt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Vt.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:s,result:{cacaos:r,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(d){throw n.setError(bs.authenticated_session_approve_publish_failure),d}return await this.client.auth.requests.delete(s,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:y}}),D(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:s,reason:r}=t,n=this.getPendingAuthRequest(s);if(!n)throw new Error(`Could not find pending auth request with id ${s}`);n.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=zn(o),h={type:Mn,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:s,topic:c,error:r,encodeOpts:h,rpcOpts:me.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(s,{message:"rejected",code:0}),await this.client.proposal.delete(s,de("USER_DISCONNECTED"))}),D(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return Du(s,r)}),D(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)}),D(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const s=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!==s.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(s){this.client.logger.error(s)}}),D(this,"deleteSession",async t=>{var s;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,de("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Ah).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,de("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=wt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),D(this,"deleteProposal",async(t,s)=>{if(s)try{const r=this.client.proposal.get(t);this.client.core.eventClient.getEvent({topic:r.pairingTopic})?.setError(Ht.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,de("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),D(this,"deletePendingSessionRequest",async(t,s,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,s),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=wt.idle,this.client.events.emit("session_request_expire",{id:t}))}),D(this,"deletePendingAuthRequest",async(t,s,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,s),r?Promise.resolve():this.client.core.expirer.del(t)])}),D(this,"setExpiry",async(t,s)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,s),await this.client.session.update(t,{expiry:s}))}),D(this,"setProposal",async(t,s)=>{this.client.core.expirer.set(t,ke(me.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),D(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=le.relay}=s;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})}),D(this,"setPendingSessionRequest",async t=>{const{id:s,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ke(me.wc_sessionRequest.req.ttl);this.client.core.expirer.set(s,a),await this.client.pendingRequest.set(s,{id:s,topic:r,params:n,verifyContext:o})}),D(this,"sendRequest",async t=>{const{topic:s,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:u}=t,p=v.formatJsonRpcRequest(r,n,c);let g;const w=!!l;try{const m=w?Ss:gr;g=await this.client.core.crypto.encode(s,p,{encoding:m})}catch(m){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),m}let y;if(Y2.includes(r)){const m=Ii(JSON.stringify(p)),f=Ii(g);y=await this.client.core.verify.register({id:f,decryptedId:m})}const d=me[r].req;if(d.attestation=y,o&&(d.ttl=o),a&&(d.id=a),this.client.core.history.set(s,p),w){const m=yr(l,s,g);await z.global.Linking.openURL(m,this.client.name)}else{const m=me[r].req;o&&(m.ttl=o),a&&(m.id=a),m.tvf=Ue(oe({},u),{correlationId:p.id}),h?(m.internal=Ue(oe({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,g,m)):this.client.core.relayer.publish(s,g,m).catch(f=>this.client.logger.error(f))}return p.id}),D(this,"sendResult",async t=>{const{id:s,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=v.formatJsonRpcResult(s,n);let l;const u=c&&typeof(z.global==null?void 0:z.global.Linking)<"u";try{const w=u?Ss:gr;l=await this.client.core.crypto.encode(r,h,Ue(oe({},a||{}),{encoding:w}))}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),w}let p,g;try{p=await this.client.core.history.get(r,s);const w=p.request;try{this.shouldSetTVF(w.method,w.params)&&(g=this.getTVFParams(s,w.params,n))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),w}if(u){const w=yr(c,r,l);await z.global.Linking.openURL(w,this.client.name)}else{const w=p.request.method,y=me[w].res;y.tvf=Ue(oe({},g),{correlationId:s}),o?(y.internal=Ue(oe({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,y)):this.client.core.relayer.publish(r,l,y).catch(d=>this.client.logger.error(d))}await this.client.core.history.resolve(h)}),D(this,"sendError",async t=>{const{id:s,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=v.formatJsonRpcError(s,n);let l;const u=c&&typeof(z.global==null?void 0:z.global.Linking)<"u";try{const g=u?Ss:gr;l=await this.client.core.crypto.encode(r,h,Ue(oe({},o||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),g}let p;try{p=await this.client.core.history.get(r,s)}catch(g){throw this.client.logger.error(`sendError() -> history.get(${r}, ${s}) failed`),g}if(u){const g=yr(c,r,l);await z.global.Linking.openURL(g,this.client.name)}else{const g=p.request.method,w=a||me[g].res;this.client.core.relayer.publish(r,l,w)}await this.client.core.history.resolve(h)}),D(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;vi(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=>{vi(r.expiryTimestamp)&&s.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...s.map(r=>this.deleteProposal(r))])}),D(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),D(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),D(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===wt.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=wt.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=wt.idle}),D(this,"processRequest",async t=>{const{topic:s,payload:r,attestation:n,transportType:o,encryptedId:a}=t,c=r.method;if(!this.shouldIgnorePairingRequest({topic:s,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:s,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(s,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(s,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(s,r);case"wc_sessionPing":return await this.onSessionPingRequest(s,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(s,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:s,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(s,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:s,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),D(this,"onRelayEventResponse",async t=>{const{topic:s,payload:r,transportType:n}=t,o=(await this.client.core.history.get(s,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(s,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(s,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(s,r);case"wc_sessionExtend":return this.onSessionExtendResponse(s,r);case"wc_sessionPing":return this.onSessionPingResponse(s,r);case"wc_sessionRequest":return this.onSessionRequestResponse(s,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(s,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),D(this,"onRelayEventUnknownPayload",t=>{const{topic:s}=t,{message:r}=V("MISSING_OR_INVALID",`Decoded payload on topic ${s} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),D(this,"shouldIgnorePairingRequest",t=>{const{topic:s,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(s);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),D(this,"onSessionProposeRequest",async t=>{const{topic:s,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:c}=r;try{const h=this.client.core.eventClient.getEvent({topic:s});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),h?.setError(St.proposal_listener_not_found)),this.isValidConnect(oe({},r.params));const l=a.expiryTimestamp||ke(me.wc_sessionPropose.req.ttl),u=oe({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,u);const p=await this.getVerifyContext({attestationId:n,hash:Ii(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});h?.addTrace(mt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:p})}catch(h){await this.sendError({id:c,topic:s,error:h,rpcOpts:me.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),D(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(v.isJsonRpcResult(s)){const{result:o}=s;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(c,h);this.pendingSessions.set(n,{sessionTopic:l,pairingTopic:t,proposalId:n,publicKey:c});const u=await this.client.core.relayer.subscribe(l,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(v.isJsonRpcError(s)){await this.client.proposal.delete(n,de("USER_DISCONNECTED"));const o=ne("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:s.error})}}),D(this,"onSessionSettleRequest",async(t,s)=>{const{id:r,params:n}=s;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=s.params,g=[...this.pendingSessions.values()].find(d=>d.sessionTopic===t);if(!g)return this.client.logger.error(`Pending session not found for topic ${t}`);const w=this.client.proposal.get(g.proposalId),y=Ue(oe(oe(oe({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:g.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:g.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),{transportType:le.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:g.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(ne("session_connect",g.proposalId),{session:y}),this.pendingSessions.delete(g.proposalId),this.deleteProposal(g.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:s.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),D(this,"onSessionSettleResponse",async(t,s)=>{const{id:r}=s;v.isJsonRpcResult(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(ne("session_approve",r),{})):v.isJsonRpcError(s)&&(await this.client.session.delete(t,de("USER_DISCONNECTED")),this.events.emit(ne("session_approve",r),{error:s.error}))}),D(this,"onSessionUpdateRequest",async(t,s)=>{const{params:r,id:n}=s;try{const o=`${t}_session_update`,a=xs.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:de("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:t},r));try{xs.set(o,n),await this.client.session.update(t,{namespaces:r.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(c){throw xs.delete(o),c}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)}}),D(this,"isRequestOutOfSync",(t,s)=>s.toString().slice(0,-3)<t.toString().slice(0,-3)),D(this,"onSessionUpdateResponse",(t,s)=>{const{id:r}=s,n=ne("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);v.isJsonRpcResult(s)?this.events.emit(ne("session_update",r),{}):v.isJsonRpcError(s)&&this.events.emit(ne("session_update",r),{error:s.error})}),D(this,"onSessionExtendRequest",async(t,s)=>{const{id:r}=s;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ke(Si)),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)}}),D(this,"onSessionExtendResponse",(t,s)=>{const{id:r}=s,n=ne("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);v.isJsonRpcResult(s)?this.events.emit(ne("session_extend",r),{}):v.isJsonRpcError(s)&&this.events.emit(ne("session_extend",r),{error:s.error})}),D(this,"onSessionPingRequest",async(t,s)=>{const{id:r}=s;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)}}),D(this,"onSessionPingResponse",(t,s)=>{const{id:r}=s,n=ne("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);v.isJsonRpcResult(s)?this.events.emit(ne("session_ping",r),{}):v.isJsonRpcError(s)&&this.events.emit(ne("session_ping",r),{error:s.error})},500)}),D(this,"onSessionDeleteRequest",async(t,s)=>{const{id:r}=s;try{this.isValidDisconnect({topic:t,reason:s.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(Ie.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:de("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),D(this,"onSessionRequest",async t=>{var s,r,n;const{topic:o,payload:a,attestation:c,encryptedId:h,transportType:l}=t,{id:u,params:p}=a;try{await this.isValidRequest(oe({topic:o},p));const g=this.client.session.get(o),w=await this.getVerifyContext({attestationId:c,hash:Ii(JSON.stringify(v.formatJsonRpcRequest("wc_sessionRequest",p,u))),encryptedId:h,metadata:g.peer.metadata,transportType:l}),y={id:u,topic:o,params:p,verifyContext:w};await this.setPendingSessionRequest(y),l===le.link_mode&&(s=g.peer.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp((r=g.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(g){await this.sendError({id:u,topic:o,error:g}),this.client.logger.error(g)}}),D(this,"onSessionRequestResponse",(t,s)=>{const{id:r}=s,n=ne("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);v.isJsonRpcResult(s)?this.events.emit(ne("session_request",r),{result:s.result}):v.isJsonRpcError(s)&&this.events.emit(ne("session_request",r),{error:s.error})}),D(this,"onSessionEventRequest",async(t,s)=>{const{id:r,params:n}=s;try{const o=`${t}_session_event_${n.event.name}`,a=xs.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(oe({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),xs.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),D(this,"onSessionAuthenticateResponse",(t,s)=>{const{id:r}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:s}),v.isJsonRpcResult(s)?this.events.emit(ne("session_request",r),{result:s.result}):v.isJsonRpcError(s)&&this.events.emit(ne("session_request",r),{error:s.error})}),D(this,"onSessionAuthenticateRequest",async t=>{var s;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:h,authPayload:l,expiryTimestamp:u}=n.params,p=await this.getVerifyContext({attestationId:o,hash:Ii(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),g={requester:h,pairingTopic:r,id:n.id,authPayload:l,verifyContext:p,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:g,pairingTopic:r,transportType:c}),c===le.link_mode&&(s=h.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:p})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(n.params.requester.metadata,c),g={type:Mn,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:g,rpcOpts:me.wc_sessionAuthenticate.autoReject,appLink:p})}}),D(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),D(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=wt.idle,this.processSessionRequestQueue()},v.cjsExports$1.toMiliseconds(this.requestQueueDelay))}),D(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:s})=>{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=ne("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ne("session_request",n.request.id),{error:s})})}),D(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===wt.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=wt.active,this.emitSessionRequest(t)}catch(s){this.client.logger.error(s)}}),D(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),D(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const s=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);s&&this.onSessionProposeRequest({topic:t.topic,payload:v.formatJsonRpcRequest("wc_sessionPropose",Ue(oe({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id)})}),D(this,"isValidConnect",async t=>{if(!at(t)){const{message:h}=V("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:s,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(Me(s)||await this.isValidPairingTopic(s),!j2(c)){const{message:h}=V("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!Me(r)&&Vs(r)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(r,"requiredNamespaces")}if(!Me(n)&&Vs(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Me(o)||this.validateSessionProps(o,"sessionProperties"),!Me(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(l=>h.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(h)}`)}}),D(this,"validateNamespaces",(t,s)=>{const r=U2(t,"connect()",s);if(r)throw new Error(r.message)}),D(this,"isValidApprove",async t=>{if(!at(t))throw new Error(V("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:s,namespaces:r,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(s),await this.isValidProposalId(s);const c=this.client.proposal.get(s),h=Hn(r,"approve()");if(h)throw new Error(h.message);const l=_h(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!$e(n,!0)){const{message:u}=V("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(Me(o)||this.validateSessionProps(o,"sessionProperties"),!Me(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(p=>u.has(p)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),D(this,"isValidReject",async t=>{if(!at(t)){const{message:n}=V("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:s,reason:r}=t;if(this.checkRecentlyDeleted(s),await this.isValidProposalId(s),!k2(r)){const{message:n}=V("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),D(this,"isValidSessionSettleRequest",t=>{if(!at(t)){const{message:h}=V("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:s,controller:r,namespaces:n,expiry:o}=t;if(!od(s)){const{message:h}=V("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=A2(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Hn(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(vi(o)){const{message:h}=V("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),D(this,"isValidUpdate",async t=>{if(!at(t)){const{message:c}=V("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:s,namespaces:r}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const n=this.client.session.get(s),o=Hn(r,"update()");if(o)throw new Error(o.message);const a=_h(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),D(this,"isValidExtend",async t=>{if(!at(t)){const{message:r}=V("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:s}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s)}),D(this,"isValidRequest",async t=>{if(!at(t)){const{message:c}=V("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:s,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const{namespaces:a}=this.client.session.get(s);if(!Ph(a,n)){const{message:c}=V("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!L2(r)){const{message:c}=V("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!M2(a,n,r.method)){const{message:c}=V("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!K2(o,Gn)){const{message:c}=V("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Gn.min} and ${Gn.max}`);throw new Error(c)}}),D(this,"isValidRespond",async t=>{var s;if(!at(t)){const{message:o}=V("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(s=t?.response)!=null&&s.id&&this.cleanupAfterResponse(t),o}if(!D2(n)){const{message:o}=V("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),D(this,"isValidPing",async t=>{if(!at(t)){const{message:r}=V("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),D(this,"isValidEmit",async t=>{if(!at(t)){const{message:a}=V("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:s,event:r,chainId:n}=t;await this.isValidSessionTopic(s);const{namespaces:o}=this.client.session.get(s);if(!Ph(o,n)){const{message:a}=V("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!F2(r)){const{message:a}=V("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!z2(o,n,r.name)){const{message:a}=V("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),D(this,"isValidDisconnect",async t=>{if(!at(t)){const{message:r}=V("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),D(this,"isValidAuthenticate",t=>{const{chains:s,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(s)||s.length===0)throw new Error("chains is required and must be a non-empty array");if(!$e(r,!1))throw new Error("uri is required parameter");if(!$e(n,!1))throw new Error("domain is required parameter");if(!$e(o,!1))throw new Error("nonce is required parameter");if([...new Set(s.map(c=>Sr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Sr(s[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),D(this,"getVerifyContext",async t=>{const{attestationId:s,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||Cs,validation:"UNKNOWN",origin:o.url||""}};try{if(a===le.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const h=await this.client.core.verify.resolve({attestationId:s,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),D(this,"validateSessionProps",(t,s)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=V("MISSING_OR_INVALID",`${s} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),D(this,"getPendingAuthRequest",t=>{const s=this.client.auth.requests.get(t);return typeof s=="object"?s:void 0}),D(this,"addToRecentlyDeleted",(t,s)=>{if(this.recentlyDeletedMap.set(t,s),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)}}}),D(this,"checkRecentlyDeleted",t=>{const s=this.recentlyDeletedMap.get(t);if(s){const{message:r}=V("MISSING_OR_INVALID",`Record was recently deleted - ${s}: ${t}`);throw new Error(r)}}),D(this,"isLinkModeEnabled",(t,s)=>{var r,n,o,a,c,h,l,u,p;return!t||s!==le.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&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((l=t?.redirect)==null?void 0:l.universal)!==void 0&&((u=t?.redirect)==null?void 0:u.universal)!==""&&((p=t?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(z.global==null?void 0:z.global.Linking)<"u"}),D(this,"getAppLinkIfEnabled",(t,s)=>{var r;return this.isLinkModeEnabled(t,s)?(r=t?.redirect)==null?void 0:r.universal:void 0}),D(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const s=Zc(t,"topic")||"",r=decodeURIComponent(Zc(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:le.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),D(this,"registerLinkModeListeners",async()=>{var t;if(X0()||Nu()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const s=z.global==null?void 0:z.global.Linking;if(typeof s<"u"){s.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await s.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),D(this,"shouldSetTVF",(t,s)=>{if(!s||t!=="wc_sessionRequest")return!1;const{request:r}=s;return Object.keys(Nh).includes(r.method)}),D(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return Ue(oe({correlationId:t,rpcMethods:[a],chainId:s.chainId},this.isValidContractData(s.request.params)&&{contractAddresses:[(o=(n=s.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),D(this,"isValidContractData",t=>{var s;if(!t)return!1;try{const r=t?.data||((s=t?.[0])==null?void 0:s.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}),D(this,"extractTxHashesFromResult",(t,s)=>{try{const r=Nh[t];if(typeof s=="string")return[s];const n=s[r.key];if(sr(n))return t==="solana_signAllTransactions"?n.map(o=>Rv(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[s,r]of Object.entries(t))for(const n of r)try{await this.onProviderMessageEvent({topic:s,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${s}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=V("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ie.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Pr)?this.client.auth.authKeys.get(Pr):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===le.link_mode?Ss:gr});v.isJsonRpcRequest(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:Ii(s)})):v.isJsonRpcResponse(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,s)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(it.expired,async e=>{const{topic:t,id:s}=W0(e.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,V("EXPIRED"),!0);if(s&&this.client.auth.requests.keys.includes(s))return await this.deletePendingAuthRequest(s,V("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):s&&(await this.deleteProposal(s,!0),this.client.events.emit("proposal_expire",{id:s}))})}registerPairingEvents(){this.client.core.pairing.events.on(Zt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Zt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!$e(e,!1)){const{message:t}=V("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}=V("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(vi(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=V("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!$e(e,!1)){const{message:t}=V("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}=V("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(vi(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=V("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=V("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($e(e,!1)){const{message:t}=V("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=V("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!q2(e)){const{message:t}=V("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=V("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(vi(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=V("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class h$ extends ui{constructor(e,t){super(e,t,G2,da),this.core=e,this.logger=t}}let l$=class extends ui{constructor(e,t){super(e,t,W2,da),this.core=e,this.logger=t}};class u$ extends ui{constructor(e,t){super(e,t,J2,da,s=>s.id),this.core=e,this.logger=t}}class d$ extends ui{constructor(e,t){super(e,t,e$,tn,()=>Pr),this.core=e,this.logger=t}}class p$ extends ui{constructor(e,t){super(e,t,t$,tn),this.core=e,this.logger=t}}class f$ extends ui{constructor(e,t){super(e,t,i$,tn,s=>s.id),this.core=e,this.logger=t}}var g$=Object.defineProperty,y$=(i,e,t)=>e in i?g$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wn=(i,e,t)=>y$(i,typeof e!="symbol"?e+"":e,t);class w${constructor(e,t){this.core=e,this.logger=t,Wn(this,"authKeys"),Wn(this,"pairingTopics"),Wn(this,"requests"),this.authKeys=new d$(this.core,this.logger),this.pairingTopics=new p$(this.core,this.logger),this.requests=new f$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var m$=Object.defineProperty,b$=(i,e,t)=>e in i?m$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Y=(i,e,t)=>b$(i,typeof e!="symbol"?e+"":e,t);let v$=class ld extends Tf{constructor(e){super(e),Y(this,"protocol",ad),Y(this,"version",cd),Y(this,"name",Kn.name),Y(this,"metadata"),Y(this,"core"),Y(this,"logger"),Y(this,"events",new v.eventsExports.EventEmitter),Y(this,"engine"),Y(this,"session"),Y(this,"proposal"),Y(this,"pendingRequest"),Y(this,"auth"),Y(this,"signConfig"),Y(this,"on",(s,r)=>this.events.on(s,r)),Y(this,"once",(s,r)=>this.events.once(s,r)),Y(this,"off",(s,r)=>this.events.off(s,r)),Y(this,"removeListener",(s,r)=>this.events.removeListener(s,r)),Y(this,"removeAllListeners",s=>this.events.removeAllListeners(s)),Y(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"pair",async s=>{try{return await this.engine.pair(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"approve",async s=>{try{return await this.engine.approve(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"reject",async s=>{try{return await this.engine.reject(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"update",async s=>{try{return await this.engine.update(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"extend",async s=>{try{return await this.engine.extend(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"request",async s=>{try{return await this.engine.request(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"respond",async s=>{try{return await this.engine.respond(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"ping",async s=>{try{return await this.engine.ping(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"emit",async s=>{try{return await this.engine.emit(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"find",s=>{try{return this.engine.find(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}}),Y(this,"authenticate",async(s,r)=>{try{return await this.engine.authenticate(s,r)}catch(n){throw this.logger.error(n.message),n}}),Y(this,"formatAuthMessage",s=>{try{return this.engine.formatAuthMessage(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"approveSessionAuthenticate",async s=>{try{return await this.engine.approveSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"rejectSessionAuthenticate",async s=>{try{return await this.engine.rejectSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),this.name=e?.name||Kn.name,this.metadata=K0(e?.metadata),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:v.Ot(v.k({level:e?.logger||Kn.logger}));this.core=e?.core||new H1(e),this.logger=v.E(t,this.name),this.session=new l$(this.core,this.logger),this.proposal=new h$(this.core,this.logger),this.pendingRequest=new u$(this.core,this.logger),this.engine=new c$(this),this.auth=new w$(this.core,this.logger)}static async init(e){const t=new ld(e);return await t.initialize(),t}get context(){return v.y(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()},v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Ch="error",E$="wss://relay.walletconnect.org",$$="wc",I$="universal_provider",wr=`${$$}@2:${I$}:`,ud="https://rpc.walletconnect.org/v1/",ji="generic",S$=`${ud}bundler`,st={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function x$(){}function pa(i){return i==null||typeof i!="object"&&typeof i!="function"}function fa(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function P$(i){if(pa(i))return i;if(Array.isArray(i)||fa(i)||i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);const e=Object.getPrototypeOf(i),t=e.constructor;if(i instanceof Date||i instanceof Map||i instanceof Set)return new t(i);if(i instanceof RegExp){const s=new t(i);return s.lastIndex=i.lastIndex,s}if(i instanceof DataView)return new t(i.buffer.slice(0));if(i instanceof Error){const s=new t(i.message);return s.stack=i.stack,s.name=i.name,s.cause=i.cause,s}if(typeof File<"u"&&i instanceof File)return new t([i],i.name,{type:i.type,lastModified:i.lastModified});if(typeof i=="object"){const s=Object.create(e);return Object.assign(s,i)}return i}function Bh(i){return typeof i=="object"&&i!==null}function dd(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function pd(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const _$="[object RegExp]",fd="[object String]",gd="[object Number]",yd="[object Boolean]",wd="[object Arguments]",O$="[object Symbol]",A$="[object Date]",R$="[object Map]",N$="[object Set]",T$="[object Array]",C$="[object ArrayBuffer]",B$="[object Object]",U$="[object DataView]",j$="[object Uint8Array]",q$="[object Uint8ClampedArray]",k$="[object Uint16Array]",L$="[object Uint32Array]",D$="[object Int8Array]",F$="[object Int16Array]",M$="[object Int32Array]",z$="[object Float32Array]",H$="[object Float64Array]";function V$(i,e){return Fi(i,void 0,i,new Map,e)}function Fi(i,e,t,s=new Map,r=void 0){const n=r?.(i,e,t,s);if(n!=null)return n;if(pa(i))return i;if(s.has(i))return s.get(i);if(Array.isArray(i)){const o=new Array(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=Fi(i[a],a,t,s,r);return Object.hasOwn(i,"index")&&(o.index=i.index),Object.hasOwn(i,"input")&&(o.input=i.input),o}if(i instanceof Date)return new Date(i.getTime());if(i instanceof RegExp){const o=new RegExp(i.source,i.flags);return o.lastIndex=i.lastIndex,o}if(i instanceof Map){const o=new Map;s.set(i,o);for(const[a,c]of i)o.set(a,Fi(c,a,t,s,r));return o}if(i instanceof Set){const o=new Set;s.set(i,o);for(const a of i)o.add(Fi(a,void 0,t,s,r));return o}if(typeof z.Buffer<"u"&&z.Buffer.isBuffer(i))return i.subarray();if(fa(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=Fi(i[a],a,t,s,r);return o}if(i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);if(i instanceof DataView){const o=new DataView(i.buffer.slice(0),i.byteOffset,i.byteLength);return s.set(i,o),Yt(o,i,t,s,r),o}if(typeof File<"u"&&i instanceof File){const o=new File([i],i.name,{type:i.type});return s.set(i,o),Yt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),Yt(o,i,t,s,r),o}if(i instanceof Error){const o=new i.constructor;return s.set(i,o),o.message=i.message,o.name=i.name,o.stack=i.stack,o.cause=i.cause,Yt(o,i,t,s,r),o}if(typeof i=="object"&&K$(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),Yt(o,i,t,s,r),o}return i}function Yt(i,e,t=i,s,r){const n=[...Object.keys(e),...dd(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=Fi(e[a],a,t,s,r))}}function K$(i){switch(pd(i)){case wd:case T$:case C$:case U$:case yd:case A$:case z$:case H$:case D$:case F$:case M$:case R$:case gd:case B$:case _$:case N$:case fd:case O$:case j$:case q$:case k$:case L$:return!0;default:return!1}}function G$(i,e){return V$(i,(t,s,r,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case gd:case fd:case yd:{const o=new i.constructor(i?.valueOf());return Yt(o,i),o}case wd:{const o={};return Yt(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function Uh(i){return G$(i)}function jh(i){return i!==null&&typeof i=="object"&&pd(i)==="[object Arguments]"}function W$(i){return fa(i)}function Z$(i){if(typeof i!="object"||i==null)return!1;if(Object.getPrototypeOf(i)===null)return!0;if(Object.prototype.toString.call(i)!=="[object Object]"){const t=i[Symbol.toStringTag];return t==null||!Object.getOwnPropertyDescriptor(i,Symbol.toStringTag)?.writable?!1:i.toString()===`[object ${t}]`}let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function J$(i,...e){const t=e.slice(0,-1),s=e[e.length-1];let r=i;for(let n=0;n<t.length;n++){const o=t[n];r=zo(r,o,s,new Map)}return r}function zo(i,e,t,s){if(pa(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(s.has(e))return P$(s.get(e));if(s.set(e,i),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),...dd(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(jh(a)&&(a={...a}),jh(c)&&(c={...c}),typeof z.Buffer<"u"&&z.Buffer.isBuffer(a)&&(a=Uh(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],u=Reflect.ownKeys(c);for(let p=0;p<u.length;p++){const g=u[p];l[g]=c[g]}c=l}else c=[];const h=t(c,a,o,i,e,s);h!=null?i[o]=h:Array.isArray(a)||Bh(c)&&Bh(a)?i[o]=zo(c,a,t,s):c==null&&Z$(a)?i[o]=zo({},a,t,s):c==null&&W$(a)?i[o]=Uh(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Y$(i,...e){return J$(i,...e,x$)}var Q$=Object.defineProperty,X$=Object.defineProperties,eI=Object.getOwnPropertyDescriptors,qh=Object.getOwnPropertySymbols,tI=Object.prototype.hasOwnProperty,iI=Object.prototype.propertyIsEnumerable,kh=(i,e,t)=>e in i?Q$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,mr=(i,e)=>{for(var t in e||(e={}))tI.call(e,t)&&kh(i,t,e[t]);if(qh)for(var t of qh(e))iI.call(e,t)&&kh(i,t,e[t]);return i},sI=(i,e)=>X$(i,eI(e));function Qe(i,e,t){var s;const r=Zh(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${ud}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function di(i){return i.includes(":")?i.split(":")[1]:i}function md(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function rI(i,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(i));if(!t.length)return[];const s=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;s.push(...n)}),s}function br(i={},e={}){const t=Lh(i),s=Lh(e);return Y$(t,s)}function Lh(i){var e,t,s,r,n;const o={};if(!fn(i))return o;for(const[a,c]of Object.entries(i)){const h=Jo(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],p=c.rpcMap||{},g=_s(a);o[g]=sI(mr(mr({},o[g]),c),{chains:rn(h,(e=o[g])==null?void 0:e.chains),methods:rn(l,(t=o[g])==null?void 0:t.methods),events:rn(u,(s=o[g])==null?void 0:s.events)}),(fn(p)||fn(((r=o[g])==null?void 0:r.rpcMap)||{}))&&(o[g].rpcMap=mr(mr({},p),(n=o[g])==null?void 0:n.rpcMap))}return o}function Dh(i){return i.includes(":")?i.split(":")[2]:i}function Fh(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=Jo(t)?[t]:s.chains?s.chains:md(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Zn(i){return typeof i=="number"?i:i.includes("0x")?parseInt(i,16):(i=i.includes(":")?i.split(":")[1]:i,isNaN(Number(i))?i:Number(i))}const bd={},ie=i=>bd[i],Jn=(i,e)=>{bd[i]=e};var nI=Object.defineProperty,oI=(i,e,t)=>e in i?nI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,xi=(i,e,t)=>oI(i,typeof e!="symbol"?e+"":e,t);class aI{constructor(e){xi(this,"name","polkadot"),xi(this,"client"),xi(this,"httpProviders"),xi(this,"events"),xi(this,"namespace"),xi(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.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 s;const r=di(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var cI=Object.defineProperty,hI=Object.defineProperties,lI=Object.getOwnPropertyDescriptors,Mh=Object.getOwnPropertySymbols,uI=Object.prototype.hasOwnProperty,dI=Object.prototype.propertyIsEnumerable,Ho=(i,e,t)=>e in i?cI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,zh=(i,e)=>{for(var t in e||(e={}))uI.call(e,t)&&Ho(i,t,e[t]);if(Mh)for(var t of Mh(e))dI.call(e,t)&&Ho(i,t,e[t]);return i},Hh=(i,e)=>hI(i,lI(e)),Pi=(i,e,t)=>Ho(i,typeof e!="symbol"?e+"":e,t);class pI{constructor(e){Pi(this,"name","eip155"),Pi(this,"client"),Pi(this,"chainId"),Pi(this,"namespace"),Pi(this,"httpProviders"),Pi(this,"events"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const s=t||Qe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=parseInt(di(t));e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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,s;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:(s=this.namespace.chains)==null?void 0:s[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,s,r,n,o;const a=(s=(t=e.request)==null?void 0:t.params)==null?void 0:s[0],c=((n=(r=e.request)==null?void 0:r.params)==null?void 0:n[1])||[],h=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[h])return u?.[h];const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Hh(zh({},l.sessionProperties||{}),{capabilities:Hh(zh({},u||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var t,s;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(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(s=r.sessionProperties)==null?void 0:s.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 s;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v.formatJsonRpcRequest("eth_getUserOperationReceipt",[(s=t.request.params)==null?void 0:s[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${S$}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var fI=Object.defineProperty,gI=(i,e,t)=>e in i?fI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,_i=(i,e,t)=>gI(i,typeof e!="symbol"?e+"":e,t);class yI{constructor(e){_i(this,"name","solana"),_i(this,"client"),_i(this,"httpProviders"),_i(this,"events"),_i(this,"namespace"),_i(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=di(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var wI=Object.defineProperty,mI=(i,e,t)=>e in i?wI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Oi=(i,e,t)=>mI(i,typeof e!="symbol"?e+"":e,t);class bI{constructor(e){Oi(this,"name","cosmos"),Oi(this,"client"),Oi(this,"httpProviders"),Oi(this,"events"),Oi(this,"namespace"),Oi(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.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 s;const r=di(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var vI=Object.defineProperty,EI=(i,e,t)=>e in i?vI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ai=(i,e,t)=>EI(i,typeof e!="symbol"?e+"":e,t);class $I{constructor(e){Ai(this,"name","algorand"),Ai(this,"client"),Ai(this,"httpProviders"),Ai(this,"events"),Ai(this,"namespace"),Ai(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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 s=t||Qe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;e[t]=this.createHttpProvider(t,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new v.o(new v.f$1(s,ie("disableProviderPing")))}}var II=Object.defineProperty,SI=(i,e,t)=>e in i?II(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ri=(i,e,t)=>SI(i,typeof e!="symbol"?e+"":e,t);class xI{constructor(e){Ri(this,"name","cip34"),Ri(this,"client"),Ri(this,"httpProviders"),Ri(this,"events"),Ri(this,"namespace"),Ri(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.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 s=this.getCardanoRPCUrl(t),r=di(t);e[r]=this.createHttpProvider(r,s)}),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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||this.getCardanoRPCUrl(e);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var PI=Object.defineProperty,_I=(i,e,t)=>e in i?PI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ni=(i,e,t)=>_I(i,typeof e!="symbol"?e+"":e,t);class OI{constructor(e){Ni(this,"name","elrond"),Ni(this,"client"),Ni(this,"httpProviders"),Ni(this,"events"),Ni(this,"namespace"),Ni(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=di(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var AI=Object.defineProperty,RI=(i,e,t)=>e in i?AI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ti=(i,e,t)=>RI(i,typeof e!="symbol"?e+"":e,t);class NI{constructor(e){Ti(this,"name","multiversx"),Ti(this,"client"),Ti(this,"httpProviders"),Ti(this,"events"),Ti(this,"namespace"),Ti(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=di(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var TI=Object.defineProperty,CI=(i,e,t)=>e in i?TI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ci=(i,e,t)=>CI(i,typeof e!="symbol"?e+"":e,t);class BI{constructor(e){Ci(this,"name","near"),Ci(this,"client"),Ci(this,"httpProviders"),Ci(this,"events"),Ci(this,"namespace"),Ci(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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 s=t||Qe(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(st.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 s;e[t]=this.createHttpProvider(t,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace);return typeof s>"u"?void 0:new v.o(new v.f$1(s,ie("disableProviderPing")))}}var UI=Object.defineProperty,jI=(i,e,t)=>e in i?UI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Bi=(i,e,t)=>jI(i,typeof e!="symbol"?e+"":e,t);class qI{constructor(e){Bi(this,"name","tezos"),Bi(this,"client"),Bi(this,"httpProviders"),Bi(this,"events"),Bi(this,"namespace"),Bi(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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 s=t||Qe(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(st.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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace);return typeof s>"u"?void 0:new v.o(new v.f$1(s))}}var kI=Object.defineProperty,LI=(i,e,t)=>e in i?kI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ui=(i,e,t)=>LI(i,typeof e!="symbol"?e+"":e,t);class DI{constructor(e){Ui(this,"name",ji),Ui(this,"client"),Ui(this,"httpProviders"),Ui(this,"events"),Ui(this,"namespace"),Ui(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const s={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=Zh(r);s[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),s}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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var FI=Object.defineProperty,MI=Object.defineProperties,zI=Object.getOwnPropertyDescriptors,Vh=Object.getOwnPropertySymbols,HI=Object.prototype.hasOwnProperty,VI=Object.prototype.propertyIsEnumerable,Vo=(i,e,t)=>e in i?FI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vr=(i,e)=>{for(var t in e||(e={}))HI.call(e,t)&&Vo(i,t,e[t]);if(Vh)for(var t of Vh(e))VI.call(e,t)&&Vo(i,t,e[t]);return i},Yn=(i,e)=>MI(i,zI(e)),tt=(i,e,t)=>Vo(i,typeof e!="symbol"?e+"":e,t);let KI=class vd{constructor(e){tt(this,"client"),tt(this,"namespaces"),tt(this,"optionalNamespaces"),tt(this,"sessionProperties"),tt(this,"scopedProperties"),tt(this,"events",new v.Nt),tt(this,"rpcProviders",{}),tt(this,"session"),tt(this,"providerOpts"),tt(this,"logger"),tt(this,"uri"),tt(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:v.Ot(v.k({level:e?.logger||Ch})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new vd(e);return await t.initialize(),t}async request(e,t,s){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:vr({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:s})}sendAsync(e,t,s,r){const n=new Date().getTime();this.request(e,s,r).then(o=>t(null,v.formatJsonRpcResult(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:no("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:s,response:r}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const n=await r();if(this.session=n.session,this.session){const o=Fh(this.session.namespaces);this.namespaces=br(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:s}=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 s();this.session=r;const n=Fh(r.namespaces);return this.namespaces=br(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[s,r]=this.validateChain(e),n=this.getProvider(s);n.name===ji?n.setDefaultChain(`${s}:${r}`,t):n.setDefaultChain(r,t)}catch(s){if(!/Please call connect/.test(s.message))throw s}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(Mi(t)){for(const s of t)e.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.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 v$.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Ch,relayUrl:this.providerOpts.relayUrl||E$,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(s){throw this.logger.error("Failed to get session",s),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 s=this.client.session.getAll();this.session=s[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=>_s(t)))];Jn("client",this.client),Jn("events",this.events),Jn("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=rI(t,this.session),r=md(s),n=br(this.namespaces,this.optionalNamespaces),o=Yn(vr({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new pI({namespace:o});break;case"algorand":this.rpcProviders[t]=new $I({namespace:o});break;case"solana":this.rpcProviders[t]=new yI({namespace:o});break;case"cosmos":this.rpcProviders[t]=new bI({namespace:o});break;case"polkadot":this.rpcProviders[t]=new aI({namespace:o});break;case"cip34":this.rpcProviders[t]=new xI({namespace:o});break;case"elrond":this.rpcProviders[t]=new OI({namespace:o});break;case"multiversx":this.rpcProviders[t]=new NI({namespace:o});break;case"near":this.rpcProviders[t]=new BI({namespace:o});break;case"tezos":this.rpcProviders[t]=new qI({namespace:o});break;default:this.rpcProviders[ji]?this.rpcProviders[ji].updateNamespace(o):this.rpcProviders[ji]=new DI({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:s}=e;s===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:s,topic:r}=e;if(r!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=s;if(n.name==="accountsChanged"){const o=n.data;o&&Mi(o)&&this.events.emit("accountsChanged",o.map(Dh))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=_s(o),h=Zn(o)!==Zn(a)?`${c}:${Zn(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var s,r;if(e!==((s=this.session)==null?void 0:s.topic))return;const{namespaces:n}=t,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Yn(vr({},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",Yn(vr({},no("USER_DISCONNECTED")),{data:e.topic})))}),this.on(st.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[ji]}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:s={},sessionProperties:r,scopedProperties:n}=e;this.optionalNamespaces=br(t,s),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,s]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(o=>_s(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&s)return[t,s];const r=_s(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[s,r]=this.validateChain(e);if(!r)return;this.updateNamespaceChain(s,r),this.events.emit("chainChanged",r);const n=this.getProvider(s).getDefaultChain();t||this.getProvider(s).setDefaultChain(r),this.emitAccountsChangedOnChainChange({namespace:s,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:s}){var r,n;try{if(t===s)return;const o=(n=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${s}:`)).map(Dh);if(!Mi(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const s=this.namespaces[e]?e:`${e}:${t}`,r={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[s]?this.namespaces[s]&&(this.namespaces[s].defaultChain=t):this.namespaces[s]=r}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 s;const r=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.setItem(`${wr}/${e}${r}`,t)}async getFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${wr}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${wr}/${e}${s}`)}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 s of t)s.startsWith(wr)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const GI=KI,WI="wc",ZI="ethereum_provider",JI=`${WI}@2:${ZI}:`,YI="https://rpc.walletconnect.org/v1/",Br=["eth_sendTransaction","personal_sign"],Ed=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Ur=["chainChanged","accountsChanged"],$d=["chainChanged","accountsChanged","message","disconnect","connect"],QI=async()=>{const{createAppKit:i}=await Promise.resolve().then(()=>require("./core-B-drR9_7.js")).then(e=>e.core);return i};var XI=Object.defineProperty,eS=Object.defineProperties,tS=Object.getOwnPropertyDescriptors,Kh=Object.getOwnPropertySymbols,iS=Object.prototype.hasOwnProperty,sS=Object.prototype.propertyIsEnumerable,Ko=(i,e,t)=>e in i?XI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Kt=(i,e)=>{for(var t in e||(e={}))iS.call(e,t)&&Ko(i,t,e[t]);if(Kh)for(var t of Kh(e))sS.call(e,t)&&Ko(i,t,e[t]);return i},Ps=(i,e)=>eS(i,tS(e)),He=(i,e,t)=>Ko(i,typeof e!="symbol"?e+"":e,t);function jr(i){return Number(i[0].split(":")[1])}function Er(i){return`0x${i.toString(16)}`}function rS(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!Mi(e))throw new Error("Invalid chains");const c={chains:e,methods:s||Br,events:n||Ur,rpcMap:Kt({},e.length?{[jr(e)]:a[jr(e)]}:{})},h=n?.filter(g=>!Ur.includes(g)),l=s?.filter(g=>!Br.includes(g));if(!t&&!o&&!r&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=h?.length&&l?.length||!t,p={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(r!=null&&r.length?r:Ed))],events:[...new Set(c.events.concat(o!=null&&o.length?o:$d))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?p:void 0}}class sn{constructor(){He(this,"events",new v.eventsExports.EventEmitter),He(this,"namespace","eip155"),He(this,"accounts",[]),He(this,"signer"),He(this,"chainId",1),He(this,"modal"),He(this,"rpc"),He(this,"STORAGE_KEY",JI),He(this,"on",(e,t)=>(this.events.on(e,t),this)),He(this,"once",(e,t)=>(this.events.once(e,t),this)),He(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),He(this,"off",(e,t)=>(this.events.off(e,t),this)),He(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new sn;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,s){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),s)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var t;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:s,optional:r}=rS(this.rpc);try{const n=await new Promise(async(a,c)=>{var h,l;this.rpc.showQrModal&&((h=this.modal)==null||h.open(),(l=this.modal)==null||l.subscribeState(p=>{!p.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const u=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Ps(Kt({namespaces:Kt({},s&&{[this.namespace]:s})},r&&{optionalNamespaces:{[this.namespace]:r}}),{pairingTopic:e?.pairingTopic,scopedProperties:u})).then(p=>{a(p)}).catch(p=>{var g;(g=this.modal)==null||g.showErrorMessage("Unable to connect"),c(new Error(p.message))})});if(!n)return;const o=ga(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Er(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(t=this.modal)==null||t.close()}}async authenticate(e,t){var s;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const r=await new Promise(async(o,a)=>{var c,h;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(h=this.modal)==null||h.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Ps(Kt({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=r.session;if(n){const o=ga(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Er(this.chainId)})}return r}catch(r){throw this.signer.logger.error(r),r}finally{(s=this.modal)==null||s.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:s}=t;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",Er(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",Ps(Kt({},no("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",Er(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,s,r]=e.split(":");return{chainId:`${t}:${s}`,address:r}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,s;const r=(t=e?.chains)!=null?t:[],n=(s=e?.optionalChains)!=null?s:[],o=r.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=r.length?e?.methods||Br:[],c=r.length?e?.events||Ur:[],h=e?.optionalMethods||[],l=e?.optionalEvents||[],u=e?.rpcMap||this.buildRpcMap(o,e.projectId),p=e?.qrModalOptions||void 0;return{chains:r?.map(g=>this.formatChainId(g)),optionalChains:n.map(g=>this.formatChainId(g)),methods:a,events:c,optionalMethods:h,optionalEvents:l,rpcMap:u,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:p,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const s={};return e.forEach(r=>{s[r]=this.getRpcUrl(r,t)}),s}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?jr(this.rpc.chains):jr(this.rpc.optionalChains),this.signer=await GI.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let t;try{const s=await QI(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return gS}),n=r(Ps(Kt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=s(Ps(Kt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:s,rpcMap:r}=e;t&&Mi(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=r?.[n]||this.getRpcUrl(n)})),s&&Mi(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=r?.[n]||this.getRpcUrl(n)}))}getRpcUrl(e,t){var s;return((s=this.rpc.rpcMap)==null?void 0:s[e])||`${YI}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}}const nS=sn;var oS=Object.defineProperty,aS=Object.defineProperties,cS=Object.getOwnPropertyDescriptors,Gh=Object.getOwnPropertySymbols,hS=Object.prototype.hasOwnProperty,lS=Object.prototype.propertyIsEnumerable,Wh=(i,e,t)=>e in i?oS(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Id=(i,e)=>{for(var t in e||(e={}))hS.call(e,t)&&Wh(i,t,e[t]);if(Gh)for(var t of Gh(e))lS.call(e,t)&&Wh(i,t,e[t]);return i},uS=(i,e)=>aS(i,cS(e));function dS(i){if(i)return{"--w3m-font-family":i["--wcm-font-family"],"--w3m-accent":i["--wcm-accent-color"],"--w3m-color-mix":i["--wcm-background-color"],"--w3m-z-index":i["--wcm-z-index"]?Number(i["--wcm-z-index"]):void 0,"--w3m-qr-color":i["--wcm-accent-color"],"--w3m-font-size-master":i["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":i["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const pS=i=>{const[e,t]=i.split(":");return Sd({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function fS(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(pS).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(u=>{var p;return u.id===((p=i.defaultChain)==null?void 0:p.id)}),l={projectId:i.projectId,networks:c,themeMode:i.themeMode,themeVariables:dS(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:uS(Id({},i.metadata),{name:((t=i.metadata)==null?void 0:t.name)||"WalletConnect",description:((s=i.metadata)==null?void 0:s.description)||"Connect to WalletConnect-compatible wallets",url:((r=i.metadata)==null?void 0:r.url)||"https://walletconnect.org",icons:((n=i.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:i.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(i.explorerRecommendedWalletIds)?i.explorerRecommendedWalletIds:[],excludeWalletIds:i.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(i.explorerExcludedWalletIds)?i.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=i.mobileWallets)!=null&&o.length||(a=i.desktopWallets)!=null&&a.length){const u=[...(i.mobileWallets||[]).map(w=>({id:w.id,name:w.name,links:w.links})),...(i.desktopWallets||[]).map(w=>({id:w.id,name:w.name,links:{native:w.links.native,universal:w.links.universal}}))],p=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],g=u.filter(w=>!p.includes(w.id));g.length&&(l.customWallets=g)}return l}function Sd(i){return Id({formatters:void 0,fees:void 0,serializers:void 0},i)}var gS=Object.freeze({__proto__:null,convertWCMToAppKitOptions:fS,defineChain:Sd});const yS=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:nS,OPTIONAL_EVENTS:$d,OPTIONAL_METHODS:Ed,REQUIRED_EVENTS:Ur,REQUIRED_METHODS:Br,default:sn},Symbol.toStringTag,{value:"Module"}));exports.Hash=Iu;exports.abytes=er;exports.aexists=To;exports.ahash=n0;exports.aoutput=$u;exports.concatBytes=w0;exports.createView=p0;exports.index_es=yS;exports.randomBytes=m0;exports.rotr=f0;exports.toBytes=sa;exports.wrapConstructor=Su;
11
+ Approved: ${p.toString()}`))}),o.forEach(u=>{s||(Qt(r[u].methods,n[u].methods)?Qt(r[u].events,n[u].events)||(s=V("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):s=V("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),s}function H2(i){const e={};return Object.keys(i).forEach(t=>{var s;t.includes(":")?e[t]=i[t]:(s=i[t].chains)==null||s.forEach(r=>{e[r]={methods:i[t].methods,events:i[t].events}})}),e}function Oh(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function V2(i){const e={};return Object.keys(i).forEach(t=>{t.includes(":")?e[t]=i[t]:gs(i[t].accounts)?.forEach(r=>{e[r]={accounts:i[t].accounts.filter(n=>n.includes(`${r}:`)),methods:i[t].methods,events:i[t].events}})}),e}function K2(i,e){return ua(i,!1)&&i<=e.max&&i>=e.min}const Vn={};class xs{static get(e){return Vn[e]}static set(e,t){Vn[e]=t}static delete(e){delete Vn[e]}}const ad="wc",cd=2,hd="client",da=`${ad}@${cd}:${hd}:`,Kn={name:hd,logger:"error"},Ah="WALLETCONNECT_DEEPLINK_CHOICE",G2="proposal",Rh="Proposal expired",W2="session",Si=v.cjsExports$1.SEVEN_DAYS,Z2="engine",me={wc_sessionPropose:{req:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1104},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1106},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1112},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1114},res:{ttl:v.cjsExports$1.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:v.cjsExports$1.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:v.cjsExports$1.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:v.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1119}}},Gn={min:v.cjsExports$1.FIVE_MINUTES,max:v.cjsExports$1.SEVEN_DAYS},wt={idle:"IDLE",active:"ACTIVE"},Nh={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},J2="request",Y2=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Q2="wc",X2="auth",e$="authKeys",t$="pairingTopics",i$="requests",tn=`${Q2}@${1.5}:${X2}:`,Pr=`${tn}:PUB_KEY`;var s$=Object.defineProperty,r$=Object.defineProperties,n$=Object.getOwnPropertyDescriptors,Th=Object.getOwnPropertySymbols,o$=Object.prototype.hasOwnProperty,a$=Object.prototype.propertyIsEnumerable,Mo=(i,e,t)=>e in i?s$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oe=(i,e)=>{for(var t in e||(e={}))o$.call(e,t)&&Mo(i,t,e[t]);if(Th)for(var t of Th(e))a$.call(e,t)&&Mo(i,t,e[t]);return i},Ue=(i,e)=>r$(i,n$(e)),D=(i,e,t)=>Mo(i,typeof e!="symbol"?e+"":e,t);class c$ extends Cf{constructor(e){super(e),D(this,"name",Z2),D(this,"events",new v.Nt),D(this,"initialized",!1),D(this,"requestQueue",{state:wt.idle,queue:[]}),D(this,"sessionRequestQueue",{state:wt.idle,queue:[]}),D(this,"requestQueueDelay",v.cjsExports$1.ONE_SECOND),D(this,"expectedPairingMethodMap",new Map),D(this,"recentlyDeletedMap",new Map),D(this,"recentlyDeletedLimit",200),D(this,"relayMessageCache",[]),D(this,"pendingSessions",new Map),D(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(me)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},v.cjsExports$1.toMiliseconds(this.requestQueueDelay)))}),D(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=Ue(oe({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=S2(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h}=s;let l=r,u,p=!1;try{if(l){const O=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),p=O.active}}catch(O){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),O}if(!l||!p){const{topic:O,uri:P}=await this.client.core.pairing.create();l=O,u=P}if(!l){const{message:O}=V("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(O)}const g=await this.client.core.crypto.generateKeyPair(),w=me.wc_sessionPropose.req.ttl||v.cjsExports$1.FIVE_MINUTES,y=ke(w),d=Ue(oe(oe({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:tu}],proposer:{publicKey:g,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:v.payloadId()}),m=ne("session_connect",d.id),{reject:f,resolve:E,done:_}=bi(w,Rh),C=({id:O})=>{O===d.id&&(this.client.events.off("proposal_expire",C),this.pendingSessions.delete(d.id),this.events.emit(m,{error:{message:Rh,code:0}}))};return this.client.events.on("proposal_expire",C),this.events.once(m,({error:O,session:P})=>{this.client.events.off("proposal_expire",C),O?f(O):P&&E(P)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:d,throwOnFailedPublish:!0,clientRpcId:d.id}),await this.setProposal(d.id,d),{uri:u,approval:_}}),D(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(s){throw this.client.logger.error("pair() failed"),s}}),D(this,"approve",async t=>{var s,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(s=t?.id)==null?void 0:s.toString(),trace:[nt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(S){throw o.setError(Ht.no_internet_connection),S}try{await this.isValidProposalId(t?.id)}catch(S){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),o.setError(Ht.proposal_not_found),S}try{await this.isValidApprove(t)}catch(S){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Ht.session_approve_namespace_validation_failure),S}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=t,g=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:w,proposer:y,requiredNamespaces:d,optionalNamespaces:m}=g;let f=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:w});f||(f=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:nt.session_approve_started,properties:{topic:w,trace:[nt.session_approve_started,nt.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),_=y.publicKey,C=await this.client.core.crypto.generateSharedKey(E,_),O=oe(oe(oe({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:E,metadata:this.client.metadata},expiry:ke(Si)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),P=le.relay;f.addTrace(nt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(C,{transportType:P})}catch(S){throw f.setError(Ht.subscribe_session_topic_failure),S}f.addTrace(nt.subscribe_session_topic_success);const R=Ue(oe({},O),{topic:C,requiredNamespaces:d,optionalNamespaces:m,pairingTopic:w,acknowledged:!1,self:O.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:E,transportType:le.relay});await this.client.session.set(C,R),f.addTrace(nt.store_session);try{f.addTrace(nt.publishing_session_settle),await this.sendRequest({topic:C,method:"wc_sessionSettle",params:O,throwOnFailedPublish:!0}).catch(S=>{throw f?.setError(Ht.session_settle_publish_failure),S}),f.addTrace(nt.session_settle_publish_success),f.addTrace(nt.publishing_session_approve),await this.sendResult({id:a,topic:w,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(S=>{throw f?.setError(Ht.session_approve_publish_failure),S}),f.addTrace(nt.session_approve_publish_success)}catch(S){throw this.client.logger.error(S),this.client.session.delete(C,de("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(C),S}return this.client.core.eventClient.deleteEvent({eventId:f.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:y.metadata}),await this.client.proposal.delete(a,de("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(C,ke(Si)),{topic:C,acknowledged:()=>Promise.resolve(this.client.session.get(C))}}),D(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:s,reason:r}=t;let n;try{n=this.client.proposal.get(s).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${s}) failed`),o}n&&(await this.sendError({id:s,topic:n,error:r,rpcOpts:me.wc_sessionPropose.reject}),await this.client.proposal.delete(s,de("USER_DISCONNECTED")))}),D(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:s,namespaces:r}=t,{done:n,resolve:o,reject:a}=bi(),c=v.payloadId(),h=v.getBigIntRpcId().toString(),l=this.client.session.get(s).namespaces;return this.events.once(ne("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(s,{namespaces:r}),await this.sendRequest({topic:s,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(u=>{this.client.logger.error(u),this.client.session.update(s,{namespaces:l}),a(u)}),{acknowledged:n}}),D(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:s}=t,r=v.payloadId(),{done:n,resolve:o,reject:a}=bi();return this.events.once(ne("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,ke(Si)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),D(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:s,request:r,topic:n,expiry:o=me.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);a?.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const c=v.payloadId(),h=v.getBigIntRpcId().toString(),{done:l,resolve:u,reject:p}=bi(o,"Request expired. Please try again.");this.events.once(ne("session_request",c),({error:m,result:f})=>{m?p(m):u(f)});const g="wc_sessionRequest",w=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(w)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:{request:Ue(oe({},r),{expiryTimestamp:ke(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:w}).catch(m=>p(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const y={request:Ue(oe({},r),{expiryTimestamp:ke(o)}),chainId:s},d=this.shouldSetTVF(g,y);return await Promise.all([new Promise(async m=>{await this.sendRequest(oe({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:y,expiry:o,throwOnFailedPublish:!0},d&&{tvf:this.getTVFParams(c,y)})).catch(f=>p(f)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),m()}),new Promise(async m=>{var f;if(!((f=a.sessionConfig)!=null&&f.disableDeepLink)){const E=await Q0(this.client.core.storage,Ah);await Z0({id:c,topic:n,wcDeepLink:E})}m()}),l()]).then(m=>m[2])}),D(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:s,response:r}=t,{id:n}=r,o=this.client.session.get(s);o.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);v.isJsonRpcResult(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):v.isJsonRpcError(r)&&await this.sendError({id:n,topic:s,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),D(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:s}=t;if(this.client.session.keys.includes(s)){const r=v.payloadId(),n=v.getBigIntRpcId().toString(),{done:o,resolve:a,reject:c}=bi();this.events.once(ne("session_ping",r),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:s,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(s)&&(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:s}))}),D(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:s,event:r,chainId:n}=t,o=v.getBigIntRpcId().toString(),a=v.payloadId();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),D(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:s}=t;if(this.client.session.keys.includes(s))await this.sendRequest({topic:s,method:"wc_sessionDelete",params:de("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:s,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(s))await this.client.core.pairing.disconnect({topic:s});else{const{message:r}=V("MISMATCHED_TOPIC",`Session or pairing topic not found: ${s}`);throw new Error(r)}}),D(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(s=>_2(s,t)))),D(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),D(this,"authenticate",async(t,s)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=s&&this.client.core.linkModeSupportedApps.includes(s)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?le.link_mode:le.relay;o===le.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:p,exp:g,nbf:w,methods:y=[],expiry:d}=t,m=[...t.resources||[]],{topic:f,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:f,uri:E}});const _=await this.client.core.crypto.generateKeyPair(),C=zn(_);if(await Promise.all([this.client.auth.authKeys.set(Pr,{responseTopic:C,publicKey:_}),this.client.auth.pairingTopics.set(C,{topic:C,pairingTopic:f})]),await this.client.core.relayer.subscribe(C,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${f}`),y.length>0){const{namespace:x}=Sr(a[0]);let q=Hv(x,"request",y);xr(m)&&(q=Kv(q,m.pop())),m.push(q)}const O=d&&d>me.wc_sessionAuthenticate.req.ttl?d:me.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:p??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:g,nbf:w,resources:m},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:ke(O)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},S={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:f,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:ke(me.wc_sessionPropose.req.ttl),id:v.payloadId()},{done:U,resolve:N,reject:B}=bi(O,"Request expired"),j=v.payloadId(),b=ne("session_connect",S.id),I=ne("session_request",j),$=async({error:x,session:q})=>{this.events.off(I,A),x?B(x):q&&N({session:q})},A=async x=>{var q,k,L;if(await this.deletePendingAuthRequest(j,{message:"fulfilled",code:0}),x.error){const W=de("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return x.error.code===W.code?void 0:(this.events.off(b,$),B(x.error.message))}await this.deleteProposal(S.id),this.events.off(b,$);const{cacaos:M,responder:F}=x.result,H=[],K=[];for(const W of M){await sh({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(de("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Be}=W,ue=xr(Be.resources),ae=[Co(Be.iss)],he=Tr(Be.iss);if(ue){const Xe=rh(ue),dt=nh(ue);H.push(...Xe),ae.push(...dt)}for(const Xe of ae)K.push(`${Xe}:${he}`)}const Z=await this.client.core.crypto.generateSharedKey(_,F.publicKey);let G;H.length>0&&(G={topic:Z,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:F,controller:F.publicKey,expiry:ke(Si),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:f,namespaces:Sh([...new Set(H)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(Z,{transportType:o}),await this.client.session.set(Z,G),f&&await this.client.core.pairing.updateMetadata({topic:f,metadata:F.metadata}),G=this.client.session.get(Z)),(q=this.client.metadata.redirect)!=null&&q.linkMode&&(k=F.metadata.redirect)!=null&&k.linkMode&&(L=F.metadata.redirect)!=null&&L.universal&&s&&(this.client.core.addLinkModeSupportedApp(F.metadata.redirect.universal),this.client.session.update(Z,{transportType:le.link_mode})),N({auths:M,session:G})};this.events.once(b,$),this.events.once(I,A);let T;try{if(n){const x=v.formatJsonRpcRequest("wc_sessionAuthenticate",P,j);this.client.core.history.set(f,x);const q=await this.client.core.crypto.encode("",x,{type:u2,encoding:Ss});T=yr(s,f,q)}else await Promise.all([this.sendRequest({topic:f,method:"wc_sessionAuthenticate",params:P,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:j}),this.sendRequest({topic:f,method:"wc_sessionPropose",params:S,expiry:me.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:S.id})])}catch(x){throw this.events.off(b,$),this.events.off(I,A),x}return await this.setProposal(S.id,S),await this.setAuthRequest(j,{request:Ue(oe({},P),{verifyContext:{}}),pairingTopic:f,transportType:o}),{uri:T??E,response:U}}),D(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[Vt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(d){throw n.setError(bs.no_internet_connection),d}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(bs.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||le.relay;a===le.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=zn(c),u={type:Mn,receiverPublicKey:c,senderPublicKey:h},p=[],g=[];for(const d of r){if(!await sh({cacao:d,projectId:this.client.core.projectId})){n.setError(bs.invalid_cacao);const C=de("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:C,encodeOpts:u}),new Error(C.message)}n.addTrace(Vt.cacaos_verified);const{p:m}=d,f=xr(m.resources),E=[Co(m.iss)],_=Tr(m.iss);if(f){const C=rh(f),O=nh(f);p.push(...C),E.push(...O)}for(const C of E)g.push(`${C}:${_}`)}const w=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Vt.create_authenticated_session_topic);let y;if(p?.length>0){y={topic:w,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ke(Si),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Sh([...new Set(p)],[...new Set(g)]),transportType:a},n.addTrace(Vt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:a})}catch(d){throw n.setError(bs.subscribe_authenticated_session_topic_failure),d}n.addTrace(Vt.subscribe_authenticated_session_topic_success),await this.client.session.set(w,y),n.addTrace(Vt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Vt.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:s,result:{cacaos:r,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(d){throw n.setError(bs.authenticated_session_approve_publish_failure),d}return await this.client.auth.requests.delete(s,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:y}}),D(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:s,reason:r}=t,n=this.getPendingAuthRequest(s);if(!n)throw new Error(`Could not find pending auth request with id ${s}`);n.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=zn(o),h={type:Mn,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:s,topic:c,error:r,encodeOpts:h,rpcOpts:me.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(s,{message:"rejected",code:0}),await this.client.proposal.delete(s,de("USER_DISCONNECTED"))}),D(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return Du(s,r)}),D(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)}),D(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const s=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!==s.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(s){this.client.logger.error(s)}}),D(this,"deleteSession",async t=>{var s;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,de("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Ah).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,de("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=wt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),D(this,"deleteProposal",async(t,s)=>{if(s)try{const r=this.client.proposal.get(t);this.client.core.eventClient.getEvent({topic:r.pairingTopic})?.setError(Ht.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,de("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),D(this,"deletePendingSessionRequest",async(t,s,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,s),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=wt.idle,this.client.events.emit("session_request_expire",{id:t}))}),D(this,"deletePendingAuthRequest",async(t,s,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,s),r?Promise.resolve():this.client.core.expirer.del(t)])}),D(this,"setExpiry",async(t,s)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,s),await this.client.session.update(t,{expiry:s}))}),D(this,"setProposal",async(t,s)=>{this.client.core.expirer.set(t,ke(me.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),D(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=le.relay}=s;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})}),D(this,"setPendingSessionRequest",async t=>{const{id:s,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ke(me.wc_sessionRequest.req.ttl);this.client.core.expirer.set(s,a),await this.client.pendingRequest.set(s,{id:s,topic:r,params:n,verifyContext:o})}),D(this,"sendRequest",async t=>{const{topic:s,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:u}=t,p=v.formatJsonRpcRequest(r,n,c);let g;const w=!!l;try{const m=w?Ss:gr;g=await this.client.core.crypto.encode(s,p,{encoding:m})}catch(m){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),m}let y;if(Y2.includes(r)){const m=Ii(JSON.stringify(p)),f=Ii(g);y=await this.client.core.verify.register({id:f,decryptedId:m})}const d=me[r].req;if(d.attestation=y,o&&(d.ttl=o),a&&(d.id=a),this.client.core.history.set(s,p),w){const m=yr(l,s,g);await z.global.Linking.openURL(m,this.client.name)}else{const m=me[r].req;o&&(m.ttl=o),a&&(m.id=a),m.tvf=Ue(oe({},u),{correlationId:p.id}),h?(m.internal=Ue(oe({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,g,m)):this.client.core.relayer.publish(s,g,m).catch(f=>this.client.logger.error(f))}return p.id}),D(this,"sendResult",async t=>{const{id:s,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=v.formatJsonRpcResult(s,n);let l;const u=c&&typeof(z.global==null?void 0:z.global.Linking)<"u";try{const w=u?Ss:gr;l=await this.client.core.crypto.encode(r,h,Ue(oe({},a||{}),{encoding:w}))}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),w}let p,g;try{p=await this.client.core.history.get(r,s);const w=p.request;try{this.shouldSetTVF(w.method,w.params)&&(g=this.getTVFParams(s,w.params,n))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),w}if(u){const w=yr(c,r,l);await z.global.Linking.openURL(w,this.client.name)}else{const w=p.request.method,y=me[w].res;y.tvf=Ue(oe({},g),{correlationId:s}),o?(y.internal=Ue(oe({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,y)):this.client.core.relayer.publish(r,l,y).catch(d=>this.client.logger.error(d))}await this.client.core.history.resolve(h)}),D(this,"sendError",async t=>{const{id:s,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=v.formatJsonRpcError(s,n);let l;const u=c&&typeof(z.global==null?void 0:z.global.Linking)<"u";try{const g=u?Ss:gr;l=await this.client.core.crypto.encode(r,h,Ue(oe({},o||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),g}let p;try{p=await this.client.core.history.get(r,s)}catch(g){throw this.client.logger.error(`sendError() -> history.get(${r}, ${s}) failed`),g}if(u){const g=yr(c,r,l);await z.global.Linking.openURL(g,this.client.name)}else{const g=p.request.method,w=a||me[g].res;this.client.core.relayer.publish(r,l,w)}await this.client.core.history.resolve(h)}),D(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;vi(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=>{vi(r.expiryTimestamp)&&s.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...s.map(r=>this.deleteProposal(r))])}),D(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),D(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),D(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===wt.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=wt.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=wt.idle}),D(this,"processRequest",async t=>{const{topic:s,payload:r,attestation:n,transportType:o,encryptedId:a}=t,c=r.method;if(!this.shouldIgnorePairingRequest({topic:s,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:s,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(s,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(s,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(s,r);case"wc_sessionPing":return await this.onSessionPingRequest(s,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(s,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:s,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(s,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:s,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),D(this,"onRelayEventResponse",async t=>{const{topic:s,payload:r,transportType:n}=t,o=(await this.client.core.history.get(s,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(s,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(s,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(s,r);case"wc_sessionExtend":return this.onSessionExtendResponse(s,r);case"wc_sessionPing":return this.onSessionPingResponse(s,r);case"wc_sessionRequest":return this.onSessionRequestResponse(s,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(s,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),D(this,"onRelayEventUnknownPayload",t=>{const{topic:s}=t,{message:r}=V("MISSING_OR_INVALID",`Decoded payload on topic ${s} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),D(this,"shouldIgnorePairingRequest",t=>{const{topic:s,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(s);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),D(this,"onSessionProposeRequest",async t=>{const{topic:s,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:c}=r;try{const h=this.client.core.eventClient.getEvent({topic:s});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),h?.setError(St.proposal_listener_not_found)),this.isValidConnect(oe({},r.params));const l=a.expiryTimestamp||ke(me.wc_sessionPropose.req.ttl),u=oe({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,u);const p=await this.getVerifyContext({attestationId:n,hash:Ii(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});h?.addTrace(mt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:p})}catch(h){await this.sendError({id:c,topic:s,error:h,rpcOpts:me.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),D(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(v.isJsonRpcResult(s)){const{result:o}=s;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(c,h);this.pendingSessions.set(n,{sessionTopic:l,pairingTopic:t,proposalId:n,publicKey:c});const u=await this.client.core.relayer.subscribe(l,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(v.isJsonRpcError(s)){await this.client.proposal.delete(n,de("USER_DISCONNECTED"));const o=ne("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:s.error})}}),D(this,"onSessionSettleRequest",async(t,s)=>{const{id:r,params:n}=s;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=s.params,g=[...this.pendingSessions.values()].find(d=>d.sessionTopic===t);if(!g)return this.client.logger.error(`Pending session not found for topic ${t}`);const w=this.client.proposal.get(g.proposalId),y=Ue(oe(oe(oe({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:g.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:g.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),{transportType:le.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:g.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(ne("session_connect",g.proposalId),{session:y}),this.pendingSessions.delete(g.proposalId),this.deleteProposal(g.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:s.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),D(this,"onSessionSettleResponse",async(t,s)=>{const{id:r}=s;v.isJsonRpcResult(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(ne("session_approve",r),{})):v.isJsonRpcError(s)&&(await this.client.session.delete(t,de("USER_DISCONNECTED")),this.events.emit(ne("session_approve",r),{error:s.error}))}),D(this,"onSessionUpdateRequest",async(t,s)=>{const{params:r,id:n}=s;try{const o=`${t}_session_update`,a=xs.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:de("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:t},r));try{xs.set(o,n),await this.client.session.update(t,{namespaces:r.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(c){throw xs.delete(o),c}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)}}),D(this,"isRequestOutOfSync",(t,s)=>s.toString().slice(0,-3)<t.toString().slice(0,-3)),D(this,"onSessionUpdateResponse",(t,s)=>{const{id:r}=s,n=ne("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);v.isJsonRpcResult(s)?this.events.emit(ne("session_update",r),{}):v.isJsonRpcError(s)&&this.events.emit(ne("session_update",r),{error:s.error})}),D(this,"onSessionExtendRequest",async(t,s)=>{const{id:r}=s;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ke(Si)),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)}}),D(this,"onSessionExtendResponse",(t,s)=>{const{id:r}=s,n=ne("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);v.isJsonRpcResult(s)?this.events.emit(ne("session_extend",r),{}):v.isJsonRpcError(s)&&this.events.emit(ne("session_extend",r),{error:s.error})}),D(this,"onSessionPingRequest",async(t,s)=>{const{id:r}=s;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)}}),D(this,"onSessionPingResponse",(t,s)=>{const{id:r}=s,n=ne("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);v.isJsonRpcResult(s)?this.events.emit(ne("session_ping",r),{}):v.isJsonRpcError(s)&&this.events.emit(ne("session_ping",r),{error:s.error})},500)}),D(this,"onSessionDeleteRequest",async(t,s)=>{const{id:r}=s;try{this.isValidDisconnect({topic:t,reason:s.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(Ie.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:de("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),D(this,"onSessionRequest",async t=>{var s,r,n;const{topic:o,payload:a,attestation:c,encryptedId:h,transportType:l}=t,{id:u,params:p}=a;try{await this.isValidRequest(oe({topic:o},p));const g=this.client.session.get(o),w=await this.getVerifyContext({attestationId:c,hash:Ii(JSON.stringify(v.formatJsonRpcRequest("wc_sessionRequest",p,u))),encryptedId:h,metadata:g.peer.metadata,transportType:l}),y={id:u,topic:o,params:p,verifyContext:w};await this.setPendingSessionRequest(y),l===le.link_mode&&(s=g.peer.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp((r=g.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(g){await this.sendError({id:u,topic:o,error:g}),this.client.logger.error(g)}}),D(this,"onSessionRequestResponse",(t,s)=>{const{id:r}=s,n=ne("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);v.isJsonRpcResult(s)?this.events.emit(ne("session_request",r),{result:s.result}):v.isJsonRpcError(s)&&this.events.emit(ne("session_request",r),{error:s.error})}),D(this,"onSessionEventRequest",async(t,s)=>{const{id:r,params:n}=s;try{const o=`${t}_session_event_${n.event.name}`,a=xs.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(oe({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),xs.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),D(this,"onSessionAuthenticateResponse",(t,s)=>{const{id:r}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:s}),v.isJsonRpcResult(s)?this.events.emit(ne("session_request",r),{result:s.result}):v.isJsonRpcError(s)&&this.events.emit(ne("session_request",r),{error:s.error})}),D(this,"onSessionAuthenticateRequest",async t=>{var s;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:h,authPayload:l,expiryTimestamp:u}=n.params,p=await this.getVerifyContext({attestationId:o,hash:Ii(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),g={requester:h,pairingTopic:r,id:n.id,authPayload:l,verifyContext:p,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:g,pairingTopic:r,transportType:c}),c===le.link_mode&&(s=h.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:p})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(n.params.requester.metadata,c),g={type:Mn,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:g,rpcOpts:me.wc_sessionAuthenticate.autoReject,appLink:p})}}),D(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),D(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=wt.idle,this.processSessionRequestQueue()},v.cjsExports$1.toMiliseconds(this.requestQueueDelay))}),D(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:s})=>{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=ne("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ne("session_request",n.request.id),{error:s})})}),D(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===wt.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=wt.active,this.emitSessionRequest(t)}catch(s){this.client.logger.error(s)}}),D(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),D(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const s=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);s&&this.onSessionProposeRequest({topic:t.topic,payload:v.formatJsonRpcRequest("wc_sessionPropose",Ue(oe({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id)})}),D(this,"isValidConnect",async t=>{if(!at(t)){const{message:h}=V("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:s,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(Me(s)||await this.isValidPairingTopic(s),!j2(c)){const{message:h}=V("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!Me(r)&&Vs(r)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(r,"requiredNamespaces")}if(!Me(n)&&Vs(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Me(o)||this.validateSessionProps(o,"sessionProperties"),!Me(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(l=>h.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(h)}`)}}),D(this,"validateNamespaces",(t,s)=>{const r=U2(t,"connect()",s);if(r)throw new Error(r.message)}),D(this,"isValidApprove",async t=>{if(!at(t))throw new Error(V("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:s,namespaces:r,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(s),await this.isValidProposalId(s);const c=this.client.proposal.get(s),h=Hn(r,"approve()");if(h)throw new Error(h.message);const l=_h(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!$e(n,!0)){const{message:u}=V("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(Me(o)||this.validateSessionProps(o,"sessionProperties"),!Me(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(p=>u.has(p)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),D(this,"isValidReject",async t=>{if(!at(t)){const{message:n}=V("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:s,reason:r}=t;if(this.checkRecentlyDeleted(s),await this.isValidProposalId(s),!k2(r)){const{message:n}=V("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),D(this,"isValidSessionSettleRequest",t=>{if(!at(t)){const{message:h}=V("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:s,controller:r,namespaces:n,expiry:o}=t;if(!od(s)){const{message:h}=V("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=A2(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Hn(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(vi(o)){const{message:h}=V("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),D(this,"isValidUpdate",async t=>{if(!at(t)){const{message:c}=V("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:s,namespaces:r}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const n=this.client.session.get(s),o=Hn(r,"update()");if(o)throw new Error(o.message);const a=_h(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),D(this,"isValidExtend",async t=>{if(!at(t)){const{message:r}=V("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:s}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s)}),D(this,"isValidRequest",async t=>{if(!at(t)){const{message:c}=V("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:s,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const{namespaces:a}=this.client.session.get(s);if(!Ph(a,n)){const{message:c}=V("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!L2(r)){const{message:c}=V("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!M2(a,n,r.method)){const{message:c}=V("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!K2(o,Gn)){const{message:c}=V("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Gn.min} and ${Gn.max}`);throw new Error(c)}}),D(this,"isValidRespond",async t=>{var s;if(!at(t)){const{message:o}=V("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(s=t?.response)!=null&&s.id&&this.cleanupAfterResponse(t),o}if(!D2(n)){const{message:o}=V("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),D(this,"isValidPing",async t=>{if(!at(t)){const{message:r}=V("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),D(this,"isValidEmit",async t=>{if(!at(t)){const{message:a}=V("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:s,event:r,chainId:n}=t;await this.isValidSessionTopic(s);const{namespaces:o}=this.client.session.get(s);if(!Ph(o,n)){const{message:a}=V("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!F2(r)){const{message:a}=V("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!z2(o,n,r.name)){const{message:a}=V("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),D(this,"isValidDisconnect",async t=>{if(!at(t)){const{message:r}=V("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),D(this,"isValidAuthenticate",t=>{const{chains:s,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(s)||s.length===0)throw new Error("chains is required and must be a non-empty array");if(!$e(r,!1))throw new Error("uri is required parameter");if(!$e(n,!1))throw new Error("domain is required parameter");if(!$e(o,!1))throw new Error("nonce is required parameter");if([...new Set(s.map(c=>Sr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Sr(s[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),D(this,"getVerifyContext",async t=>{const{attestationId:s,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||Cs,validation:"UNKNOWN",origin:o.url||""}};try{if(a===le.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const h=await this.client.core.verify.resolve({attestationId:s,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),D(this,"validateSessionProps",(t,s)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=V("MISSING_OR_INVALID",`${s} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),D(this,"getPendingAuthRequest",t=>{const s=this.client.auth.requests.get(t);return typeof s=="object"?s:void 0}),D(this,"addToRecentlyDeleted",(t,s)=>{if(this.recentlyDeletedMap.set(t,s),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)}}}),D(this,"checkRecentlyDeleted",t=>{const s=this.recentlyDeletedMap.get(t);if(s){const{message:r}=V("MISSING_OR_INVALID",`Record was recently deleted - ${s}: ${t}`);throw new Error(r)}}),D(this,"isLinkModeEnabled",(t,s)=>{var r,n,o,a,c,h,l,u,p;return!t||s!==le.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&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((l=t?.redirect)==null?void 0:l.universal)!==void 0&&((u=t?.redirect)==null?void 0:u.universal)!==""&&((p=t?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(z.global==null?void 0:z.global.Linking)<"u"}),D(this,"getAppLinkIfEnabled",(t,s)=>{var r;return this.isLinkModeEnabled(t,s)?(r=t?.redirect)==null?void 0:r.universal:void 0}),D(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const s=Zc(t,"topic")||"",r=decodeURIComponent(Zc(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:le.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),D(this,"registerLinkModeListeners",async()=>{var t;if(X0()||Nu()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const s=z.global==null?void 0:z.global.Linking;if(typeof s<"u"){s.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await s.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),D(this,"shouldSetTVF",(t,s)=>{if(!s||t!=="wc_sessionRequest")return!1;const{request:r}=s;return Object.keys(Nh).includes(r.method)}),D(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return Ue(oe({correlationId:t,rpcMethods:[a],chainId:s.chainId},this.isValidContractData(s.request.params)&&{contractAddresses:[(o=(n=s.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),D(this,"isValidContractData",t=>{var s;if(!t)return!1;try{const r=t?.data||((s=t?.[0])==null?void 0:s.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}),D(this,"extractTxHashesFromResult",(t,s)=>{try{const r=Nh[t];if(typeof s=="string")return[s];const n=s[r.key];if(sr(n))return t==="solana_signAllTransactions"?n.map(o=>Rv(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[s,r]of Object.entries(t))for(const n of r)try{await this.onProviderMessageEvent({topic:s,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${s}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=V("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ie.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Pr)?this.client.auth.authKeys.get(Pr):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===le.link_mode?Ss:gr});v.isJsonRpcRequest(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:Ii(s)})):v.isJsonRpcResponse(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,s)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(it.expired,async e=>{const{topic:t,id:s}=W0(e.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,V("EXPIRED"),!0);if(s&&this.client.auth.requests.keys.includes(s))return await this.deletePendingAuthRequest(s,V("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):s&&(await this.deleteProposal(s,!0),this.client.events.emit("proposal_expire",{id:s}))})}registerPairingEvents(){this.client.core.pairing.events.on(Zt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Zt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!$e(e,!1)){const{message:t}=V("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}=V("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(vi(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=V("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!$e(e,!1)){const{message:t}=V("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}=V("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(vi(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=V("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=V("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($e(e,!1)){const{message:t}=V("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=V("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!q2(e)){const{message:t}=V("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=V("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(vi(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=V("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class h$ extends ui{constructor(e,t){super(e,t,G2,da),this.core=e,this.logger=t}}let l$=class extends ui{constructor(e,t){super(e,t,W2,da),this.core=e,this.logger=t}};class u$ extends ui{constructor(e,t){super(e,t,J2,da,s=>s.id),this.core=e,this.logger=t}}class d$ extends ui{constructor(e,t){super(e,t,e$,tn,()=>Pr),this.core=e,this.logger=t}}class p$ extends ui{constructor(e,t){super(e,t,t$,tn),this.core=e,this.logger=t}}class f$ extends ui{constructor(e,t){super(e,t,i$,tn,s=>s.id),this.core=e,this.logger=t}}var g$=Object.defineProperty,y$=(i,e,t)=>e in i?g$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wn=(i,e,t)=>y$(i,typeof e!="symbol"?e+"":e,t);class w${constructor(e,t){this.core=e,this.logger=t,Wn(this,"authKeys"),Wn(this,"pairingTopics"),Wn(this,"requests"),this.authKeys=new d$(this.core,this.logger),this.pairingTopics=new p$(this.core,this.logger),this.requests=new f$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var m$=Object.defineProperty,b$=(i,e,t)=>e in i?m$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Y=(i,e,t)=>b$(i,typeof e!="symbol"?e+"":e,t);let v$=class ld extends Tf{constructor(e){super(e),Y(this,"protocol",ad),Y(this,"version",cd),Y(this,"name",Kn.name),Y(this,"metadata"),Y(this,"core"),Y(this,"logger"),Y(this,"events",new v.eventsExports.EventEmitter),Y(this,"engine"),Y(this,"session"),Y(this,"proposal"),Y(this,"pendingRequest"),Y(this,"auth"),Y(this,"signConfig"),Y(this,"on",(s,r)=>this.events.on(s,r)),Y(this,"once",(s,r)=>this.events.once(s,r)),Y(this,"off",(s,r)=>this.events.off(s,r)),Y(this,"removeListener",(s,r)=>this.events.removeListener(s,r)),Y(this,"removeAllListeners",s=>this.events.removeAllListeners(s)),Y(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"pair",async s=>{try{return await this.engine.pair(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"approve",async s=>{try{return await this.engine.approve(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"reject",async s=>{try{return await this.engine.reject(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"update",async s=>{try{return await this.engine.update(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"extend",async s=>{try{return await this.engine.extend(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"request",async s=>{try{return await this.engine.request(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"respond",async s=>{try{return await this.engine.respond(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"ping",async s=>{try{return await this.engine.ping(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"emit",async s=>{try{return await this.engine.emit(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"find",s=>{try{return this.engine.find(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}}),Y(this,"authenticate",async(s,r)=>{try{return await this.engine.authenticate(s,r)}catch(n){throw this.logger.error(n.message),n}}),Y(this,"formatAuthMessage",s=>{try{return this.engine.formatAuthMessage(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"approveSessionAuthenticate",async s=>{try{return await this.engine.approveSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),Y(this,"rejectSessionAuthenticate",async s=>{try{return await this.engine.rejectSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),this.name=e?.name||Kn.name,this.metadata=K0(e?.metadata),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:v.Ot(v.k({level:e?.logger||Kn.logger}));this.core=e?.core||new H1(e),this.logger=v.E(t,this.name),this.session=new l$(this.core,this.logger),this.proposal=new h$(this.core,this.logger),this.pendingRequest=new u$(this.core,this.logger),this.engine=new c$(this),this.auth=new w$(this.core,this.logger)}static async init(e){const t=new ld(e);return await t.initialize(),t}get context(){return v.y(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()},v.cjsExports$1.toMiliseconds(v.cjsExports$1.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Ch="error",E$="wss://relay.walletconnect.org",$$="wc",I$="universal_provider",wr=`${$$}@2:${I$}:`,ud="https://rpc.walletconnect.org/v1/",ji="generic",S$=`${ud}bundler`,st={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function x$(){}function pa(i){return i==null||typeof i!="object"&&typeof i!="function"}function fa(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function P$(i){if(pa(i))return i;if(Array.isArray(i)||fa(i)||i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);const e=Object.getPrototypeOf(i),t=e.constructor;if(i instanceof Date||i instanceof Map||i instanceof Set)return new t(i);if(i instanceof RegExp){const s=new t(i);return s.lastIndex=i.lastIndex,s}if(i instanceof DataView)return new t(i.buffer.slice(0));if(i instanceof Error){const s=new t(i.message);return s.stack=i.stack,s.name=i.name,s.cause=i.cause,s}if(typeof File<"u"&&i instanceof File)return new t([i],i.name,{type:i.type,lastModified:i.lastModified});if(typeof i=="object"){const s=Object.create(e);return Object.assign(s,i)}return i}function Bh(i){return typeof i=="object"&&i!==null}function dd(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function pd(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const _$="[object RegExp]",fd="[object String]",gd="[object Number]",yd="[object Boolean]",wd="[object Arguments]",O$="[object Symbol]",A$="[object Date]",R$="[object Map]",N$="[object Set]",T$="[object Array]",C$="[object ArrayBuffer]",B$="[object Object]",U$="[object DataView]",j$="[object Uint8Array]",q$="[object Uint8ClampedArray]",k$="[object Uint16Array]",L$="[object Uint32Array]",D$="[object Int8Array]",F$="[object Int16Array]",M$="[object Int32Array]",z$="[object Float32Array]",H$="[object Float64Array]";function V$(i,e){return Fi(i,void 0,i,new Map,e)}function Fi(i,e,t,s=new Map,r=void 0){const n=r?.(i,e,t,s);if(n!=null)return n;if(pa(i))return i;if(s.has(i))return s.get(i);if(Array.isArray(i)){const o=new Array(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=Fi(i[a],a,t,s,r);return Object.hasOwn(i,"index")&&(o.index=i.index),Object.hasOwn(i,"input")&&(o.input=i.input),o}if(i instanceof Date)return new Date(i.getTime());if(i instanceof RegExp){const o=new RegExp(i.source,i.flags);return o.lastIndex=i.lastIndex,o}if(i instanceof Map){const o=new Map;s.set(i,o);for(const[a,c]of i)o.set(a,Fi(c,a,t,s,r));return o}if(i instanceof Set){const o=new Set;s.set(i,o);for(const a of i)o.add(Fi(a,void 0,t,s,r));return o}if(typeof z.Buffer<"u"&&z.Buffer.isBuffer(i))return i.subarray();if(fa(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=Fi(i[a],a,t,s,r);return o}if(i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);if(i instanceof DataView){const o=new DataView(i.buffer.slice(0),i.byteOffset,i.byteLength);return s.set(i,o),Yt(o,i,t,s,r),o}if(typeof File<"u"&&i instanceof File){const o=new File([i],i.name,{type:i.type});return s.set(i,o),Yt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),Yt(o,i,t,s,r),o}if(i instanceof Error){const o=new i.constructor;return s.set(i,o),o.message=i.message,o.name=i.name,o.stack=i.stack,o.cause=i.cause,Yt(o,i,t,s,r),o}if(typeof i=="object"&&K$(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),Yt(o,i,t,s,r),o}return i}function Yt(i,e,t=i,s,r){const n=[...Object.keys(e),...dd(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=Fi(e[a],a,t,s,r))}}function K$(i){switch(pd(i)){case wd:case T$:case C$:case U$:case yd:case A$:case z$:case H$:case D$:case F$:case M$:case R$:case gd:case B$:case _$:case N$:case fd:case O$:case j$:case q$:case k$:case L$:return!0;default:return!1}}function G$(i,e){return V$(i,(t,s,r,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case gd:case fd:case yd:{const o=new i.constructor(i?.valueOf());return Yt(o,i),o}case wd:{const o={};return Yt(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function Uh(i){return G$(i)}function jh(i){return i!==null&&typeof i=="object"&&pd(i)==="[object Arguments]"}function W$(i){return fa(i)}function Z$(i){if(typeof i!="object"||i==null)return!1;if(Object.getPrototypeOf(i)===null)return!0;if(Object.prototype.toString.call(i)!=="[object Object]"){const t=i[Symbol.toStringTag];return t==null||!Object.getOwnPropertyDescriptor(i,Symbol.toStringTag)?.writable?!1:i.toString()===`[object ${t}]`}let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function J$(i,...e){const t=e.slice(0,-1),s=e[e.length-1];let r=i;for(let n=0;n<t.length;n++){const o=t[n];r=zo(r,o,s,new Map)}return r}function zo(i,e,t,s){if(pa(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(s.has(e))return P$(s.get(e));if(s.set(e,i),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),...dd(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(jh(a)&&(a={...a}),jh(c)&&(c={...c}),typeof z.Buffer<"u"&&z.Buffer.isBuffer(a)&&(a=Uh(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],u=Reflect.ownKeys(c);for(let p=0;p<u.length;p++){const g=u[p];l[g]=c[g]}c=l}else c=[];const h=t(c,a,o,i,e,s);h!=null?i[o]=h:Array.isArray(a)||Bh(c)&&Bh(a)?i[o]=zo(c,a,t,s):c==null&&Z$(a)?i[o]=zo({},a,t,s):c==null&&W$(a)?i[o]=Uh(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Y$(i,...e){return J$(i,...e,x$)}var Q$=Object.defineProperty,X$=Object.defineProperties,eI=Object.getOwnPropertyDescriptors,qh=Object.getOwnPropertySymbols,tI=Object.prototype.hasOwnProperty,iI=Object.prototype.propertyIsEnumerable,kh=(i,e,t)=>e in i?Q$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,mr=(i,e)=>{for(var t in e||(e={}))tI.call(e,t)&&kh(i,t,e[t]);if(qh)for(var t of qh(e))iI.call(e,t)&&kh(i,t,e[t]);return i},sI=(i,e)=>X$(i,eI(e));function Qe(i,e,t){var s;const r=Zh(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${ud}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function di(i){return i.includes(":")?i.split(":")[1]:i}function md(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function rI(i,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(i));if(!t.length)return[];const s=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;s.push(...n)}),s}function br(i={},e={}){const t=Lh(i),s=Lh(e);return Y$(t,s)}function Lh(i){var e,t,s,r,n;const o={};if(!fn(i))return o;for(const[a,c]of Object.entries(i)){const h=Jo(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],p=c.rpcMap||{},g=_s(a);o[g]=sI(mr(mr({},o[g]),c),{chains:rn(h,(e=o[g])==null?void 0:e.chains),methods:rn(l,(t=o[g])==null?void 0:t.methods),events:rn(u,(s=o[g])==null?void 0:s.events)}),(fn(p)||fn(((r=o[g])==null?void 0:r.rpcMap)||{}))&&(o[g].rpcMap=mr(mr({},p),(n=o[g])==null?void 0:n.rpcMap))}return o}function Dh(i){return i.includes(":")?i.split(":")[2]:i}function Fh(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=Jo(t)?[t]:s.chains?s.chains:md(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Zn(i){return typeof i=="number"?i:i.includes("0x")?parseInt(i,16):(i=i.includes(":")?i.split(":")[1]:i,isNaN(Number(i))?i:Number(i))}const bd={},ie=i=>bd[i],Jn=(i,e)=>{bd[i]=e};var nI=Object.defineProperty,oI=(i,e,t)=>e in i?nI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,xi=(i,e,t)=>oI(i,typeof e!="symbol"?e+"":e,t);class aI{constructor(e){xi(this,"name","polkadot"),xi(this,"client"),xi(this,"httpProviders"),xi(this,"events"),xi(this,"namespace"),xi(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.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 s;const r=di(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var cI=Object.defineProperty,hI=Object.defineProperties,lI=Object.getOwnPropertyDescriptors,Mh=Object.getOwnPropertySymbols,uI=Object.prototype.hasOwnProperty,dI=Object.prototype.propertyIsEnumerable,Ho=(i,e,t)=>e in i?cI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,zh=(i,e)=>{for(var t in e||(e={}))uI.call(e,t)&&Ho(i,t,e[t]);if(Mh)for(var t of Mh(e))dI.call(e,t)&&Ho(i,t,e[t]);return i},Hh=(i,e)=>hI(i,lI(e)),Pi=(i,e,t)=>Ho(i,typeof e!="symbol"?e+"":e,t);class pI{constructor(e){Pi(this,"name","eip155"),Pi(this,"client"),Pi(this,"chainId"),Pi(this,"namespace"),Pi(this,"httpProviders"),Pi(this,"events"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const s=t||Qe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=parseInt(di(t));e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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,s;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:(s=this.namespace.chains)==null?void 0:s[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,s,r,n,o;const a=(s=(t=e.request)==null?void 0:t.params)==null?void 0:s[0],c=((n=(r=e.request)==null?void 0:r.params)==null?void 0:n[1])||[],h=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[h])return u?.[h];const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Hh(zh({},l.sessionProperties||{}),{capabilities:Hh(zh({},u||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var t,s;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(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(s=r.sessionProperties)==null?void 0:s.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 s;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v.formatJsonRpcRequest("eth_getUserOperationReceipt",[(s=t.request.params)==null?void 0:s[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${S$}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var fI=Object.defineProperty,gI=(i,e,t)=>e in i?fI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,_i=(i,e,t)=>gI(i,typeof e!="symbol"?e+"":e,t);class yI{constructor(e){_i(this,"name","solana"),_i(this,"client"),_i(this,"httpProviders"),_i(this,"events"),_i(this,"namespace"),_i(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=di(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var wI=Object.defineProperty,mI=(i,e,t)=>e in i?wI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Oi=(i,e,t)=>mI(i,typeof e!="symbol"?e+"":e,t);class bI{constructor(e){Oi(this,"name","cosmos"),Oi(this,"client"),Oi(this,"httpProviders"),Oi(this,"events"),Oi(this,"namespace"),Oi(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.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 s;const r=di(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var vI=Object.defineProperty,EI=(i,e,t)=>e in i?vI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ai=(i,e,t)=>EI(i,typeof e!="symbol"?e+"":e,t);class $I{constructor(e){Ai(this,"name","algorand"),Ai(this,"client"),Ai(this,"httpProviders"),Ai(this,"events"),Ai(this,"namespace"),Ai(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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 s=t||Qe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;e[t]=this.createHttpProvider(t,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new v.o(new v.f$1(s,ie("disableProviderPing")))}}var II=Object.defineProperty,SI=(i,e,t)=>e in i?II(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ri=(i,e,t)=>SI(i,typeof e!="symbol"?e+"":e,t);class xI{constructor(e){Ri(this,"name","cip34"),Ri(this,"client"),Ri(this,"httpProviders"),Ri(this,"events"),Ri(this,"namespace"),Ri(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.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 s=this.getCardanoRPCUrl(t),r=di(t);e[r]=this.createHttpProvider(r,s)}),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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||this.getCardanoRPCUrl(e);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var PI=Object.defineProperty,_I=(i,e,t)=>e in i?PI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ni=(i,e,t)=>_I(i,typeof e!="symbol"?e+"":e,t);class OI{constructor(e){Ni(this,"name","elrond"),Ni(this,"client"),Ni(this,"httpProviders"),Ni(this,"events"),Ni(this,"namespace"),Ni(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=di(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var AI=Object.defineProperty,RI=(i,e,t)=>e in i?AI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ti=(i,e,t)=>RI(i,typeof e!="symbol"?e+"":e,t);class NI{constructor(e){Ti(this,"name","multiversx"),Ti(this,"client"),Ti(this,"httpProviders"),Ti(this,"events"),Ti(this,"namespace"),Ti(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=di(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var TI=Object.defineProperty,CI=(i,e,t)=>e in i?TI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ci=(i,e,t)=>CI(i,typeof e!="symbol"?e+"":e,t);class BI{constructor(e){Ci(this,"name","near"),Ci(this,"client"),Ci(this,"httpProviders"),Ci(this,"events"),Ci(this,"namespace"),Ci(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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 s=t||Qe(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(st.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 s;e[t]=this.createHttpProvider(t,(s=this.namespace.rpcMap)==null?void 0:s[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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace);return typeof s>"u"?void 0:new v.o(new v.f$1(s,ie("disableProviderPing")))}}var UI=Object.defineProperty,jI=(i,e,t)=>e in i?UI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Bi=(i,e,t)=>jI(i,typeof e!="symbol"?e+"":e,t);class qI{constructor(e){Bi(this,"name","tezos"),Bi(this,"client"),Bi(this,"httpProviders"),Bi(this,"events"),Bi(this,"namespace"),Bi(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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 s=t||Qe(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(st.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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace);return typeof s>"u"?void 0:new v.o(new v.f$1(s))}}var kI=Object.defineProperty,LI=(i,e,t)=>e in i?kI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ui=(i,e,t)=>LI(i,typeof e!="symbol"?e+"":e,t);class DI{constructor(e){Ui(this,"name",ji),Ui(this,"client"),Ui(this,"httpProviders"),Ui(this,"events"),Ui(this,"namespace"),Ui(this,"chainId"),this.namespace=e.namespace,this.events=ie("events"),this.client=ie("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(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const s={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=Zh(r);s[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),s}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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qe(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new v.o(new v.f$1(s,ie("disableProviderPing")))}}var FI=Object.defineProperty,MI=Object.defineProperties,zI=Object.getOwnPropertyDescriptors,Vh=Object.getOwnPropertySymbols,HI=Object.prototype.hasOwnProperty,VI=Object.prototype.propertyIsEnumerable,Vo=(i,e,t)=>e in i?FI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vr=(i,e)=>{for(var t in e||(e={}))HI.call(e,t)&&Vo(i,t,e[t]);if(Vh)for(var t of Vh(e))VI.call(e,t)&&Vo(i,t,e[t]);return i},Yn=(i,e)=>MI(i,zI(e)),tt=(i,e,t)=>Vo(i,typeof e!="symbol"?e+"":e,t);let KI=class vd{constructor(e){tt(this,"client"),tt(this,"namespaces"),tt(this,"optionalNamespaces"),tt(this,"sessionProperties"),tt(this,"scopedProperties"),tt(this,"events",new v.Nt),tt(this,"rpcProviders",{}),tt(this,"session"),tt(this,"providerOpts"),tt(this,"logger"),tt(this,"uri"),tt(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:v.Ot(v.k({level:e?.logger||Ch})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new vd(e);return await t.initialize(),t}async request(e,t,s){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:vr({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:s})}sendAsync(e,t,s,r){const n=new Date().getTime();this.request(e,s,r).then(o=>t(null,v.formatJsonRpcResult(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:no("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:s,response:r}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const n=await r();if(this.session=n.session,this.session){const o=Fh(this.session.namespaces);this.namespaces=br(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:s}=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 s();this.session=r;const n=Fh(r.namespaces);return this.namespaces=br(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[s,r]=this.validateChain(e),n=this.getProvider(s);n.name===ji?n.setDefaultChain(`${s}:${r}`,t):n.setDefaultChain(r,t)}catch(s){if(!/Please call connect/.test(s.message))throw s}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(Mi(t)){for(const s of t)e.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.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 v$.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Ch,relayUrl:this.providerOpts.relayUrl||E$,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(s){throw this.logger.error("Failed to get session",s),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 s=this.client.session.getAll();this.session=s[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=>_s(t)))];Jn("client",this.client),Jn("events",this.events),Jn("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=rI(t,this.session),r=md(s),n=br(this.namespaces,this.optionalNamespaces),o=Yn(vr({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new pI({namespace:o});break;case"algorand":this.rpcProviders[t]=new $I({namespace:o});break;case"solana":this.rpcProviders[t]=new yI({namespace:o});break;case"cosmos":this.rpcProviders[t]=new bI({namespace:o});break;case"polkadot":this.rpcProviders[t]=new aI({namespace:o});break;case"cip34":this.rpcProviders[t]=new xI({namespace:o});break;case"elrond":this.rpcProviders[t]=new OI({namespace:o});break;case"multiversx":this.rpcProviders[t]=new NI({namespace:o});break;case"near":this.rpcProviders[t]=new BI({namespace:o});break;case"tezos":this.rpcProviders[t]=new qI({namespace:o});break;default:this.rpcProviders[ji]?this.rpcProviders[ji].updateNamespace(o):this.rpcProviders[ji]=new DI({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:s}=e;s===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:s,topic:r}=e;if(r!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=s;if(n.name==="accountsChanged"){const o=n.data;o&&Mi(o)&&this.events.emit("accountsChanged",o.map(Dh))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=_s(o),h=Zn(o)!==Zn(a)?`${c}:${Zn(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var s,r;if(e!==((s=this.session)==null?void 0:s.topic))return;const{namespaces:n}=t,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Yn(vr({},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",Yn(vr({},no("USER_DISCONNECTED")),{data:e.topic})))}),this.on(st.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[ji]}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:s={},sessionProperties:r,scopedProperties:n}=e;this.optionalNamespaces=br(t,s),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,s]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(o=>_s(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&s)return[t,s];const r=_s(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[s,r]=this.validateChain(e);if(!r)return;this.updateNamespaceChain(s,r),this.events.emit("chainChanged",r);const n=this.getProvider(s).getDefaultChain();t||this.getProvider(s).setDefaultChain(r),this.emitAccountsChangedOnChainChange({namespace:s,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:s}){var r,n;try{if(t===s)return;const o=(n=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${s}:`)).map(Dh);if(!Mi(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const s=this.namespaces[e]?e:`${e}:${t}`,r={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[s]?this.namespaces[s]&&(this.namespaces[s].defaultChain=t):this.namespaces[s]=r}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 s;const r=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.setItem(`${wr}/${e}${r}`,t)}async getFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${wr}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${wr}/${e}${s}`)}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 s of t)s.startsWith(wr)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const GI=KI,WI="wc",ZI="ethereum_provider",JI=`${WI}@2:${ZI}:`,YI="https://rpc.walletconnect.org/v1/",Br=["eth_sendTransaction","personal_sign"],Ed=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Ur=["chainChanged","accountsChanged"],$d=["chainChanged","accountsChanged","message","disconnect","connect"],QI=async()=>{const{createAppKit:i}=await Promise.resolve().then(()=>require("./core-B8BH62nw.js")).then(e=>e.core);return i};var XI=Object.defineProperty,eS=Object.defineProperties,tS=Object.getOwnPropertyDescriptors,Kh=Object.getOwnPropertySymbols,iS=Object.prototype.hasOwnProperty,sS=Object.prototype.propertyIsEnumerable,Ko=(i,e,t)=>e in i?XI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Kt=(i,e)=>{for(var t in e||(e={}))iS.call(e,t)&&Ko(i,t,e[t]);if(Kh)for(var t of Kh(e))sS.call(e,t)&&Ko(i,t,e[t]);return i},Ps=(i,e)=>eS(i,tS(e)),He=(i,e,t)=>Ko(i,typeof e!="symbol"?e+"":e,t);function jr(i){return Number(i[0].split(":")[1])}function Er(i){return`0x${i.toString(16)}`}function rS(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!Mi(e))throw new Error("Invalid chains");const c={chains:e,methods:s||Br,events:n||Ur,rpcMap:Kt({},e.length?{[jr(e)]:a[jr(e)]}:{})},h=n?.filter(g=>!Ur.includes(g)),l=s?.filter(g=>!Br.includes(g));if(!t&&!o&&!r&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=h?.length&&l?.length||!t,p={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(r!=null&&r.length?r:Ed))],events:[...new Set(c.events.concat(o!=null&&o.length?o:$d))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?p:void 0}}class sn{constructor(){He(this,"events",new v.eventsExports.EventEmitter),He(this,"namespace","eip155"),He(this,"accounts",[]),He(this,"signer"),He(this,"chainId",1),He(this,"modal"),He(this,"rpc"),He(this,"STORAGE_KEY",JI),He(this,"on",(e,t)=>(this.events.on(e,t),this)),He(this,"once",(e,t)=>(this.events.once(e,t),this)),He(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),He(this,"off",(e,t)=>(this.events.off(e,t),this)),He(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new sn;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,s){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),s)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var t;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:s,optional:r}=rS(this.rpc);try{const n=await new Promise(async(a,c)=>{var h,l;this.rpc.showQrModal&&((h=this.modal)==null||h.open(),(l=this.modal)==null||l.subscribeState(p=>{!p.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const u=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Ps(Kt({namespaces:Kt({},s&&{[this.namespace]:s})},r&&{optionalNamespaces:{[this.namespace]:r}}),{pairingTopic:e?.pairingTopic,scopedProperties:u})).then(p=>{a(p)}).catch(p=>{var g;(g=this.modal)==null||g.showErrorMessage("Unable to connect"),c(new Error(p.message))})});if(!n)return;const o=ga(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Er(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(t=this.modal)==null||t.close()}}async authenticate(e,t){var s;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const r=await new Promise(async(o,a)=>{var c,h;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(h=this.modal)==null||h.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Ps(Kt({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=r.session;if(n){const o=ga(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Er(this.chainId)})}return r}catch(r){throw this.signer.logger.error(r),r}finally{(s=this.modal)==null||s.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:s}=t;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",Er(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",Ps(Kt({},no("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",Er(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,s,r]=e.split(":");return{chainId:`${t}:${s}`,address:r}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,s;const r=(t=e?.chains)!=null?t:[],n=(s=e?.optionalChains)!=null?s:[],o=r.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=r.length?e?.methods||Br:[],c=r.length?e?.events||Ur:[],h=e?.optionalMethods||[],l=e?.optionalEvents||[],u=e?.rpcMap||this.buildRpcMap(o,e.projectId),p=e?.qrModalOptions||void 0;return{chains:r?.map(g=>this.formatChainId(g)),optionalChains:n.map(g=>this.formatChainId(g)),methods:a,events:c,optionalMethods:h,optionalEvents:l,rpcMap:u,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:p,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const s={};return e.forEach(r=>{s[r]=this.getRpcUrl(r,t)}),s}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?jr(this.rpc.chains):jr(this.rpc.optionalChains),this.signer=await GI.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let t;try{const s=await QI(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return gS}),n=r(Ps(Kt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=s(Ps(Kt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:s,rpcMap:r}=e;t&&Mi(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=r?.[n]||this.getRpcUrl(n)})),s&&Mi(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=r?.[n]||this.getRpcUrl(n)}))}getRpcUrl(e,t){var s;return((s=this.rpc.rpcMap)==null?void 0:s[e])||`${YI}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}}const nS=sn;var oS=Object.defineProperty,aS=Object.defineProperties,cS=Object.getOwnPropertyDescriptors,Gh=Object.getOwnPropertySymbols,hS=Object.prototype.hasOwnProperty,lS=Object.prototype.propertyIsEnumerable,Wh=(i,e,t)=>e in i?oS(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Id=(i,e)=>{for(var t in e||(e={}))hS.call(e,t)&&Wh(i,t,e[t]);if(Gh)for(var t of Gh(e))lS.call(e,t)&&Wh(i,t,e[t]);return i},uS=(i,e)=>aS(i,cS(e));function dS(i){if(i)return{"--w3m-font-family":i["--wcm-font-family"],"--w3m-accent":i["--wcm-accent-color"],"--w3m-color-mix":i["--wcm-background-color"],"--w3m-z-index":i["--wcm-z-index"]?Number(i["--wcm-z-index"]):void 0,"--w3m-qr-color":i["--wcm-accent-color"],"--w3m-font-size-master":i["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":i["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const pS=i=>{const[e,t]=i.split(":");return Sd({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function fS(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(pS).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(u=>{var p;return u.id===((p=i.defaultChain)==null?void 0:p.id)}),l={projectId:i.projectId,networks:c,themeMode:i.themeMode,themeVariables:dS(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:uS(Id({},i.metadata),{name:((t=i.metadata)==null?void 0:t.name)||"WalletConnect",description:((s=i.metadata)==null?void 0:s.description)||"Connect to WalletConnect-compatible wallets",url:((r=i.metadata)==null?void 0:r.url)||"https://walletconnect.org",icons:((n=i.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:i.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(i.explorerRecommendedWalletIds)?i.explorerRecommendedWalletIds:[],excludeWalletIds:i.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(i.explorerExcludedWalletIds)?i.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=i.mobileWallets)!=null&&o.length||(a=i.desktopWallets)!=null&&a.length){const u=[...(i.mobileWallets||[]).map(w=>({id:w.id,name:w.name,links:w.links})),...(i.desktopWallets||[]).map(w=>({id:w.id,name:w.name,links:{native:w.links.native,universal:w.links.universal}}))],p=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],g=u.filter(w=>!p.includes(w.id));g.length&&(l.customWallets=g)}return l}function Sd(i){return Id({formatters:void 0,fees:void 0,serializers:void 0},i)}var gS=Object.freeze({__proto__:null,convertWCMToAppKitOptions:fS,defineChain:Sd});const yS=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:nS,OPTIONAL_EVENTS:$d,OPTIONAL_METHODS:Ed,REQUIRED_EVENTS:Ur,REQUIRED_METHODS:Br,default:sn},Symbol.toStringTag,{value:"Module"}));exports.Hash=Iu;exports.abytes=er;exports.aexists=To;exports.ahash=n0;exports.aoutput=$u;exports.concatBytes=w0;exports.createView=p0;exports.index_es=yS;exports.randomBytes=m0;exports.rotr=f0;exports.toBytes=sa;exports.wrapConstructor=Su;