@dcl/blog-site 0.2.2 → 0.2.3-23948667956.commit-cfe47f9

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 (302) hide show
  1. package/assets/QueryClientProvider-mZKMZTwe.js +2 -0
  2. package/assets/RoobertPRO-Bold-DDyOqNrI.woff2 +0 -0
  3. package/assets/SignInRedirect-CXUOqOjy.js +11 -0
  4. package/assets/X-3yocgepi.js +15 -0
  5. package/assets/___vite-browser-external_commonjs-proxy-BqV5D26a.js +1 -0
  6. package/assets/__federation_expose_App-CMGDAIUH.js +1 -0
  7. package/assets/__federation_fn_import-C51lglKS.js +1 -0
  8. package/assets/__federation_shared_@dcl/hooks-Dm9PRmKy.js +535 -0
  9. package/assets/__federation_shared_@dcl/schemas-CVwtHlVJ.js +1 -0
  10. package/assets/__federation_shared_@emotion/react-AmEOkpjC.js +1 -0
  11. package/assets/__federation_shared_@emotion/styled-aZ9bk9Xh.js +1 -0
  12. package/assets/__federation_shared_@reduxjs/toolkit-DIZvwqf7.js +1 -0
  13. package/assets/__federation_shared_decentraland-ui2-KxrbFOTA.js +358 -0
  14. package/assets/__federation_shared_react-B3tlNTLg.js +1 -0
  15. package/assets/__federation_shared_react-dom-CCS4dT_K.js +1 -0
  16. package/assets/__federation_shared_react-redux-Ckcz2edF.js +13 -0
  17. package/assets/__federation_shared_react-router-dom-jUWpDOjR.js +49 -0
  18. package/assets/__federation_shared_viem-Cdp7wK0V.js +2 -0
  19. package/assets/__federation_shared_wagmi-CHWRoybR.js +17 -0
  20. package/assets/__vite-optional-peer-dep_lottie-react_decentraland-ui2-BIHI7g3E.js +1 -0
  21. package/assets/_commonjsHelpers-C4iS2aBk.js +1 -0
  22. package/assets/{add-Dnkf3E3Q.js → add-DHMb_tRw.js} +2 -2
  23. package/assets/all-wallets-Bo3QRxXL.js +6 -0
  24. package/assets/{app-store-C9FH4_zP.js → app-store-BHwDXU8D.js} +2 -2
  25. package/assets/{apple-Dm5w1W69.js → apple-BFX-plRw.js} +2 -2
  26. package/assets/arrow-bottom-Djx9NXV2.js +8 -0
  27. package/assets/{arrow-bottom-circle-Bgw9yiHN.js → arrow-bottom-circle-DcJnW2eo.js} +2 -2
  28. package/assets/arrow-left-BS_dJGSP.js +8 -0
  29. package/assets/arrow-right-B-mwy0Iu.js +8 -0
  30. package/assets/arrow-top-Di1bbZG1.js +8 -0
  31. package/assets/auto-track-pkMvCaah.js +1 -0
  32. package/assets/{bank-qNUWniDB.js → bank-B9SMq-ix.js} +2 -2
  33. package/assets/{basic-DJvhbg9L.js → basic-DijYF-IW.js} +124 -124
  34. package/assets/biconomy-CCw3vtwR.js +1 -0
  35. package/assets/{browser-Du0KKb8R.js → browser-CdKdszu-.js} +2 -2
  36. package/assets/{card-BpDAuOwe.js → card-CQu4Eu8c.js} +2 -2
  37. package/assets/ccip-AgQ5AD9v.js +1 -0
  38. package/assets/chains-D88UzVoE.js +1 -0
  39. package/assets/{checkmark-srdyV91l.js → checkmark-D2vezo75.js} +2 -2
  40. package/assets/{checkmark-bold-BYtPga6u.js → checkmark-bold-DriAapzP.js} +2 -2
  41. package/assets/chevron-bottom-CcFEOVdH.js +8 -0
  42. package/assets/chevron-left-BXS-ybhL.js +8 -0
  43. package/assets/chevron-right-TvO5COya.js +8 -0
  44. package/assets/chevron-top-D84SgxMg.js +8 -0
  45. package/assets/{chrome-store-D-UYtj15.js → chrome-store-rpsfVQln.js} +2 -2
  46. package/assets/{clock-BGyfn2Ix.js → clock-BMJ2gt7b.js} +2 -2
  47. package/assets/close-kAWkeKAP.js +8 -0
  48. package/assets/{coinPlaceholder-o1yCmFLN.js → coinPlaceholder-Dz8MKewa.js} +2 -2
  49. package/assets/common-D37S_OFt.js +1 -0
  50. package/assets/{compass-BrX88OdU.js → compass-BednEqu-.js} +2 -2
  51. package/assets/controller-D0Gc4Hsp.js +2 -0
  52. package/assets/{copy-CGKLgPMf.js → copy-D7rBk-hZ.js} +2 -2
  53. package/assets/core-Bn8Mr-tS.js +907 -0
  54. package/assets/create-submenu-Bu20F8-Z.webp +0 -0
  55. package/assets/createBundlerClient-DhRCLsYO.js +4 -0
  56. package/assets/createClient-C9QPJaZu.js +1 -0
  57. package/assets/cursor-C8UG2IDe.js +3 -0
  58. package/assets/{cursor-transparent--gaS-5ET.js → cursor-transparent-CyP0H3C5.js} +2 -2
  59. package/assets/decimals-B7Pm5rZk.js +1 -0
  60. package/assets/decimals-DedKFk8m.js +1 -0
  61. package/assets/defineChain-7I0Ce1VT.js +1 -0
  62. package/assets/{desktop-D3dzP-FX.js → desktop-LBcRpcZE.js} +2 -2
  63. package/assets/detectExtension-C2uVeK-n.js +1 -0
  64. package/assets/{disconnect-CsHX0nla.js → disconnect-DEBEe-yK.js} +2 -2
  65. package/assets/{discord-TnXCJHRv.js → discord-BlVFKMf0.js} +2 -2
  66. package/assets/emotion-react.browser.esm-BzYQLDSp.js +8 -0
  67. package/assets/emotion-use-insertion-effect-with-fallbacks.browser.esm-TsHx33zg.js +1 -0
  68. package/assets/encode-DvvW4ZKt.js +2 -0
  69. package/assets/engine-CD7SeAap.js +1 -0
  70. package/assets/estimate-gas-CeHGaIbG.js +3 -0
  71. package/assets/estimate-l1-fee-ClMO5l7U.js +1 -0
  72. package/assets/eth_estimateGas-C2ENZ_HR.js +1 -0
  73. package/assets/eth_getStorageAt-BHgF2qz5.js +1 -0
  74. package/assets/eth_getTransactionCount-DWnnw2mX.js +1 -0
  75. package/assets/ethereum-dN7ENYl_.js +1 -0
  76. package/assets/{etherscan-BNOTAlpJ.js → etherscan-C_pqcV9R.js} +2 -2
  77. package/assets/events-B5inrCVE.js +1 -0
  78. package/assets/{exclamation-triangle-3cTnBFEz.js → exclamation-triangle-R9Xq3IaG.js} +2 -2
  79. package/assets/explore-submenu-BFVuYMi9.webp +0 -0
  80. package/assets/{extension-C7i3kBcJ.js → extension-DkA_7Cbg.js} +2 -2
  81. package/assets/external-link-BPOw_fuW.js +8 -0
  82. package/assets/extractIPFS-B4LGER25.js +1 -0
  83. package/assets/{facebook-BtRXxuTh.js → facebook-CMZk_t1A.js} +2 -2
  84. package/assets/{farcaster-DuvCkOsj.js → farcaster-CveILPqa.js} +2 -2
  85. package/assets/fee-data-BKBGP5kG.js +1 -0
  86. package/assets/fetchTokenMetadata-BLDHgO8L.js +2 -0
  87. package/assets/{filters-q4uY0GXA.js → filters-BspTrZpX.js} +2 -2
  88. package/assets/get-ecosystem-wallet-info-D3PrM5FE.js +1 -0
  89. package/assets/getBalance-D7nzATjL.js +2 -0
  90. package/assets/getInstalledModules-Ck_Gj8FO.js +1 -0
  91. package/assets/getNFT-BcCS23O_.js +1 -0
  92. package/assets/getNFT-DXdMP0Q5.js +2 -0
  93. package/assets/{github-DdvkoPeB.js → github-DoFHEMIF.js} +2 -2
  94. package/assets/{google-d4Ql9qix.js → google-NTQi9GVe.js} +2 -2
  95. package/assets/governance-submenu-VTIKvCIL.webp +0 -0
  96. package/assets/{help-circle-BY_Weu8t.js → help-circle-DV0uNPdn.js} +2 -2
  97. package/assets/hex-B0Rx0hII.js +2 -0
  98. package/assets/{id-BJNb6vOI.js → id-UAVc1FOO.js} +1 -1
  99. package/assets/{image-DIsXNsXJ.js → image-BeHBzCPG.js} +2 -2
  100. package/assets/in-app-wallet-calls-CvFtsXP9.js +1 -0
  101. package/assets/index-B2OCb4Ez.js +1 -0
  102. package/assets/index-B65z14KI.js +4 -0
  103. package/assets/index-BAhlRyDG.js +1 -0
  104. package/assets/{index-DOqN8xaU.js → index-BTtTX-5z.js} +1 -1
  105. package/assets/index-BjzJcZq6.js +1 -0
  106. package/assets/index-BjzJcZq6__bundled.js +24 -0
  107. package/assets/index-BozJS3za.js +12 -0
  108. package/assets/index-C05H8NDX.js +1 -0
  109. package/assets/index-C1IoT2if.js +3 -0
  110. package/assets/index-C2hdqzGT.js +2 -0
  111. package/assets/index-CgMDPZul.js +13 -0
  112. package/assets/index-CjuQOkbh.js +2 -0
  113. package/assets/index-CpR9p5nk.js +1 -0
  114. package/assets/index-D1lXZVQu.js +45 -0
  115. package/assets/index-D6ZAha0r.js +395 -0
  116. package/assets/{index-X-a697cI.js → index-DJ7GgcJ9.js} +2 -2
  117. package/assets/index-DajuSfcu.js +2 -0
  118. package/assets/index-DeklogZX.js +1 -0
  119. package/assets/index-DmAaXUNv.js +1 -0
  120. package/assets/index-Dy0yjznp.js +1 -0
  121. package/assets/index-Dy0yjznp__bundled.js +9 -0
  122. package/assets/index-HvoTJwGm.js +1 -0
  123. package/assets/index-MYKNZAUu.js +8 -0
  124. package/assets/index-Tsk25L8E.js +1 -0
  125. package/assets/index.es-C8Kfv-K1.js +11 -0
  126. package/assets/index.es-CAXGMBEH.js +1 -0
  127. package/assets/index.es-D3pP9hN4.js +27 -0
  128. package/assets/index.es-D5YKsq2-.js +2 -0
  129. package/assets/index.umd-DK712HHb.js +1 -0
  130. package/assets/{info-BvPgRaaJ.js → info-CzcA85TO.js} +2 -2
  131. package/assets/{info-circle-sWcom9RD.js → info-circle-D3Mr3R9u.js} +2 -2
  132. package/assets/is-plan-event-enabled-DeNtQvA5.js +1 -0
  133. package/assets/json-BHzNJmTy.js +1 -0
  134. package/assets/jsx-runtime-DncYoG30.js +1 -0
  135. package/assets/jsx-runtime-DncYoG30__bundled.js +9 -0
  136. package/assets/learn-submenu-sfxVP5Db.webp +0 -0
  137. package/assets/{lightbulb-HJchniSu.js → lightbulb-B2FZtM_8.js} +2 -2
  138. package/assets/localBatchGatewayRequest-BIEAG3VG.js +1 -0
  139. package/assets/{mail-DlRijJmV.js → mail-CkhGbows.js} +2 -2
  140. package/assets/marketplace-submenu-CixWTv8_.webp +0 -0
  141. package/assets/{mobile-CoiDw6cg.js → mobile-1H3FtqAS.js} +2 -2
  142. package/assets/{more-LUiRL6x4.js → more-CZiQi624.js} +2 -2
  143. package/assets/{network-placeholder-Cj3jgVfo.js → network-placeholder-DA2bm2rC.js} +2 -2
  144. package/assets/{nftPlaceholder-LkhQmGFs.js → nftPlaceholder-C9t5Ydxp.js} +2 -2
  145. package/assets/off-D8z0OQ3M.js +8 -0
  146. package/assets/op-gas-fee-reducer-CfxMcvXl.js +1 -0
  147. package/assets/openzeppelin-ZKz6sLW9.js +1 -0
  148. package/assets/ownerOf-D1aXOt9Q.js +1 -0
  149. package/assets/parseNft-LjEwmOst.js +2 -0
  150. package/assets/passkeys-CTJ4NPfL.js +1 -0
  151. package/assets/{play-store-DBit2AoS.js → play-store-_X5LrPwx.js} +2 -2
  152. package/assets/{plus-CZe-WgSN.js → plus-JriDhMxt.js} +2 -2
  153. package/assets/preload-helper-BorDCKdG.js +1 -0
  154. package/assets/publicKeyToAddress-CxEKPAKT.js +1 -0
  155. package/assets/{qr-code-BhW7ZXY-.js → qr-code-DaB080BF.js} +2 -2
  156. package/assets/{qr-overlay-DsRPQv6v.js → qr-overlay-CGnFhcTk.js} +1 -1
  157. package/assets/{recycle-horizontal-DBnWoDRV.js → recycle-horizontal-CGeFmMrT.js} +2 -2
  158. package/assets/redux-BNDF-Lt-.js +1 -0
  159. package/assets/{refresh-qvocxvcf.js → refresh-Dgvxxw5C.js} +2 -2
  160. package/assets/remoteEntry.js +1 -0
  161. package/assets/{reown-logo-C-45v-AJ.js → reown-logo-CBX48aN9.js} +2 -2
  162. package/assets/resolveImplementation-Cb2bL1tx.js +1 -0
  163. package/assets/rich-text-react-renderer.es5-D_tE7AHo.js +2 -0
  164. package/assets/rpc-ti0b0r_u.js +3 -0
  165. package/assets/search-DamXBOxM.js +8 -0
  166. package/assets/secp256k1-UEF-yOzn.js +1 -0
  167. package/assets/{send-DI2x4DfJ.js → send-BLpUSx_G.js} +2 -2
  168. package/assets/send-batch-transaction-DnH876GL.js +1 -0
  169. package/assets/send-eip712-transaction-D_FU-Avh.js +2 -0
  170. package/assets/send-gasless-transaction-MP1Q_mLW.js +2 -0
  171. package/assets/serializeTransaction-mtsVBaO6.js +1 -0
  172. package/assets/session-proposal-CM3P7DaL.js +1 -0
  173. package/assets/session-request-Dqw67u3p.js +2 -0
  174. package/assets/sha256-DYtpy1Qz.js +1 -0
  175. package/assets/signing-BFeVjjPi.js +5 -0
  176. package/assets/store-DOLZnwHk.js +1 -0
  177. package/assets/{swapHorizontal-eTjjU7d8.js → swapHorizontal-Br-MZ1tO.js} +2 -2
  178. package/assets/{swapHorizontalBold-B86nJTAP.js → swapHorizontalBold-CkUNbZ1G.js} +2 -2
  179. package/assets/{swapHorizontalMedium-CNT7ELrN.js → swapHorizontalMedium-D3qEQNb5.js} +2 -2
  180. package/assets/{swapHorizontalRoundedBold-R_inXmIh.js → swapHorizontalRoundedBold-CzzBPCtt.js} +2 -2
  181. package/assets/{swapVertical-DBChOUj8.js → swapVertical-Mrn3zm_W.js} +2 -2
  182. package/assets/{telegram-DjYbgHgS.js → telegram-ZTLC9FiA.js} +2 -2
  183. package/assets/thirdweb-CHfVLLbM.js +1 -0
  184. package/assets/thirdweb-D5ezTmuN.js +27 -0
  185. package/assets/{three-dots-VoULPGrI.js → three-dots-DYl4uQjm.js} +2 -2
  186. package/assets/totalSupply-B5jHW8gx.js +1 -0
  187. package/assets/tslib.es6-DbvBTznf.js +1 -0
  188. package/assets/{twitch-ETBgqGHE.js → twitch-DPLkA98Q.js} +2 -2
  189. package/assets/{twitterIcon-N584dzfh.js → twitterIcon-BEY_UAyG.js} +2 -2
  190. package/assets/uid-D00jCazq.js +44 -0
  191. package/assets/{uint8-array-CjVHUazS.js → uint8-array-DZKEMhA1.js} +1 -1
  192. package/assets/utils-C7urdXtO.js +2 -0
  193. package/assets/utils-CozXUO91.js +1 -0
  194. package/assets/{verify-Dp4bztGk.js → verify-DuPdiufm.js} +2 -2
  195. package/assets/{verify-filled-B7WhO3Kn.js → verify-filled-CdqEW5AP.js} +2 -2
  196. package/assets/{w3m-modal-BmEHfmEu.js → w3m-modal-BLzhBUlF.js} +34 -34
  197. package/assets/wait-for-tx-receipt-B-o5aPQ8.js +1 -0
  198. package/assets/{wallet-tXSvlbUa.js → wallet-CZw1g3L8.js} +2 -2
  199. package/assets/{wallet-placeholder-B2e9Wl_u.js → wallet-placeholder-OAkoJuru.js} +2 -2
  200. package/assets/{walletconnect-D70wSjLs.js → walletconnect-BJ3w7-IU.js} +4 -4
  201. package/assets/wallets-Q5RcRyG6.js +16 -0
  202. package/assets/{warning-circle-CsTkZ4Rl.js → warning-circle-DpDeOZKv.js} +2 -2
  203. package/assets/web-connector-CB7tpRui.js +9 -0
  204. package/assets/webSocket-dQW3n9NM.js +3 -0
  205. package/assets/withCache-DYumIHzL.js +1 -0
  206. package/assets/{x-DwOCQuex.js → x-liJqLZUi.js} +2 -2
  207. package/assets/zora-sepolia-DNJ2DQat.js +1 -0
  208. package/index.html +17 -3
  209. package/package.json +3 -3
  210. package/assets/RoobertPRO-Bold-BLoSpx-h.otf +0 -0
  211. package/assets/all-wallets-C5N9p7Oh.js +0 -6
  212. package/assets/arrow-bottom-CXaxVEeb.js +0 -8
  213. package/assets/arrow-left-pgI3hg3C.js +0 -8
  214. package/assets/arrow-right-CyKp2yFa.js +0 -8
  215. package/assets/arrow-top-B2waxVPx.js +0 -8
  216. package/assets/auto-track-BvFI9h3i.js +0 -1
  217. package/assets/biconomy-DZsFbmF0.js +0 -1
  218. package/assets/ccip-CpLmER95.js +0 -1
  219. package/assets/chains-BJ1WS73W.js +0 -1
  220. package/assets/chevron-bottom-C2aa3E9i.js +0 -8
  221. package/assets/chevron-left-jGoftk_A.js +0 -8
  222. package/assets/chevron-right-Dt6SfcNy.js +0 -8
  223. package/assets/chevron-top-CBCgyIVe.js +0 -8
  224. package/assets/close-BQpWkcd5.js +0 -8
  225. package/assets/common-B5-2TPMC.js +0 -1
  226. package/assets/controller-BW9fJMCh.js +0 -2
  227. package/assets/core-f4taWsy5.js +0 -908
  228. package/assets/create-submenu-DEFVbrc5.png +0 -0
  229. package/assets/createBundlerClient-r1Kofl9Y.js +0 -8
  230. package/assets/cursor-l_ly71I2.js +0 -3
  231. package/assets/decimals-BB5yEnWu.js +0 -1
  232. package/assets/decimals-D7yTLBH-.js +0 -1
  233. package/assets/detectExtension-BOyq5ueD.js +0 -1
  234. package/assets/engine-COatTZhI.js +0 -1
  235. package/assets/estimate-l1-fee-gm3XrWSf.js +0 -1
  236. package/assets/eth_estimateGas-A6ba-Fl3.js +0 -1
  237. package/assets/eth_getStorageAt-DiqyV3Wq.js +0 -1
  238. package/assets/eth_getTransactionCount-CF50onAO.js +0 -1
  239. package/assets/ethereum-Bb-GI0c-.js +0 -1
  240. package/assets/events-CjOrSHaz.js +0 -1
  241. package/assets/explore-submenu-KVl6Dc-h.png +0 -0
  242. package/assets/external-link-C6RRSRES.js +0 -8
  243. package/assets/extractIPFS-BchHnCEN.js +0 -1
  244. package/assets/fetchTokenMetadata-ClRC5ORW.js +0 -2
  245. package/assets/get-ecosystem-wallet-info-C2CJ_2OU.js +0 -1
  246. package/assets/getBalance-DGuxWuYL.js +0 -1
  247. package/assets/getInstalledModules-A3tAP18V.js +0 -1
  248. package/assets/getNFT-C7cllYFm.js +0 -1
  249. package/assets/getNFT-CQKD7QHk.js +0 -2
  250. package/assets/governance-submenu-CXxLX9nT.png +0 -0
  251. package/assets/hashTypedData-7WNMs5EV.js +0 -1
  252. package/assets/in-app-wallet-calls-CIRR0eJZ.js +0 -1
  253. package/assets/index-B1P0UjN9.js +0 -1
  254. package/assets/index-BNdVKnva.js +0 -2
  255. package/assets/index-BtvcwkC4.js +0 -1
  256. package/assets/index-C3CMrfih.js +0 -1
  257. package/assets/index-C8ynIJrk.js +0 -395
  258. package/assets/index-Ca6sys5l.js +0 -3
  259. package/assets/index-CvqvWWYJ.js +0 -2
  260. package/assets/index-CxA55UWl.js +0 -1
  261. package/assets/index-D-W42D03.js +0 -12
  262. package/assets/index-DC9TKWAz.js +0 -23
  263. package/assets/index-DFfsl0Io.js +0 -4
  264. package/assets/index-DN2JqH-l.js +0 -895
  265. package/assets/index-DfqIHbWG.js +0 -2
  266. package/assets/index-pQ6ZXw4u.js +0 -13
  267. package/assets/index-qMD90g0X.js +0 -1
  268. package/assets/index.es-B2O4h03u.js +0 -12
  269. package/assets/index.es-BEAksKXY.js +0 -2
  270. package/assets/index.es-Dxxm_SKC.js +0 -1
  271. package/assets/index.es-MXG0VeeZ.js +0 -27
  272. package/assets/index.umd-DvfMpbcY.js +0 -1
  273. package/assets/is-plan-event-enabled-DS1Agtkw.js +0 -1
  274. package/assets/learn-submenu-Xs1jOwfy.png +0 -0
  275. package/assets/localBatchGatewayRequest-CHeIulW5.js +0 -1
  276. package/assets/marketplace-submenu-CjxTqNhj.png +0 -0
  277. package/assets/off-BCDn43Xl.js +0 -8
  278. package/assets/openzeppelin-_xpy9vRo.js +0 -1
  279. package/assets/ownerOf-ClSM4brX.js +0 -1
  280. package/assets/parseNft-BmEusGKu.js +0 -2
  281. package/assets/passkeys-CqFedyqV.js +0 -1
  282. package/assets/resolveImplementation-BssH7H5b.js +0 -1
  283. package/assets/rpc-DMtarHL0.js +0 -3
  284. package/assets/search-CAzZVrZw.js +0 -8
  285. package/assets/secp256k1-C_4ya0Qz.js +0 -1
  286. package/assets/secp256k1-CnKxz2gu.js +0 -1
  287. package/assets/secp256k1-oGq0B4P7.js +0 -1
  288. package/assets/send-batch-transaction-DfUNUZ4Z.js +0 -1
  289. package/assets/send-eip712-transaction-Ro5QmOlW.js +0 -2
  290. package/assets/send-gasless-transaction-B-Uu5KdW.js +0 -2
  291. package/assets/session-proposal-CRjqbz7W.js +0 -1
  292. package/assets/session-request-BI3BlMfs.js +0 -2
  293. package/assets/sha256-ChRob2fv.js +0 -1
  294. package/assets/signing-B1K_Jdsm.js +0 -30
  295. package/assets/thirdweb-0Fl_ECmE.js +0 -27
  296. package/assets/thirdweb-DZ2vK6IO.js +0 -1
  297. package/assets/totalSupply-ClM38QOc.js +0 -1
  298. package/assets/utils-B3vUvlNq.js +0 -1
  299. package/assets/wait-for-tx-receipt-pc2BJc62.js +0 -1
  300. package/assets/wallets-Dj6CY1yi.js +0 -17
  301. package/assets/web-connector-CiZO9RvI.js +0 -9
  302. package/assets/zora-sepolia-CZ4Tf1UH.js +0 -1
@@ -1,12 +0,0 @@
1
- const __vite__fileDeps=["assets/secp256k1-oGq0B4P7.js","assets/index-DN2JqH-l.js","assets/events-CjOrSHaz.js","assets/index.es-MXG0VeeZ.js","assets/index-nibyPLVP.js","assets/index.es-BEAksKXY.js","assets/core-f4taWsy5.js"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]);
2
- import{g as pa}from"./index-DN2JqH-l.js";import{e as $t,k as Fr}from"./events-CjOrSHaz.js";import{b as ln,g as Qc,c as N,a as pi,C as Yc,d as da,e as Zc,f as Xc,s as gr,h as ss,i as Is,j as Gr,I as vi,k as Ns,A as eh,E as Pe,l as th,y as ke,m as jt,r as Ei,B as Wr,o as ze,n as ih,p as Jr,q as Qr,t as Rs,P as un,Q as sh,u as rh,v as ai,w as ga,x as ut,z as it,D as mt}from"./index.es-MXG0VeeZ.js";import{c as nh,a as oh,k as ah,d as ch,s as hh,g as pn}from"./index-nibyPLVP.js";import{f as Qe}from"./index.es-BEAksKXY.js";function Ki(i,{strict:e=!0}={}){return!i||typeof i!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(i):i.startsWith("0x")}function dn(i){return Ki(i,{strict:!1})?Math.ceil((i.length-2)/2):i.length}const fa="2.23.2";let xi={getDocsUrl:({docsBaseUrl:i,docsPath:e="",docsSlug:t})=>e?`${i??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${fa}`};class Ut extends Error{constructor(e,t={}){var a;const s=(()=>{var c;return t.cause instanceof Ut?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),r=t.cause instanceof Ut&&t.cause.docsPath||t.docsPath,n=(a=xi.getDocsUrl)==null?void 0:a.call(xi,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...s?[`Details: ${s}`]:[],...xi.version?[`Version: ${xi.version}`]:[]].join(`
3
- `);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=fa}walk(e){return ya(this,e)}}function ya(i,e){return e!=null&&e(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?ya(i.cause,e):e?null:i}class ma extends Ut{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 Ii(i,{dir:e,size:t=32}={}){return typeof i=="string"?lh(i,{dir:e,size:t}):uh(i,{dir:e,size:t})}function lh(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new ma({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function uh(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new ma({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 ph extends Ut{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 dh extends Ut{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function _i(i,{size:e}){if(dn(i)>e)throw new dh({givenSize:dn(i),maxSize:e})}function fr(i,e={}){const{signed:t}=e;e.size&&_i(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 gh(i,e={}){return Number(fr(i,e))}const fh=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function yr(i,e={}){return typeof i=="number"||typeof i=="bigint"?ba(i,e):typeof i=="string"?wh(i,e):typeof i=="boolean"?yh(i,e):wa(i,e)}function yh(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?(_i(t,{size:e.size}),Ii(t,{size:e.size})):t}function wa(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=fh[i[r]];const s=`0x${t}`;return typeof e.size=="number"?(_i(s,{size:e.size}),Ii(s,{dir:"right",size:e.size})):s}function ba(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 ph({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?Ii(a,{size:s}):a}const mh=new TextEncoder;function wh(i,e={}){const t=mh.encode(i);return wa(t,e)}const bh=new TextEncoder;function vh(i,e={}){return typeof i=="number"||typeof i=="bigint"?Ih(i,e):typeof i=="boolean"?Eh(i,e):Ki(i)?va(i,e):Ea(i,e)}function Eh(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?(_i(t,{size:e.size}),Ii(t,{size:e.size})):t}const ht={zero:48,nine:57,A:65,F:70,a:97,f:102};function gn(i){if(i>=ht.zero&&i<=ht.nine)return i-ht.zero;if(i>=ht.A&&i<=ht.F)return i-(ht.A-10);if(i>=ht.a&&i<=ht.f)return i-(ht.a-10)}function va(i,e={}){let t=i;e.size&&(_i(t,{size:e.size}),t=Ii(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=gn(s.charCodeAt(a++)),h=gn(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new Ut(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function Ih(i,e){const t=ba(i,e);return va(t)}function Ea(i,e={}){const t=bh.encode(i);return typeof e.size=="number"?(_i(t,{size:e.size}),Ii(t,{dir:"right",size:e.size})):t}function _s(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function _h(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ts(i,...e){if(!_h(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 Vv(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");_s(i.outputLen),_s(i.blockLen)}function fn(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 Ph(i,e){Ts(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const rs=BigInt(2**32-1),yn=BigInt(32);function $h(i,e=!1){return e?{h:Number(i&rs),l:Number(i>>yn&rs)}:{h:Number(i>>yn&rs)|0,l:Number(i&rs)|0}}function Sh(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}=$h(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Oh=(i,e,t)=>i<<t|e>>>32-t,xh=(i,e,t)=>e<<t|i>>>32-t,Ah=(i,e,t)=>e<<t-32|i>>>64-t,Ch=(i,e,t)=>i<<t-32|e>>>64-t,Vt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Nh(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Hv(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Fv(i,e){return i<<32-e|i>>>e}const mn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Rh(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function wn(i){for(let e=0;e<i.length;e++)i[e]=Rh(i[e])}function Th(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function Ia(i){return typeof i=="string"&&(i=Th(i)),Ts(i),i}function Gv(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Ts(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 qh{clone(){return this._cloneInto()}}function jh(i){const e=s=>i().update(Ia(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Wv(i=32){if(Vt&&typeof Vt.getRandomValues=="function")return Vt.getRandomValues(new Uint8Array(i));if(Vt&&typeof Vt.randomBytes=="function")return Vt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const _a=[],Pa=[],$a=[],Dh=BigInt(0),Ai=BigInt(1),kh=BigInt(2),Uh=BigInt(7),Mh=BigInt(256),Lh=BigInt(113);for(let i=0,e=Ai,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],_a.push(2*(5*s+t)),Pa.push((i+1)*(i+2)/2%64);let r=Dh;for(let n=0;n<7;n++)e=(e<<Ai^(e>>Uh)*Lh)%Mh,e&kh&&(r^=Ai<<(Ai<<BigInt(n))-Ai);$a.push(r)}const[Bh,zh]=Sh($a,!0),bn=(i,e,t)=>t>32?Ah(i,e,t):Oh(i,e,t),vn=(i,e,t)=>t>32?Ch(i,e,t):xh(i,e,t);function Kh(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=bn(h,l,1)^t[a],p=vn(h,l,1)^t[a+1];for(let d=0;d<50;d+=10)i[o+d]^=u,i[o+d+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Pa[o],c=bn(r,n,a),h=vn(r,n,a),l=_a[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]^=Bh[s],i[1]^=zh[s]}t.fill(0)}class Yr extends qh{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,_s(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Nh(this.state)}keccak(){mn||wn(this.state32),Kh(this.state32,this.rounds),mn||wn(this.state32),this.posOut=0,this.pos=0}update(e){fn(this);const{blockLen:t,state:s}=this;e=Ia(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&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){fn(this,!1),Ts(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 _s(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ph(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 Yr(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 Vh=(i,e,t)=>jh(()=>new Yr(e,i,t)),Hh=Vh(1,136,256/8);function Sa(i,e){const t=e||"hex",s=Hh(Ki(i,{strict:!1})?vh(i):i);return t==="bytes"?s:yr(s)}class Fh 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 Ks=new Fh(8192);function Gh(i,e){if(Ks.has(`${i}.${e}`))return Ks.get(`${i}.${e}`);const t=i.substring(2).toLowerCase(),s=Sa(Ea(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 Ks.set(`${i}.${e}`,n),n}function Wh(i){const e=Sa(`0x${i.substring(4)}`).substring(26);return Gh(`0x${e}`)}async function Jh({hash:i,signature:e}){const t=Ki(i)?i:yr(i),{secp256k1:s}=await pa(async()=>{const{secp256k1:o}=await import("./secp256k1-oGq0B4P7.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3,4,5]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:u,yParity:p}=e,d=Number(p??u),g=En(d);return new s.Signature(fr(h),fr(l)).addRecoveryBit(g)}const o=Ki(e)?e:yr(e),a=gh(`0x${o.slice(130)}`),c=En(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function En(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 Qh({hash:i,signature:e}){return Wh(await Jh({hash:i,signature:e}))}function Yh(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 d=h.length;for(;p!==d&&h[p]===0;)p++,l++;const g=(d-p)*n+1>>>0,y=new Uint8Array(g);for(;p!==d;){let m=h[p],b=0;for(let I=g-1;(m!==0||b<u)&&I!==-1;I--,b++)m+=256*y[I]>>>0,y[I]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");u=b,p++}let f=g-u;for(;f!==g&&y[f]===0;)f++;let w=s.repeat(l);for(;f<g;++f)w+=i.charAt(y[f]);return w}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 d=(h.length-l)*r+1>>>0,g=new Uint8Array(d);for(;l<h.length;){const m=h.charCodeAt(l);if(m>255)return;let b=e[m];if(b===255)return;let I=0;for(let A=d-1;(b!==0||I<p)&&A!==-1;A--,I++)b+=t*g[A]>>>0,g[A]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");p=I,l++}let y=d-p;for(;y!==d&&g[y]===0;)y++;const f=new Uint8Array(u+(d-y));let w=u;for(;y!==d;)f[w++]=g[y++];return f}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 Zh="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Xh=Yh(Zh);function Oa(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Mi(i,e){e||(e=i.reduce((r,n)=>r+n.length,0));const t=Oa(e);let s=0;for(const r of i)t.set(r,s),s+=r.length;return t}function xa(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const In=xa("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Vs=xa("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=Oa(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),Aa={utf8:In,"utf-8":In,hex:ln.base16,latin1:Vs,ascii:Vs,binary:Vs,...ln};function Be(i,e="utf8"){const t=Aa[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}`)}function Ae(i,e="utf8"){const t=Aa[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.buffer,i.byteOffset,i.byteLength).toString("utf8"):t.encoder.encode(i).substring(1)}var el={};const tl=":";function ui(i){const[e,t]=i.split(tl);return{namespace:e,reference:t}}function _n(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 Ca(i,e){return i.includes(":")?[i]:e.chains||[]}var il=Object.defineProperty,sl=Object.defineProperties,rl=Object.getOwnPropertyDescriptors,Pn=Object.getOwnPropertySymbols,nl=Object.prototype.hasOwnProperty,ol=Object.prototype.propertyIsEnumerable,$n=(i,e,t)=>e in i?il(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Sn=(i,e)=>{for(var t in e||(e={}))nl.call(e,t)&&$n(i,t,e[t]);if(Pn)for(var t of Pn(e))ol.call(e,t)&&$n(i,t,e[t]);return i},al=(i,e)=>sl(i,rl(e));const cl="ReactNative",je={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},hl="js";function Ps(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function St(){return!pi()&&!!da()&&navigator.product===cl}function ll(){return St()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function ul(){return St()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Pi(){return!Ps()&&!!da()&&!!pi()}function Ji(){return St()?je.reactNative:Ps()?je.node:Pi()?je.browser:je.unknown}function On(){var i;try{return St()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(i=global.Application)==null?void 0:i.applicationId:void 0}catch{return}}function pl(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 dl(i){var e,t;const s=Na();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==null?void 0:i.icons)!=null&&e.length&&i.icons.length>0&&(i.icons=i.icons.filter(r=>r!=="")),al(Sn(Sn({},s),i),{url:(i==null?void 0:i.url)||s.url,name:(i==null?void 0:i.name)||s.name,description:(i==null?void 0:i.description)||s.description,icons:(t=i==null?void 0: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 Na(){return Qc()||{name:"",description:"",url:"",icons:[""]}}function gl(){if(Ji()===je.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:t,Version:s}=global.Platform;return[t,s].join("-")}const i=Zc();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 fl(){var i;const e=Ji();return e===je.browser?[e,((i=Xc())==null?void 0:i.host)||"unknown"].join(":"):e}function Ra(i,e,t){const s=gl(),r=fl();return[[i,e].join("-"),[hl,t].join("-"),s,r].join("/")}function yl({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Ra(i,e,s),u={auth:r,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=pl(h[1]||"",u);return h[0]+"?"+p}function Dt(i,e){return i.filter(t=>e.includes(t)).length===i.length}function mr(i){return Object.fromEntries(i.entries())}function wr(i){return new Map(Object.entries(i))}function Ct(i=N.FIVE_MINUTES,e){const t=N.toMiliseconds(i||N.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 It(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 Ta(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 ml(i){return Ta("topic",i)}function wl(i){return Ta("id",i)}function qa(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 ae(i,e){return N.fromMiliseconds(Date.now()+N.toMiliseconds(i))}function vt(i){return Date.now()>=N.toMiliseconds(i)}function W(i,e){return`${i}${e?`:${e}`:""}`}function rt(i=[],e=[]){return[...new Set([...i,...e])]}async function bl({id:i,topic:e,wcDeepLink:t}){var s;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=vl(n,i,e),a=Ji();if(a===je.browser){if(!((s=pi())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}El(o)}else a===je.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(r){console.error(r)}}function vl(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}${$l(s,!0)}`}else r=`${r}/wc?${s}`;return r}function El(i){let e="_self";Pl()?e="_top":(_l()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function Il(i,e){let t="";try{if(Pi()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function xn(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function An(){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 Zr(){return typeof process<"u"&&el.IS_VITEST==="true"}function _l(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Pl(){try{return window.self!==window.top}catch{return!1}}function $l(i,e=!1){const t=Buffer.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function ja(i){return Buffer.from(i,"base64").toString("utf-8")}function Sl(i){return new Promise(e=>setTimeout(e,i))}function Vi(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Ol(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Qi(i,...e){if(!Ol(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 Xr(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Vi(i.outputLen),Vi(i.blockLen)}function di(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 Da(i,e){Qi(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ns=BigInt(2**32-1),Cn=BigInt(32);function xl(i,e=!1){return e?{h:Number(i&ns),l:Number(i>>Cn&ns)}:{h:Number(i>>Cn&ns)|0,l:Number(i&ns)|0}}function Al(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}=xl(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Cl=(i,e,t)=>i<<t|e>>>32-t,Nl=(i,e,t)=>e<<t|i>>>32-t,Rl=(i,e,t)=>e<<t-32|i>>>64-t,Tl=(i,e,t)=>i<<t-32|e>>>64-t,Ht=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ql(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Hs(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Ze(i,e){return i<<32-e|i>>>e}const Nn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function jl(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Rn(i){for(let e=0;e<i.length;e++)i[e]=jl(i[e])}function Dl(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function gi(i){return typeof i=="string"&&(i=Dl(i)),Qi(i),i}function kl(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Qi(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 en=class{clone(){return this._cloneInto()}};function ka(i){const e=s=>i().update(gi(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function $i(i=32){if(Ht&&typeof Ht.getRandomValues=="function")return Ht.getRandomValues(new Uint8Array(i));if(Ht&&typeof Ht.randomBytes=="function")return Ht.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Ua=[],Ma=[],La=[],Ul=BigInt(0),Ci=BigInt(1),Ml=BigInt(2),Ll=BigInt(7),Bl=BigInt(256),zl=BigInt(113);for(let i=0,e=Ci,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Ua.push(2*(5*s+t)),Ma.push((i+1)*(i+2)/2%64);let r=Ul;for(let n=0;n<7;n++)e=(e<<Ci^(e>>Ll)*zl)%Bl,e&Ml&&(r^=Ci<<(Ci<<BigInt(n))-Ci);La.push(r)}const[Kl,Vl]=Al(La,!0),Tn=(i,e,t)=>t>32?Rl(i,e,t):Cl(i,e,t),qn=(i,e,t)=>t>32?Tl(i,e,t):Nl(i,e,t);function Hl(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=Tn(h,l,1)^t[a],p=qn(h,l,1)^t[a+1];for(let d=0;d<50;d+=10)i[o+d]^=u,i[o+d+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Ma[o],c=Tn(r,n,a),h=qn(r,n,a),l=Ua[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]^=Kl[s],i[1]^=Vl[s]}t.fill(0)}let Fl=class Ba extends en{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,Vi(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=ql(this.state)}keccak(){Nn||Rn(this.state32),Hl(this.state32,this.rounds),Nn||Rn(this.state32),this.posOut=0,this.pos=0}update(e){di(this);const{blockLen:t,state:s}=this;e=gi(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&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){di(this,!1),Qi(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 Vi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Da(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 Ba(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 Gl=(i,e,t)=>ka(()=>new Fl(e,i,t)),Wl=Gl(1,136,256/8),Jl="https://rpc.walletconnect.org/v1";function za(i){const e=`Ethereum Signed Message:
4
- ${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+Buffer.from(Wl(t)).toString("hex")}async function Ql(i,e,t,s,r,n){switch(t.t){case"eip191":return await Yl(i,e,t.s);case"eip1271":return await Zl(i,e,t.s,s,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function Yl(i,e,t){return(await Qh({hash:za(e),signature:t})).toLowerCase()===i.toLowerCase()}async function Zl(i,e,t,s,r,n){const o=ui(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=za(e).substring(2),p=a+u+c+h+l,d=await fetch(`${n||Jl}/?chainId=${s}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:Xl(),jsonrpc:"2.0",method:"eth_call",params:[{to:i,data:p},"latest"]})}),{result:g}=await d.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Xl(){return Date.now()+Math.floor(Math.random()*1e3)}function eu(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=Buffer.from(i,"base64").slice(1,65);return Xh.encode(n)}var tu=Object.defineProperty,iu=Object.defineProperties,su=Object.getOwnPropertyDescriptors,jn=Object.getOwnPropertySymbols,ru=Object.prototype.hasOwnProperty,nu=Object.prototype.propertyIsEnumerable,Dn=(i,e,t)=>e in i?tu(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ou=(i,e)=>{for(var t in e||(e={}))ru.call(e,t)&&Dn(i,t,e[t]);if(jn)for(var t of jn(e))nu.call(e,t)&&Dn(i,t,e[t]);return i},au=(i,e)=>iu(i,su(e));const cu="did:pkh:",tn=i=>i==null?void 0:i.split(":"),hu=i=>{const e=i&&tn(i);if(e)return i.includes(cu)?e[3]:e[1]},br=i=>{const e=i&&tn(i);if(e)return e[2]+":"+e[3]},$s=i=>{const e=i&&tn(i);if(e)return e.pop()};async function kn(i){const{cacao:e,projectId:t}=i,{s,p:r}=e,n=Ka(r,r.iss),o=$s(r.iss);return await Ql(o,n,s,br(r.iss),t)}const Ka=(i,e)=>{const t=`${i.domain} wants you to sign in with your Ethereum account:`,s=$s(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: ${hu(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,d=i.resources?`Resources:${i.resources.map(y=>`
5
- - ${y}`).join("")}`:void 0,g=ys(i.resources);if(g){const y=Hi(g);r=wu(r,y)}return[t,s,"",r,"",n,o,a,c,h,l,u,p,d].filter(y=>y!=null).join(`
6
- `)};function lu(i){return Buffer.from(JSON.stringify(i)).toString("base64")}function uu(i){return JSON.parse(Buffer.from(i,"base64").toString("utf-8"))}function Mt(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 pu(i,e,t,s={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[i]:du(e,t,s)}}}function du(i,e,t={}){e=e==null?void 0:e.sort((r,n)=>r.localeCompare(n));const s=e.map(r=>({[`${i}/${r}`]:[t]}));return Object.assign({},...s)}function Va(i){return Mt(i),`urn:recap:${lu(i).replace(/=/g,"")}`}function Hi(i){const e=uu(i.replace("urn:recap:",""));return Mt(e),e}function gu(i,e,t){const s=pu(i,e,t);return Va(s)}function fu(i){return i&&i.includes("urn:recap:")}function yu(i,e){const t=Hi(i),s=Hi(e),r=mu(t,s);return Va(r)}function mu(i,e){Mt(i),Mt(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]=au(ou({},s.att[r]),{[a]:((c=i.att[r])==null?void 0:c[a])||((h=e.att[r])==null?void 0:h[a])})})}),s}function wu(i="",e){Mt(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 Un(i){var e;const t=Hi(i);Mt(t);const s=(e=t.att)==null?void 0:e.eip155;return s?Object.keys(s).map(r=>r.split("/")[1]):[]}function Mn(i){const e=Hi(i);Mt(e);const t=[];return Object.values(e.att).forEach(s=>{Object.values(s).forEach(r=>{var n;(n=r==null?void 0:r[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function ys(i){if(!i)return;const e=i==null?void 0:i[i.length-1];return fu(e)?e:void 0}function Fs(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Ha(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function qe(i,...e){if(!Ha(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 Ln(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 bu(i,e){qe(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Bn(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const _t=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),vu=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Eu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Eu)throw new Error("Non little-endian hardware is not supported");function Iu(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function vr(i){if(typeof i=="string")i=Iu(i);else if(Ha(i))i=Er(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function _u(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function Pu(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 $u=(i,e)=>{function t(s,...r){if(qe(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?qe(h):qe(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&qe(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");qe(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,qe(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(qe(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 zn(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&&!Su(e))throw new Error("invalid output, must be aligned");return e}function Kn(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 Su(i){return i.byteOffset%4===0}function Er(i){return Uint8Array.from(i)}function fi(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const Fa=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),Ou=Fa("expand 16-byte k"),xu=Fa("expand 32-byte k"),Au=_t(Ou),Cu=_t(xu);function V(i,e){return i<<e|i>>>32-e}function Ir(i){return i.byteOffset%4===0}const os=64,Nu=16,Ga=2**32-1,Vn=new Uint32Array;function Ru(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(os),l=_t(h),u=Ir(r)&&Ir(n),p=u?_t(r):Vn,d=u?_t(n):Vn;for(let g=0;g<c;o++){if(i(e,t,s,l,o,a),o>=Ga)throw new Error("arx: counter overflow");const y=Math.min(os,c-g);if(u&&y===os){const f=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,m;w<Nu;w++)m=f+w,d[m]=p[m]^l[w];g+=os;continue}for(let f=0,w;f<y;f++)w=g+f,n[w]=r[w]^h[f];g+=y}}function Tu(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=_u({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return Fs(r),Fs(o),Bn(n),Bn(t),(a,c,h,l,u=0)=>{qe(a),qe(c),qe(h);const p=h.length;if(l===void 0&&(l=new Uint8Array(p)),qe(l),Fs(u),u<0||u>=Ga)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const d=[];let g=a.length,y,f;if(g===32)d.push(y=Er(a)),f=Cu;else if(g===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),f=Au,d.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Ir(c)||d.push(c=Er(c));const w=_t(y);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(f,w,_t(c.subarray(0,16)),w),c=c.subarray(16)}const m=16-r;if(m!==c.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const I=new Uint8Array(12);I.set(c,n?0:12-c.length),c=I,d.push(c)}const b=_t(c);return Ru(i,f,w,b,h,l,u,o),fi(...d),l}}const fe=(i,e)=>i[e++]&255|(i[e++]&255)<<8;class qu{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=vr(e),qe(e,32);const t=fe(e,0),s=fe(e,2),r=fe(e,4),n=fe(e,6),o=fe(e,8),a=fe(e,10),c=fe(e,12),h=fe(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]=fe(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],d=o[6],g=o[7],y=o[8],f=o[9],w=fe(e,t+0),m=fe(e,t+2),b=fe(e,t+4),I=fe(e,t+6),A=fe(e,t+8),P=fe(e,t+10),S=fe(e,t+12),R=fe(e,t+14);let v=n[0]+(w&8191),k=n[1]+((w>>>13|m<<3)&8191),q=n[2]+((m>>>10|b<<6)&8191),D=n[3]+((b>>>7|I<<9)&8191),M=n[4]+((I>>>4|A<<12)&8191),_=n[5]+(A>>>1&8191),x=n[6]+((A>>>14|P<<2)&8191),O=n[7]+((P>>>11|S<<5)&8191),T=n[8]+((S>>>8|R<<8)&8191),j=n[9]+(R>>>5|r),$=0,U=$+v*a+k*(5*f)+q*(5*y)+D*(5*g)+M*(5*d);$=U>>>13,U&=8191,U+=_*(5*p)+x*(5*u)+O*(5*l)+T*(5*h)+j*(5*c),$+=U>>>13,U&=8191;let L=$+v*c+k*a+q*(5*f)+D*(5*y)+M*(5*g);$=L>>>13,L&=8191,L+=_*(5*d)+x*(5*p)+O*(5*u)+T*(5*l)+j*(5*h),$+=L>>>13,L&=8191;let B=$+v*h+k*c+q*a+D*(5*f)+M*(5*y);$=B>>>13,B&=8191,B+=_*(5*g)+x*(5*d)+O*(5*p)+T*(5*u)+j*(5*l),$+=B>>>13,B&=8191;let Z=$+v*l+k*h+q*c+D*a+M*(5*f);$=Z>>>13,Z&=8191,Z+=_*(5*y)+x*(5*g)+O*(5*d)+T*(5*p)+j*(5*u),$+=Z>>>13,Z&=8191;let G=$+v*u+k*l+q*h+D*c+M*a;$=G>>>13,G&=8191,G+=_*(5*f)+x*(5*y)+O*(5*g)+T*(5*d)+j*(5*p),$+=G>>>13,G&=8191;let ie=$+v*p+k*u+q*l+D*h+M*c;$=ie>>>13,ie&=8191,ie+=_*a+x*(5*f)+O*(5*y)+T*(5*g)+j*(5*d),$+=ie>>>13,ie&=8191;let ce=$+v*d+k*p+q*u+D*l+M*h;$=ce>>>13,ce&=8191,ce+=_*c+x*a+O*(5*f)+T*(5*y)+j*(5*g),$+=ce>>>13,ce&=8191;let ve=$+v*g+k*d+q*p+D*u+M*l;$=ve>>>13,ve&=8191,ve+=_*h+x*c+O*a+T*(5*f)+j*(5*y),$+=ve>>>13,ve&=8191;let ne=$+v*y+k*g+q*d+D*p+M*u;$=ne>>>13,ne&=8191,ne+=_*l+x*h+O*c+T*a+j*(5*f),$+=ne>>>13,ne&=8191;let oe=$+v*f+k*y+q*g+D*d+M*p;$=oe>>>13,oe&=8191,oe+=_*u+x*l+O*h+T*c+j*a,$+=oe>>>13,oe&=8191,$=($<<2)+$|0,$=$+U|0,U=$&8191,$=$>>>13,L+=$,n[0]=U,n[1]=L,n[2]=B,n[3]=Z,n[4]=G,n[5]=ie,n[6]=ce,n[7]=ve,n[8]=ne,n[9]=oe}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;fi(s)}update(e){Ln(this);const{buffer:t,blockLen:s}=this;e=vr(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(){fi(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ln(this),bu(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 ju(i){const e=(s,r)=>i(r).update(vr(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const Du=ju(i=>new qu(i));function ku(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],d=e[3],g=e[4],y=e[5],f=e[6],w=e[7],m=r,b=t[0],I=t[1],A=t[2],P=o,S=a,R=c,v=h,k=l,q=u,D=p,M=d,_=g,x=y,O=f,T=w,j=m,$=b,U=I,L=A;for(let Z=0;Z<n;Z+=2)P=P+k|0,j=V(j^P,16),_=_+j|0,k=V(k^_,12),P=P+k|0,j=V(j^P,8),_=_+j|0,k=V(k^_,7),S=S+q|0,$=V($^S,16),x=x+$|0,q=V(q^x,12),S=S+q|0,$=V($^S,8),x=x+$|0,q=V(q^x,7),R=R+D|0,U=V(U^R,16),O=O+U|0,D=V(D^O,12),R=R+D|0,U=V(U^R,8),O=O+U|0,D=V(D^O,7),v=v+M|0,L=V(L^v,16),T=T+L|0,M=V(M^T,12),v=v+M|0,L=V(L^v,8),T=T+L|0,M=V(M^T,7),P=P+q|0,L=V(L^P,16),O=O+L|0,q=V(q^O,12),P=P+q|0,L=V(L^P,8),O=O+L|0,q=V(q^O,7),S=S+D|0,j=V(j^S,16),T=T+j|0,D=V(D^T,12),S=S+D|0,j=V(j^S,8),T=T+j|0,D=V(D^T,7),R=R+M|0,$=V($^R,16),_=_+$|0,M=V(M^_,12),R=R+M|0,$=V($^R,8),_=_+$|0,M=V(M^_,7),v=v+k|0,U=V(U^v,16),x=x+U|0,k=V(k^x,12),v=v+k|0,U=V(U^v,8),x=x+U|0,k=V(k^x,7);let B=0;s[B++]=o+P|0,s[B++]=a+S|0,s[B++]=c+R|0,s[B++]=h+v|0,s[B++]=l+k|0,s[B++]=u+q|0,s[B++]=p+D|0,s[B++]=d+M|0,s[B++]=g+_|0,s[B++]=y+x|0,s[B++]=f+O|0,s[B++]=w+T|0,s[B++]=m+j|0,s[B++]=b+$|0,s[B++]=I+U|0,s[B++]=A+L|0}const Uu=Tu(ku,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Mu=new Uint8Array(16),Hn=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(Mu.subarray(t))},Lu=new Uint8Array(32);function Fn(i,e,t,s,r){const n=i(e,t,Lu),o=Du.create(n);r&&Hn(o,r),Hn(o,s);const a=new Uint8Array(16),c=vu(a);Kn(c,0,BigInt(r?r.length:0),!0),Kn(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return fi(n,a),h}const Bu=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=zn(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=Fn(i,e,t,a,s);return n.set(c,o),fi(c),n},decrypt(r,n){n=zn(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Fn(i,e,t,o,s);if(!Pu(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),fi(c),n}}),Wa=$u({blockSize:64,nonceLength:12,tagLength:16},Bu(Uu));let Ja=class extends en{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Xr(e);const s=gi(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 di(this),this.iHash.update(e),this}digestInto(e){di(this),Qi(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 qs=(i,e,t)=>new Ja(i,e).update(t).digest();qs.create=(i,e)=>new Ja(i,e);function zu(i,e,t){return Xr(i),t===void 0&&(t=new Uint8Array(i.outputLen)),qs(i,gi(t),gi(e))}const Gs=new Uint8Array([0]),Gn=new Uint8Array;function Ku(i,e,t,s=32){if(Xr(i),Vi(s),s>255*i.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(s/i.outputLen);t===void 0&&(t=Gn);const n=new Uint8Array(r*i.outputLen),o=qs.create(i,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let h=0;h<r;h++)Gs[0]=h+1,a.update(h===0?Gn:c).update(t).update(Gs).digestInto(c),n.set(c,i.outputLen*h),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Gs.fill(0),n.slice(0,s)}const Vu=(i,e,t,s,r)=>Ku(i,zu(i,e,t),s,r);function Hu(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 Fu(i,e,t){return i&e^~i&t}function Gu(i,e,t){return i&e^i&t^e&t}let Wu=class extends en{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=Hs(this.buffer)}update(e){di(this);const{view:t,buffer:s,blockLen:r}=this;e=gi(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=Hs(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){di(this),Da(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;Hu(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=Hs(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 Ju=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]),wt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),bt=new Uint32Array(64);class Qu extends Wu{constructor(){super(64,32,8,!1),this.A=wt[0]|0,this.B=wt[1]|0,this.C=wt[2]|0,this.D=wt[3]|0,this.E=wt[4]|0,this.F=wt[5]|0,this.G=wt[6]|0,this.H=wt[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)bt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=bt[u-15],d=bt[u-2],g=Ze(p,7)^Ze(p,18)^p>>>3,y=Ze(d,17)^Ze(d,19)^d>>>10;bt[u]=y+bt[u-7]+g+bt[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=Ze(a,6)^Ze(a,11)^Ze(a,25),d=l+p+Fu(a,c,h)+Ju[u]+bt[u]|0,g=(Ze(s,2)^Ze(s,13)^Ze(s,22))+Gu(s,r,n)|0;l=h,h=c,c=a,a=o+d|0,o=n,n=r,r=s,s=d+g|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(){bt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Yi=ka(()=>new Qu);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const js=BigInt(0),Ds=BigInt(1),Yu=BigInt(2);function Lt(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Zi(i){if(!Lt(i))throw new Error("Uint8Array expected")}function yi(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const Zu=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function mi(i){Zi(i);let e="";for(let t=0;t<i.length;t++)e+=Zu[i[t]];return e}function ci(i){const e=i.toString(16);return e.length&1?"0"+e:e}function sn(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?js:BigInt("0x"+i)}const lt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Wn(i){if(i>=lt._0&&i<=lt._9)return i-lt._0;if(i>=lt.A&&i<=lt.F)return i-(lt.A-10);if(i>=lt.a&&i<=lt.f)return i-(lt.a-10)}function wi(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=Wn(i.charCodeAt(n)),a=Wn(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 kt(i){return sn(mi(i))}function Fi(i){return Zi(i),sn(mi(Uint8Array.from(i).reverse()))}function bi(i,e){return wi(i.toString(16).padStart(e*2,"0"))}function ks(i,e){return bi(i,e).reverse()}function Xu(i){return wi(ci(i))}function Te(i,e,t){let s;if(typeof e=="string")try{s=wi(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(Lt(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 Gi(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Zi(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 ep(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 tp(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const Ws=i=>typeof i=="bigint"&&js<=i;function Us(i,e,t){return Ws(i)&&Ws(e)&&Ws(t)&&e<=i&&i<t}function ft(i,e,t,s){if(!Us(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function Qa(i){let e;for(e=0;i>js;i>>=Ds,e+=1);return e}function ip(i,e){return i>>BigInt(e)&Ds}function sp(i,e,t){return i|(t?Ds:js)<<BigInt(e)}const rn=i=>(Yu<<BigInt(i-1))-Ds,Js=i=>new Uint8Array(i),Jn=i=>Uint8Array.from(i);function Ya(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=Js(i),r=Js(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=Js())=>{r=a(Jn([0]),l),s=a(),l.length!==0&&(r=a(Jn([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 Gi(...u)};return(l,u)=>{o(),c(l);let p;for(;!(p=u(h()));)c();return o(),p}}const rp={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"||Lt(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 Si(i,e,t={}){const s=(r,n,o)=>{const a=rp[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 np=()=>{throw new Error("not implemented")};function _r(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 op=Object.freeze({__proto__:null,isBytes:Lt,abytes:Zi,abool:yi,bytesToHex:mi,numberToHexUnpadded:ci,hexToNumber:sn,hexToBytes:wi,bytesToNumberBE:kt,bytesToNumberLE:Fi,numberToBytesBE:bi,numberToBytesLE:ks,numberToVarBytesBE:Xu,ensureBytes:Te,concatBytes:Gi,equalBytes:ep,utf8ToBytes:tp,inRange:Us,aInRange:ft,bitLen:Qa,bitGet:ip,bitSet:sp,bitMask:rn,createHmacDrbg:Ya,validateObject:Si,notImplemented:np,memoized:_r});const ge=BigInt(0),te=BigInt(1),Rt=BigInt(2),ap=BigInt(3),Pr=BigInt(4),Qn=BigInt(5),Yn=BigInt(8);function xe(i,e){const t=i%e;return t>=ge?t:e+t}function Za(i,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===te)return ge;let s=te;for(;e>ge;)e&te&&(s=s*i%t),i=i*i%t,e>>=te;return s}function Ge(i,e,t){let s=i;for(;e-- >ge;)s*=s,s%=t;return s}function $r(i,e){if(i===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let t=xe(i,e),s=e,r=ge,n=te;for(;t!==ge;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==te)throw new Error("invert: does not exist");return xe(r,e)}function cp(i){const e=(i-te)/Rt;let t,s,r;for(t=i-te,s=0;t%Rt===ge;t/=Rt,s++);for(r=Rt;r<i&&Za(r,e,i)!==i-te;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+te)/Pr;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+te)/Rt;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 g=o.sqr(u);p<c&&!o.eql(g,o.ONE);p++)g=o.sqr(g);const d=o.pow(h,te<<BigInt(c-p-1));h=o.sqr(d),l=o.mul(l,d),u=o.mul(u,h),c=p}return l}}function hp(i){if(i%Pr===ap){const e=(i+te)/Pr;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%Yn===Qn){const e=(i-Qn)/Yn;return function(t,s){const r=t.mul(s,Rt),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,Rt),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 cp(i)}const lp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function up(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=lp.reduce((s,r)=>(s[r]="function",s),e);return Si(i,t)}function pp(i,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return i.ONE;if(t===te)return e;let s=i.ONE,r=e;for(;t>ge;)t&te&&(s=i.mul(s,r)),r=i.sqr(r),t>>=te;return s}function dp(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 Xa(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function ec(i,e,t=!1,s={}){if(i<=ge)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=Xa(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:rn(r),ZERO:ge,ONE:te,create:c=>xe(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ge<=c&&c<i},is0:c=>c===ge,isOdd:c=>(c&te)===te,neg:c=>xe(-c,i),eql:(c,h)=>c===h,sqr:c=>xe(c*c,i),add:(c,h)=>xe(c+h,i),sub:(c,h)=>xe(c-h,i),mul:(c,h)=>xe(c*h,i),pow:(c,h)=>pp(a,c,h),div:(c,h)=>xe(c*$r(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>$r(c,i),sqrt:s.sqrt||(c=>(o||(o=hp(i)),o(a,c))),invertBatch:c=>dp(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?ks(c,n):bi(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?Fi(c):kt(c)}});return Object.freeze(a)}function tc(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 ic(i){const e=tc(i);return e+Math.ceil(e/2)}function gp(i,e,t=!1){const s=i.length,r=tc(e),n=ic(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?Fi(i):kt(i),a=xe(o,e-te)+te;return t?ks(a,r):bi(a,r)}const Zn=BigInt(0),as=BigInt(1);function Qs(i,e){const t=e.negate();return i?t:e}function sc(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function Ys(i,e){sc(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function fp(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 yp(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 Zs=new WeakMap,rc=new WeakMap;function Xs(i){return rc.get(i)||1}function mp(i,e){return{constTimeNegate:Qs,hasPrecomputes(t){return Xs(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>Zn;)s&as&&(r=r.add(n)),n=n.double(),s>>=as;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=Ys(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}=Ys(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 d=p*o;let g=Number(r&h);r>>=u,g>o&&(g-=l,r+=as);const y=d,f=d+Math.abs(g)-1,w=p%2!==0,m=g<0;g===0?c=c.add(Qs(w,s[y])):a=a.add(Qs(m,s[f]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=Ys(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===Zn)break;let d=Number(r&c);if(r>>=l,d>a&&(d-=h,r+=as),d===0)continue;let g=s[p+Math.abs(d)-1];d<0&&(g=g.negate()),n=n.add(g)}return n},getPrecomputes(t,s,r){let n=Zs.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&Zs.set(s,r(n))),n},wNAFCached(t,s,r){const n=Xs(t);return this.wNAF(n,this.getPrecomputes(n,t,r),s)},wNAFCachedUnsafe(t,s,r,n){const o=Xs(t);return o===1?this.unsafeLadder(t,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,r),s,n)},setWindowSize(t,s){sc(s,e),rc.set(t,s),Zs.delete(t)}}}function wp(i,e,t,s){if(fp(t,i),yp(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=Qa(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 d=0;d<s.length;d++){const g=s[d],y=Number(g>>BigInt(u)&BigInt(a));c[y]=c[y].add(t[d])}let p=r;for(let d=c.length-1,g=r;d>0;d--)g=g.add(c[d]),p=p.add(g);if(l=l.add(p),u!==0)for(let d=0;d<o;d++)l=l.double()}return l}function nc(i){return up(i.Fp),Si(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Xa(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Ft=BigInt(0),er=BigInt(1);function bp(i){return Si(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function vp(i){const e=bp(i),{P:t}=e,s=m=>xe(m,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),c=e.powPminus2||(m=>Za(m,t-BigInt(2),t));function h(m,b,I){const A=s(m*(b-I));return b=s(b-A),I=s(I+A),[b,I]}const l=(e.a-BigInt(2))/BigInt(4);function u(m,b){ft("u",m,Ft,t),ft("scalar",b,Ft,t);const I=b,A=m;let P=er,S=Ft,R=m,v=er,k=Ft,q;for(let M=BigInt(r-1);M>=Ft;M--){const _=I>>M&er;k^=_,q=h(k,P,R),P=q[0],R=q[1],q=h(k,S,v),S=q[0],v=q[1],k=_;const x=P+S,O=s(x*x),T=P-S,j=s(T*T),$=O-j,U=R+v,L=R-v,B=s(L*x),Z=s(U*T),G=B+Z,ie=B-Z;R=s(G*G),v=s(A*s(ie*ie)),P=s(O*j),S=s($*(O+s(l*$)))}q=h(k,P,R),P=q[0],R=q[1],q=h(k,S,v),S=q[0],v=q[1];const D=c(S);return s(P*D)}function p(m){return ks(s(m),n)}function d(m){const b=Te("u coordinate",m,n);return o===32&&(b[31]&=127),Fi(b)}function g(m){const b=Te("scalar",m),I=b.length;if(I!==n&&I!==o){let A=""+n+" or "+o;throw new Error("invalid scalar, expected "+A+" bytes, got "+I)}return Fi(a(b))}function y(m,b){const I=d(b),A=g(m),P=u(I,A);if(P===Ft)throw new Error("invalid private or public key received");return p(P)}const f=p(e.Gu);function w(m){return y(m,f)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(m,b)=>y(m,b),getPublicKey:m=>w(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:f}}const Sr=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Ep=BigInt(1),Xn=BigInt(2),Ip=BigInt(3),_p=BigInt(5);BigInt(8);function Pp(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=Sr,o=i*i%n*i%n,a=Ge(o,Xn,n)*o%n,c=Ge(a,Ep,n)*i%n,h=Ge(c,_p,n)*c%n,l=Ge(h,e,n)*h%n,u=Ge(l,t,n)*l%n,p=Ge(u,s,n)*u%n,d=Ge(p,r,n)*p%n,g=Ge(d,r,n)*p%n,y=Ge(g,e,n)*h%n;return{pow_p_5_8:Ge(y,Xn,n)*i%n,b2:o}}function $p(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}const Or=vp({P:Sr,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=Sr,{pow_p_5_8:t,b2:s}=Pp(i);return xe(Ge(t,Ip,e)*s,e)},adjustScalarBytes:$p,randomBytes:$i});function eo(i){i.lowS!==void 0&&yi("lowS",i.lowS),i.prehash!==void 0&&yi("prehash",i.prehash)}function Sp(i){const e=nc(i);Si(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:Op,hexToBytes:xp}=op;class Ap extends Error{constructor(e=""){super(e)}}const dt={Err:Ap,_tlv:{encode:(i,e)=>{const{Err:t}=dt;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=ci(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?ci(r.length/2|128):"";return ci(i)+n+r+e},decode(i,e){const{Err:t}=dt;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}=dt;if(i<gt)throw new e("integer: negative integers are not allowed");let t=ci(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}=dt;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 Op(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=dt,r=typeof i=="string"?xp(i):i;Zi(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}=dt,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},gt=BigInt(0),pe=BigInt(1);BigInt(2);const to=BigInt(3);BigInt(4);function Cp(i){const e=Sp(i),{Fp:t}=e,s=ec(e.n,e.nBitLength),r=e.toBytes||((y,f,w)=>{const m=f.toAffine();return Gi(Uint8Array.from([4]),t.toBytes(m.x),t.toBytes(m.y))}),n=e.fromBytes||(y=>{const f=y.subarray(1),w=t.fromBytes(f.subarray(0,t.BYTES)),m=t.fromBytes(f.subarray(t.BYTES,2*t.BYTES));return{x:w,y:m}});function o(y){const{a:f,b:w}=e,m=t.sqr(y),b=t.mul(m,y);return t.add(t.add(b,t.mul(y,f)),w)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Us(y,pe,e.n)}function c(y){const{allowedPrivateKeyLengths:f,nByteLength:w,wrapPrivateKey:m,n:b}=e;if(f&&typeof y!="bigint"){if(Lt(y)&&(y=mi(y)),typeof y!="string"||!f.includes(y.length))throw new Error("invalid private key");y=y.padStart(w*2,"0")}let I;try{I=typeof y=="bigint"?y:kt(Te("private key",y,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof y)}return m&&(I=xe(I,b)),ft("private key",I,pe,b),I}function h(y){if(!(y instanceof p))throw new Error("ProjectivePoint expected")}const l=_r((y,f)=>{const{px:w,py:m,pz:b}=y;if(t.eql(b,t.ONE))return{x:w,y:m};const I=y.is0();f==null&&(f=I?t.ONE:t.inv(b));const A=t.mul(w,f),P=t.mul(m,f),S=t.mul(b,f);if(I)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:A,y:P}}),u=_r(y=>{if(y.is0()){if(e.allowInfinityPoint&&!t.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:f,y:w}=y.toAffine();if(!t.isValid(f)||!t.isValid(w))throw new Error("bad point: x or y not FE");const m=t.sqr(w),b=o(f);if(!t.eql(m,b))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(f,w,m){if(this.px=f,this.py=w,this.pz=m,f==null||!t.isValid(f))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(m==null||!t.isValid(m))throw new Error("z required");Object.freeze(this)}static fromAffine(f){const{x:w,y:m}=f||{};if(!f||!t.isValid(w)||!t.isValid(m))throw new Error("invalid affine point");if(f instanceof p)throw new Error("projective point not allowed");const b=I=>t.eql(I,t.ZERO);return b(w)&&b(m)?p.ZERO:new p(w,m,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const w=t.invertBatch(f.map(m=>m.pz));return f.map((m,b)=>m.toAffine(w[b])).map(p.fromAffine)}static fromHex(f){const w=p.fromAffine(n(Te("pointHex",f)));return w.assertValidity(),w}static fromPrivateKey(f){return p.BASE.multiply(c(f))}static msm(f,w){return wp(p,s,f,w)}_setWindowSize(f){g.setWindowSize(this,f)}assertValidity(){u(this)}hasEvenY(){const{y:f}=this.toAffine();if(t.isOdd)return!t.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){h(f);const{px:w,py:m,pz:b}=this,{px:I,py:A,pz:P}=f,S=t.eql(t.mul(w,P),t.mul(I,b)),R=t.eql(t.mul(m,P),t.mul(A,b));return S&&R}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:f,b:w}=e,m=t.mul(w,to),{px:b,py:I,pz:A}=this;let P=t.ZERO,S=t.ZERO,R=t.ZERO,v=t.mul(b,b),k=t.mul(I,I),q=t.mul(A,A),D=t.mul(b,I);return D=t.add(D,D),R=t.mul(b,A),R=t.add(R,R),P=t.mul(f,R),S=t.mul(m,q),S=t.add(P,S),P=t.sub(k,S),S=t.add(k,S),S=t.mul(P,S),P=t.mul(D,P),R=t.mul(m,R),q=t.mul(f,q),D=t.sub(v,q),D=t.mul(f,D),D=t.add(D,R),R=t.add(v,v),v=t.add(R,v),v=t.add(v,q),v=t.mul(v,D),S=t.add(S,v),q=t.mul(I,A),q=t.add(q,q),v=t.mul(q,D),P=t.sub(P,v),R=t.mul(q,k),R=t.add(R,R),R=t.add(R,R),new p(P,S,R)}add(f){h(f);const{px:w,py:m,pz:b}=this,{px:I,py:A,pz:P}=f;let S=t.ZERO,R=t.ZERO,v=t.ZERO;const k=e.a,q=t.mul(e.b,to);let D=t.mul(w,I),M=t.mul(m,A),_=t.mul(b,P),x=t.add(w,m),O=t.add(I,A);x=t.mul(x,O),O=t.add(D,M),x=t.sub(x,O),O=t.add(w,b);let T=t.add(I,P);return O=t.mul(O,T),T=t.add(D,_),O=t.sub(O,T),T=t.add(m,b),S=t.add(A,P),T=t.mul(T,S),S=t.add(M,_),T=t.sub(T,S),v=t.mul(k,O),S=t.mul(q,_),v=t.add(S,v),S=t.sub(M,v),v=t.add(M,v),R=t.mul(S,v),M=t.add(D,D),M=t.add(M,D),_=t.mul(k,_),O=t.mul(q,O),M=t.add(M,_),_=t.sub(D,_),_=t.mul(k,_),O=t.add(O,_),D=t.mul(M,O),R=t.add(R,D),D=t.mul(T,O),S=t.mul(x,S),S=t.sub(S,D),D=t.mul(x,M),v=t.mul(T,v),v=t.add(v,D),new p(S,R,v)}subtract(f){return this.add(f.negate())}is0(){return this.equals(p.ZERO)}wNAF(f){return g.wNAFCached(this,f,p.normalizeZ)}multiplyUnsafe(f){const{endo:w,n:m}=e;ft("scalar",f,gt,m);const b=p.ZERO;if(f===gt)return b;if(this.is0()||f===pe)return this;if(!w||g.hasPrecomputes(this))return g.wNAFCachedUnsafe(this,f,p.normalizeZ);let{k1neg:I,k1:A,k2neg:P,k2:S}=w.splitScalar(f),R=b,v=b,k=this;for(;A>gt||S>gt;)A&pe&&(R=R.add(k)),S&pe&&(v=v.add(k)),k=k.double(),A>>=pe,S>>=pe;return I&&(R=R.negate()),P&&(v=v.negate()),v=new p(t.mul(v.px,w.beta),v.py,v.pz),R.add(v)}multiply(f){const{endo:w,n:m}=e;ft("scalar",f,pe,m);let b,I;if(w){const{k1neg:A,k1:P,k2neg:S,k2:R}=w.splitScalar(f);let{p:v,f:k}=this.wNAF(P),{p:q,f:D}=this.wNAF(R);v=g.constTimeNegate(A,v),q=g.constTimeNegate(S,q),q=new p(t.mul(q.px,w.beta),q.py,q.pz),b=v.add(q),I=k.add(D)}else{const{p:A,f:P}=this.wNAF(f);b=A,I=P}return p.normalizeZ([b,I])[0]}multiplyAndAddUnsafe(f,w,m){const b=p.BASE,I=(P,S)=>S===gt||S===pe||!P.equals(b)?P.multiplyUnsafe(S):P.multiply(S),A=I(this,w).add(I(f,m));return A.is0()?void 0:A}toAffine(f){return l(this,f)}isTorsionFree(){const{h:f,isTorsionFree:w}=e;if(f===pe)return!0;if(w)return w(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:w}=e;return f===pe?this:w?w(p,this):this.multiplyUnsafe(e.h)}toRawBytes(f=!0){return yi("isCompressed",f),this.assertValidity(),r(p,this,f)}toHex(f=!0){return yi("isCompressed",f),mi(this.toRawBytes(f))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const d=e.nBitLength,g=mp(p,e.endo?Math.ceil(d/2):d);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Np(i){const e=nc(i);return Si(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Rp(i){const e=Np(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(_){return xe(_,s)}function a(_){return $r(_,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=Cp({...e,toBytes(_,x,O){const T=x.toAffine(),j=t.toBytes(T.x),$=Gi;return yi("isCompressed",O),O?$(Uint8Array.from([x.hasEvenY()?2:3]),j):$(Uint8Array.from([4]),j,t.toBytes(T.y))},fromBytes(_){const x=_.length,O=_[0],T=_.subarray(1);if(x===r&&(O===2||O===3)){const j=kt(T);if(!Us(j,pe,t.ORDER))throw new Error("Point is not on curve");const $=l(j);let U;try{U=t.sqrt($)}catch(B){const Z=B instanceof Error?": "+B.message:"";throw new Error("Point is not on curve"+Z)}const L=(U&pe)===pe;return(O&1)===1!==L&&(U=t.neg(U)),{x:j,y:U}}else if(x===n&&O===4){const j=t.fromBytes(T.subarray(0,t.BYTES)),$=t.fromBytes(T.subarray(t.BYTES,2*t.BYTES));return{x:j,y:$}}else{const j=r,$=n;throw new Error("invalid Point, expected length of "+j+", or uncompressed "+$+", got "+x)}}}),p=_=>mi(bi(_,e.nByteLength));function d(_){const x=s>>pe;return _>x}function g(_){return d(_)?o(-_):_}const y=(_,x,O)=>kt(_.slice(x,O));class f{constructor(x,O,T){this.r=x,this.s=O,this.recovery=T,this.assertValidity()}static fromCompact(x){const O=e.nByteLength;return x=Te("compactSignature",x,O*2),new f(y(x,0,O),y(x,O,2*O))}static fromDER(x){const{r:O,s:T}=dt.toSig(Te("DER",x));return new f(O,T)}assertValidity(){ft("r",this.r,pe,s),ft("s",this.s,pe,s)}addRecoveryBit(x){return new f(this.r,this.s,x)}recoverPublicKey(x){const{r:O,s:T,recovery:j}=this,$=P(Te("msgHash",x));if(j==null||![0,1,2,3].includes(j))throw new Error("recovery id invalid");const U=j===2||j===3?O+e.n:O;if(U>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=j&1?"03":"02",B=c.fromHex(L+p(U)),Z=a(U),G=o(-$*Z),ie=o(T*Z),ce=c.BASE.multiplyAndAddUnsafe(B,G,ie);if(!ce)throw new Error("point at infinify");return ce.assertValidity(),ce}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return wi(this.toDERHex())}toDERHex(){return dt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return wi(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const w={isValidPrivateKey(_){try{return h(_),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const _=ic(e.n);return gp(e.randomBytes(_),e.n)},precompute(_=8,x=c.BASE){return x._setWindowSize(_),x.multiply(BigInt(3)),x}};function m(_,x=!0){return c.fromPrivateKey(_).toRawBytes(x)}function b(_){const x=Lt(_),O=typeof _=="string",T=(x||O)&&_.length;return x?T===r||T===n:O?T===2*r||T===2*n:_ instanceof c}function I(_,x,O=!0){if(b(_))throw new Error("first arg must be private key");if(!b(x))throw new Error("second arg must be public key");return c.fromHex(x).multiply(h(_)).toRawBytes(O)}const A=e.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");const x=kt(_),O=_.length*8-e.nBitLength;return O>0?x>>BigInt(O):x},P=e.bits2int_modN||function(_){return o(A(_))},S=rn(e.nBitLength);function R(_){return ft("num < 2^"+e.nBitLength,_,gt,S),bi(_,e.nByteLength)}function v(_,x,O=k){if(["recovered","canonical"].some(ne=>ne in O))throw new Error("sign() legacy options not supported");const{hash:T,randomBytes:j}=e;let{lowS:$,prehash:U,extraEntropy:L}=O;$==null&&($=!0),_=Te("msgHash",_),eo(O),U&&(_=Te("prehashed msgHash",T(_)));const B=P(_),Z=h(x),G=[R(Z),R(B)];if(L!=null&&L!==!1){const ne=L===!0?j(t.BYTES):L;G.push(Te("extraEntropy",ne))}const ie=Gi(...G),ce=B;function ve(ne){const oe=A(ne);if(!u(oe))return;const Ot=a(oe),ot=c.BASE.multiply(oe).toAffine(),Ye=o(ot.x);if(Ye===gt)return;const at=o(Ot*o(ce+Ye*Z));if(at===gt)return;let ct=(ot.x===Ye?0:2)|Number(ot.y&pe),is=at;return $&&d(at)&&(is=g(at),ct^=1),new f(Ye,is,ct)}return{seed:ie,k2sig:ve}}const k={lowS:e.lowS,prehash:!1},q={lowS:e.lowS,prehash:!1};function D(_,x,O=k){const{seed:T,k2sig:j}=v(_,x,O),$=e;return Ya($.hash.outputLen,$.nByteLength,$.hmac)(T,j)}c.BASE._setWindowSize(8);function M(_,x,O,T=q){var at;const j=_;x=Te("msgHash",x),O=Te("publicKey",O);const{lowS:$,prehash:U,format:L}=T;if(eo(T),"strict"in T)throw new Error("options.strict was renamed to lowS");if(L!==void 0&&L!=="compact"&&L!=="der")throw new Error("format must be compact or der");const B=typeof j=="string"||Lt(j),Z=!B&&!L&&typeof j=="object"&&j!==null&&typeof j.r=="bigint"&&typeof j.s=="bigint";if(!B&&!Z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let G,ie;try{if(Z&&(G=new f(j.r,j.s)),B){try{L!=="compact"&&(G=f.fromDER(j))}catch(ct){if(!(ct instanceof dt.Err))throw ct}!G&&L!=="der"&&(G=f.fromCompact(j))}ie=c.fromHex(O)}catch{return!1}if(!G||$&&G.hasHighS())return!1;U&&(x=e.hash(x));const{r:ce,s:ve}=G,ne=P(x),oe=a(ve),Ot=o(ne*oe),ot=o(ce*oe),Ye=(at=c.BASE.multiplyAndAddUnsafe(ie,Ot,ot))==null?void 0:at.toAffine();return Ye?o(Ye.x)===ce:!1}return{CURVE:e,getPublicKey:m,getSharedSecret:I,sign:D,verify:M,ProjectivePoint:c,Signature:f,utils:w}}function Tp(i){return{hash:i,hmac:(e,...t)=>qs(i,e,kl(...t)),randomBytes:$i}}function qp(i,e){const t=s=>Rp({...i,...Tp(s)});return{...t(e),create:t}}const oc=ec(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),jp=oc.create(BigInt("-3")),Dp=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),kp=qp({a:jp,b:Dp,Fp:oc,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Yi),ac="base10",_e="base16",We="base64pad",Et="base64url",Xi="utf8",cc=0,yt=1,es=2,Up=0,io=1,Li=12,nn=32;function Mp(){const i=Or.utils.randomPrivateKey(),e=Or.getPublicKey(i);return{privateKey:Ae(i,_e),publicKey:Ae(e,_e)}}function xr(){const i=$i(nn);return Ae(i,_e)}function Lp(i,e){const t=Or.getSharedSecret(Be(i,_e),Be(e,_e)),s=Vu(Yi,t,void 0,void 0,nn);return Ae(s,_e)}function ms(i){const e=Yi(Be(i,_e));return Ae(e,_e)}function st(i){const e=Yi(Be(i,Xi));return Ae(e,_e)}function hc(i){return Be(`${i}`,ac)}function Bt(i){return Number(Ae(i,ac))}function lc(i){return i.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uc(i){const e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Bp(i){const e=hc(typeof i.type<"u"?i.type:cc);if(Bt(e)===yt&&typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof i.senderPublicKey<"u"?Be(i.senderPublicKey,_e):void 0,s=typeof i.iv<"u"?Be(i.iv,_e):$i(Li),r=Be(i.symKey,_e),n=Wa(r,s).encrypt(Be(i.message,Xi)),o=pc({type:e,sealed:n,iv:s,senderPublicKey:t});return i.encoding===Et?lc(o):o}function zp(i){const e=Be(i.symKey,_e),{sealed:t,iv:s}=Wi({encoded:i.encoded,encoding:i.encoding}),r=Wa(e,s).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return Ae(r,Xi)}function Kp(i,e){const t=hc(es),s=$i(Li),r=Be(i,Xi),n=pc({type:t,sealed:r,iv:s});return e===Et?lc(n):n}function Vp(i,e){const{sealed:t}=Wi({encoded:i,encoding:e});return Ae(t,Xi)}function pc(i){if(Bt(i.type)===es)return Ae(Mi([i.type,i.sealed]),We);if(Bt(i.type)===yt){if(typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ae(Mi([i.type,i.senderPublicKey,i.iv,i.sealed]),We)}return Ae(Mi([i.type,i.iv,i.sealed]),We)}function Wi(i){const e=(i.encoding||We)===Et?uc(i.encoded):i.encoded,t=Be(e,We),s=t.slice(Up,io),r=io;if(Bt(s)===yt){const c=r+nn,h=c+Li,l=t.slice(r,c),u=t.slice(c,h),p=t.slice(h);return{type:s,sealed:p,iv:u,senderPublicKey:l}}if(Bt(s)===es){const c=t.slice(r),h=$i(Li);return{type:s,sealed:c,iv:h}}const n=r+Li,o=t.slice(r,n),a=t.slice(n);return{type:s,sealed:a,iv:o}}function Hp(i,e){const t=Wi({encoded:i,encoding:e==null?void 0:e.encoding});return dc({type:Bt(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Ae(t.senderPublicKey,_e):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function dc(i){const e=(i==null?void 0:i.type)||cc;if(e===yt){if(typeof(i==null?void 0:i.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(i==null?void 0:i.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:i==null?void 0:i.senderPublicKey,receiverPublicKey:i==null?void 0:i.receiverPublicKey}}function so(i){return i.type===yt&&typeof i.senderPublicKey=="string"&&typeof i.receiverPublicKey=="string"}function ro(i){return i.type===es}function Fp(i){const e=Buffer.from(i.x,"base64"),t=Buffer.from(i.y,"base64");return Mi([new Uint8Array([4]),e,t])}function Gp(i,e){const[t,s,r]=i.split("."),n=Buffer.from(uc(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=Yi(c),l=Fp(e);if(!kp.verify(Mi([o,a]),h,l))throw new Error("Invalid signature");return gr(i).payload}const Wp="irn";function Ss(i){return(i==null?void 0:i.relay)||{protocol:Wp}}function ki(i){const e=Yc[i];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${i}`);return e}function Jp(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 no(i){if(!i.includes("wc:")){const h=ja(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:Qp(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:Jp(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Qp(i){return i.startsWith("//")?i.substring(2):i}function Yp(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 oo(i){const e=new URLSearchParams,t=Yp(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}`}function cs(i,e,t){return`${i}?wc_ev=${t}&topic=${e}`}var Zp=Object.defineProperty,Xp=Object.defineProperties,ed=Object.getOwnPropertyDescriptors,ao=Object.getOwnPropertySymbols,td=Object.prototype.hasOwnProperty,id=Object.prototype.propertyIsEnumerable,co=(i,e,t)=>e in i?Zp(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,sd=(i,e)=>{for(var t in e||(e={}))td.call(e,t)&&co(i,t,e[t]);if(ao)for(var t of ao(e))id.call(e,t)&&co(i,t,e[t]);return i},rd=(i,e)=>Xp(i,ed(e));function Oi(i){const e=[];return i.forEach(t=>{const[s,r]=t.split(":");e.push(`${s}:${r}`)}),e}function nd(i){const e=[];return Object.values(i).forEach(t=>{e.push(...Oi(t.accounts))}),e}function od(i,e){const t=[];return Object.values(i).forEach(s=>{Oi(s.accounts).includes(e)&&t.push(...s.methods)}),t}function ad(i,e){const t=[];return Object.values(i).forEach(s=>{Oi(s.accounts).includes(e)&&t.push(...s.events)}),t}function Ms(i){return i.includes(":")}function hi(i){return Ms(i)?i.split(":")[0]:i}function ho(i){var e,t,s;const r={};if(!Pt(i))return r;for(const[n,o]of Object.entries(i)){const a=Ms(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],l=hi(n);r[l]=rd(sd({},r[l]),{chains:rt(a,(e=r[l])==null?void 0:e.chains),methods:rt(c,(t=r[l])==null?void 0:t.methods),events:rt(h,(s=r[l])==null?void 0:s.events)})}return r}function cd(i){const e={};return i==null||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 lo(i,e){e=e.map(s=>s.replace("did:pkh:",""));const t=cd(e);for(const[s,r]of Object.entries(t))r.methods?r.methods=rt(r.methods,i):r.methods=i,r.events=["chainChanged","accountsChanged"];return t}function hd(i,e){var t,s,r,n,o,a;const c=ho(i),h=ho(e),l={},u=Object.keys(c).concat(Object.keys(h));for(const p of u)l[p]={chains:rt((t=c[p])==null?void 0:t.chains,(s=h[p])==null?void 0:s.chains),methods:rt((r=c[p])==null?void 0:r.methods,(n=h[p])==null?void 0:n.methods),events:rt((o=c[p])==null?void 0:o.events,(a=h[p])==null?void 0:a.events)};return l}const ld={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}},ud={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 C(i,e){const{message:t,code:s}=ud[i];return{message:e?`${t} ${e}`:t,code:s}}function J(i,e){const{message:t,code:s}=ld[i];return{message:e?`${t} ${e}`:t,code:s}}function Je(i,e){return!!Array.isArray(i)}function Pt(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}function we(i){return typeof i>"u"}function re(i,e){return e&&we(i)?!0:typeof i=="string"&&!!i.trim().length}function on(i,e){return e&&we(i)?!0:typeof i=="number"&&!isNaN(i)}function pd(i,e){const{requiredNamespaces:t}=e,s=Object.keys(i.namespaces),r=Object.keys(t);let n=!0;return Dt(r,s)?(s.forEach(o=>{const{accounts:a,methods:c,events:h}=i.namespaces[o],l=Oi(a),u=t[o];(!Dt(Ca(o,u),l)||!Dt(u.methods,c)||!Dt(u.events,h))&&(n=!1)}),n):!1}function Os(i){return re(i,!1)&&i.includes(":")?i.split(":").length===2:!1}function dd(i){if(re(i,!1)&&i.includes(":")){const e=i.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Os(t)}}return!1}function gd(i){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(re(i,!1)){if(e(i))return!0;const t=ja(i);return e(t)}}catch{}return!1}function fd(i){var e;return(e=i==null?void 0:i.proposer)==null?void 0:e.publicKey}function yd(i){return i==null?void 0:i.topic}function md(i,e){let t=null;return re(i==null?void 0:i.publicKey,!1)||(t=C("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function uo(i){let e=!0;return Je(i)?i.length&&(e=i.every(t=>re(t,!1))):e=!1,e}function wd(i,e,t){let s=null;return Je(e)&&e.length?e.forEach(r=>{s||Os(r)||(s=J("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Os(i)||(s=J("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 bd(i,e,t){let s=null;return Object.entries(i).forEach(([r,n])=>{if(s)return;const o=wd(r,Ca(r,n),`${e} ${t}`);o&&(s=o)}),s}function vd(i,e){let t=null;return Je(i)?i.forEach(s=>{t||dd(s)||(t=J("UNSUPPORTED_ACCOUNTS",`${e}, account ${s} should be a string and conform to "namespace:chainId:address" format`))}):t=J("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function Ed(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=vd(s==null?void 0:s.accounts,`${e} namespace`);r&&(t=r)}),t}function Id(i,e){let t=null;return uo(i==null?void 0:i.methods)?uo(i==null?void 0:i.events)||(t=J("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=J("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function gc(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=Id(s,`${e}, namespace`);r&&(t=r)}),t}function _d(i,e,t){let s=null;if(i&&Pt(i)){const r=gc(i,e);r&&(s=r);const n=bd(i,e,t);n&&(s=n)}else s=C("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return s}function tr(i,e){let t=null;if(i&&Pt(i)){const s=gc(i,e);s&&(t=s);const r=Ed(i,e);r&&(t=r)}else t=C("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function fc(i){return re(i.protocol,!0)}function Pd(i,e){let t=!1;return i?i&&Je(i)&&i.length&&i.forEach(s=>{t=fc(s)}):t=!0,t}function $d(i){return typeof i=="number"}function Oe(i){return typeof i<"u"&&typeof i!==null}function Sd(i){return!(!i||typeof i!="object"||!i.code||!on(i.code,!1)||!i.message||!re(i.message,!1))}function Od(i){return!(we(i)||!re(i.method,!1))}function xd(i){return!(we(i)||we(i.result)&&we(i.error)||!on(i.id,!1)||!re(i.jsonrpc,!1))}function Ad(i){return!(we(i)||!re(i.name,!1))}function po(i,e){return!(!Os(e)||!nd(i).includes(e))}function Cd(i,e,t){return re(t,!1)?od(i,e).includes(t):!1}function Nd(i,e,t){return re(t,!1)?ad(i,e).includes(t):!1}function go(i,e,t){let s=null;const r=Rd(i),n=Td(e),o=Object.keys(r),a=Object.keys(n),c=fo(Object.keys(i)),h=fo(Object.keys(e)),l=c.filter(u=>!h.includes(u));return l.length&&(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
7
- Required: ${l.toString()}
8
- Received: ${Object.keys(e).toString()}`)),Dt(o,a)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces.
9
- Required: ${o.toString()}
10
- Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||s)return;const p=Oi(e[u].accounts);p.includes(u)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${u}
11
- Required: ${u}
12
- Approved: ${p.toString()}`))}),o.forEach(u=>{s||(Dt(r[u].methods,n[u].methods)?Dt(r[u].events,n[u].events)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),s}function Rd(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 fo(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Td(i){const e={};return Object.keys(i).forEach(t=>{if(t.includes(":"))e[t]=i[t];else{const s=Oi(i[t].accounts);s==null||s.forEach(r=>{e[r]={accounts:i[t].accounts.filter(n=>n.includes(`${r}:`)),methods:i[t].methods,events:i[t].events}})}}),e}function qd(i,e){return on(i,!1)&&i<=e.max&&i>=e.min}function yo(){const i=Ji();return new Promise(e=>{switch(i){case je.browser:e(jd());break;case je.reactNative:e(Dd());break;case je.node:e(kd());break;default:e(!0)}})}function jd(){return Pi()&&(navigator==null?void 0:navigator.onLine)}async function Dd(){if(St()&&typeof global<"u"&&global!=null&&global.NetInfo){const i=await(global==null?void 0:global.NetInfo.fetch());return i==null?void 0:i.isConnected}return!0}function kd(){return!0}function Ud(i){switch(Ji()){case je.browser:Md(i);break;case je.reactNative:Ld(i);break}}function Md(i){!St()&&Pi()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function Ld(i){St()&&typeof global<"u"&&global!=null&&global.NetInfo&&(global==null||global.NetInfo.addEventListener(e=>i(e==null?void 0:e.isConnected)))}function Bd(){var i;return Pi()&&pi()?((i=pi())==null?void 0:i.visibilityState)==="visible":!0}const ir={};class Ni{static get(e){return ir[e]}static set(e,t){ir[e]=t}static delete(e){delete ir[e]}}function zd(i){return!i||typeof i.then!="function"?Promise.resolve(i):i}function ue(i,...e){try{return zd(i(...e))}catch(t){return Promise.reject(t)}}function Kd(i){const e=typeof i;return i===null||e!=="object"&&e!=="function"}function Vd(i){const e=Object.getPrototypeOf(i);return!e||e.isPrototypeOf(Object)}function ws(i){if(Kd(i))return String(i);if(Vd(i)||Array.isArray(i))return JSON.stringify(i);if(typeof i.toJSON=="function")return ws(i.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Ar="base64:";function Hd(i){return typeof i=="string"?i:Ar+Wd(i)}function Fd(i){return typeof i!="string"||!i.startsWith(Ar)?i:Gd(i.slice(Ar.length))}function Gd(i){return globalThis.Buffer?Buffer.from(i,"base64"):Uint8Array.from(globalThis.atob(i),e=>e.codePointAt(0))}function Wd(i){return globalThis.Buffer?Buffer.from(i).toString("base64"):globalThis.btoa(String.fromCodePoint(...i))}function Se(i){var e;return i&&((e=i.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function Jd(...i){return Se(i.join(":"))}function hs(i){return i=Se(i),i?i+":":""}function Qd(i,e){if(e===void 0)return!0;let t=0,s=i.indexOf(":");for(;s>-1;)t++,s=i.indexOf(":",s+1);return t<=e}function Yd(i,e){return e?i.startsWith(e)&&i[i.length-1]!=="$":i[i.length-1]!=="$"}const Zd="memory",Xd=()=>{const i=new Map;return{name:Zd,getInstance:()=>i,hasItem(e){return i.has(e)},getItem(e){return i.get(e)??null},getItemRaw(e){return i.get(e)??null},setItem(e,t){i.set(e,t)},setItemRaw(e,t){i.set(e,t)},removeItem(e){i.delete(e)},getKeys(){return[...i.keys()]},clear(){i.clear()},dispose(){i.clear()}}};function eg(i={}){const e={mounts:{"":i.driver||Xd()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=h=>{for(const l of e.mountpoints)if(h.startsWith(l))return{base:l,relativeKey:h.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:h,driver:e.mounts[""]}},s=(h,l)=>e.mountpoints.filter(u=>u.startsWith(h)||l&&h.startsWith(u)).map(u=>({relativeBase:h.length>u.length?h.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(h,l)=>{if(e.watching){l=Se(l);for(const u of e.watchListeners)u(h,l)}},n=async()=>{if(!e.watching){e.watching=!0;for(const h in e.mounts)e.unwatch[h]=await mo(e.mounts[h],r,h)}},o=async()=>{if(e.watching){for(const h in e.unwatch)await e.unwatch[h]();e.unwatch={},e.watching=!1}},a=(h,l,u)=>{const p=new Map,d=g=>{let y=p.get(g.base);return y||(y={driver:g.driver,base:g.base,items:[]},p.set(g.base,y)),y};for(const g of h){const y=typeof g=="string",f=Se(y?g:g.key),w=y?void 0:g.value,m=y||!g.options?l:{...l,...g.options},b=t(f);d(b).items.push({key:f,value:w,relativeKey:b.relativeKey,options:m})}return Promise.all([...p.values()].map(g=>u(g))).then(g=>g.flat())},c={hasItem(h,l={}){h=Se(h);const{relativeKey:u,driver:p}=t(h);return ue(p.hasItem,u,l)},getItem(h,l={}){h=Se(h);const{relativeKey:u,driver:p}=t(h);return ue(p.getItem,u,l).then(d=>ss(d))},getItems(h,l={}){return a(h,l,u=>u.driver.getItems?ue(u.driver.getItems,u.items.map(p=>({key:p.relativeKey,options:p.options})),l).then(p=>p.map(d=>({key:Jd(u.base,d.key),value:ss(d.value)}))):Promise.all(u.items.map(p=>ue(u.driver.getItem,p.relativeKey,p.options).then(d=>({key:p.key,value:ss(d)})))))},getItemRaw(h,l={}){h=Se(h);const{relativeKey:u,driver:p}=t(h);return p.getItemRaw?ue(p.getItemRaw,u,l):ue(p.getItem,u,l).then(d=>Fd(d))},async setItem(h,l,u={}){if(l===void 0)return c.removeItem(h);h=Se(h);const{relativeKey:p,driver:d}=t(h);d.setItem&&(await ue(d.setItem,p,ws(l),u),d.watch||r("update",h))},async setItems(h,l){await a(h,l,async u=>{if(u.driver.setItems)return ue(u.driver.setItems,u.items.map(p=>({key:p.relativeKey,value:ws(p.value),options:p.options})),l);u.driver.setItem&&await Promise.all(u.items.map(p=>ue(u.driver.setItem,p.relativeKey,ws(p.value),p.options)))})},async setItemRaw(h,l,u={}){if(l===void 0)return c.removeItem(h,u);h=Se(h);const{relativeKey:p,driver:d}=t(h);if(d.setItemRaw)await ue(d.setItemRaw,p,l,u);else if(d.setItem)await ue(d.setItem,p,Hd(l),u);else return;d.watch||r("update",h)},async removeItem(h,l={}){typeof l=="boolean"&&(l={removeMeta:l}),h=Se(h);const{relativeKey:u,driver:p}=t(h);p.removeItem&&(await ue(p.removeItem,u,l),(l.removeMeta||l.removeMata)&&await ue(p.removeItem,u+"$",l),p.watch||r("remove",h))},async getMeta(h,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),h=Se(h);const{relativeKey:u,driver:p}=t(h),d=Object.create(null);if(p.getMeta&&Object.assign(d,await ue(p.getMeta,u,l)),!l.nativeOnly){const g=await ue(p.getItem,u+"$",l).then(y=>ss(y));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(d,g))}return d},setMeta(h,l,u={}){return this.setItem(h+"$",l,u)},removeMeta(h,l={}){return this.removeItem(h+"$",l)},async getKeys(h,l={}){var f;h=hs(h);const u=s(h,!0);let p=[];const d=[];let g=!0;for(const w of u){(f=w.driver.flags)!=null&&f.maxDepth||(g=!1);const m=await ue(w.driver.getKeys,w.relativeBase,l);for(const b of m){const I=w.mountpoint+Se(b);p.some(A=>I.startsWith(A))||d.push(I)}p=[w.mountpoint,...p.filter(b=>!b.startsWith(w.mountpoint))]}const y=l.maxDepth!==void 0&&!g;return d.filter(w=>(!y||Qd(w,l.maxDepth))&&Yd(w,h))},async clear(h,l={}){h=hs(h),await Promise.all(s(h,!1).map(async u=>{if(u.driver.clear)return ue(u.driver.clear,u.relativeBase,l);if(u.driver.removeItem){const p=await u.driver.getKeys(u.relativeBase||"",l);return Promise.all(p.map(d=>u.driver.removeItem(d,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(h=>wo(h)))},async watch(h){return await n(),e.watchListeners.push(h),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==h),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(h,l){if(h=hs(h),h&&e.mounts[h])throw new Error(`already mounted at ${h}`);return h&&(e.mountpoints.push(h),e.mountpoints.sort((u,p)=>p.length-u.length)),e.mounts[h]=l,e.watching&&Promise.resolve(mo(l,r,h)).then(u=>{e.unwatch[h]=u}).catch(console.error),c},async unmount(h,l=!0){var u,p;h=hs(h),!(!h||!e.mounts[h])&&(e.watching&&h in e.unwatch&&((p=(u=e.unwatch)[h])==null||p.call(u),delete e.unwatch[h]),l&&await wo(e.mounts[h]),e.mountpoints=e.mountpoints.filter(d=>d!==h),delete e.mounts[h])},getMount(h=""){h=Se(h)+":";const l=t(h);return{driver:l.driver,base:l.base}},getMounts(h="",l={}){return h=Se(h),s(h,l.parents).map(p=>({driver:p.driver,base:p.mountpoint}))},keys:(h,l={})=>c.getKeys(h,l),get:(h,l={})=>c.getItem(h,l),set:(h,l,u={})=>c.setItem(h,l,u),has:(h,l={})=>c.hasItem(h,l),del:(h,l={})=>c.removeItem(h,l),remove:(h,l={})=>c.removeItem(h,l)};return c}function mo(i,e,t){return i.watch?i.watch((s,r)=>e(s,t+r)):()=>{}}async function wo(i){typeof i.dispose=="function"&&await ue(i.dispose)}const tg="idb-keyval";var ig=(i={})=>{const e=i.base&&i.base.length>0?`${i.base}:`:"",t=r=>e+r;let s;return i.dbName&&i.storeName&&(s=nh(i.dbName,i.storeName)),{name:tg,options:i,async hasItem(r){return!(typeof await pn(t(r),s)>"u")},async getItem(r){return await pn(t(r),s)??null},setItem(r,n){return hh(t(r),n,s)},removeItem(r){return ch(t(r),s)},getKeys(){return ah(s)},clear(){return oh(s)}}};const sg="WALLET_CONNECT_V2_INDEXED_DB",rg="keyvaluestorage";let ng=class{constructor(){this.indexedDb=eg({driver:ig({dbName:sg,storeName:rg})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,Gr(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var sr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},bs={exports:{}};(function(){let i;function e(){}i=e,i.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},i.prototype.setItem=function(t,s){this[t]=String(s)},i.prototype.removeItem=function(t){delete this[t]},i.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(s){t[s]=void 0,delete t[s]})},i.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},i.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof sr<"u"&&sr.localStorage?bs.exports=sr.localStorage:typeof window<"u"&&window.localStorage?bs.exports=window.localStorage:bs.exports=new e})();function og(i){var e;return[i[0],Is((e=i[1])!=null?e:"")]}let ag=class{constructor(){this.localStorage=bs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(og)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return Is(t)}async setItem(e,t){this.localStorage.setItem(e,Gr(t))}async removeItem(e){this.localStorage.removeItem(e)}};const cg="wc_storage_version",bo=1,hg=async(i,e,t)=>{const s=cg,r=await e.getItem(s);if(r&&r>=bo){t(e);return}const n=await i.getKeys();if(!n.length){t(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const h=await i.getItem(a);await e.setItem(a,h),o.push(a)}}await e.setItem(s,bo),t(e),lg(i,o)},lg=async(i,e)=>{e.length&&e.forEach(async t=>{await i.removeItem(t)})};let ug=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new ag;this.storage=e;try{const t=new ng;hg(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}};var pg=Object.defineProperty,dg=(i,e,t)=>e in i?pg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vo=(i,e,t)=>dg(i,typeof e!="symbol"?e+"":e,t);let gg=class extends vi{constructor(e){super(),this.opts=e,vo(this,"protocol","wc"),vo(this,"version",2)}};var fg=Object.defineProperty,yg=(i,e,t)=>e in i?fg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,mg=(i,e,t)=>yg(i,e+"",t);let wg=class extends vi{constructor(e,t){super(),this.core=e,this.logger=t,mg(this,"records",new Map)}},bg=class{constructor(e,t){this.logger=e,this.core=t}};class vg extends vi{constructor(e,t){super(),this.relayer=e,this.logger=t}}let Eg=class extends vi{constructor(e){super()}},Ig=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},_g=class extends vi{constructor(e,t){super(),this.relayer=e,this.logger=t}},Pg=class extends vi{constructor(e,t){super(),this.core=e,this.logger=t}},$g=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},Sg=class{constructor(e,t){this.projectId=e,this.logger=t}},Og=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var xg=Object.defineProperty,Ag=(i,e,t)=>e in i?xg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Eo=(i,e,t)=>Ag(i,typeof e!="symbol"?e+"":e,t);let Cg=class{constructor(e){this.opts=e,Eo(this,"protocol","wc"),Eo(this,"version",2)}},Ng=class{constructor(e){this.client=e}};var Rg={};const yc="wc",mc=2,Cr="core",nt=`${yc}@2:${Cr}:`,Tg={logger:"error"},qg={database:":memory:"},jg="crypto",Io="client_ed25519_seed",Dg=N.ONE_DAY,kg="keychain",Ug="0.3",Mg="messages",Lg="0.3",_o=N.SIX_HOURS,Bg="publisher",wc="irn",zg="error",bc="wss://relay.walletconnect.org",Kg="relayer",de={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"},Vg="_subscription",Ue={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Hg=.1,Nr="2.21.1",ee={link_mode:"link_mode",relay:"relay"},vs={inbound:"inbound",outbound:"outbound"},Fg="0.3",Gg="WALLETCONNECT_CLIENT_ID",Po="WALLETCONNECT_LINK_MODE_APPS",Re={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Wg="subscription",Jg="0.3",Qg="pairing",Yg="0.3",Ri={wc_pairingDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:N.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:N.ONE_DAY,prompt:!1,tag:0},res:{ttl:N.ONE_DAY,prompt:!1,tag:0}}},Tt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ve={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Zg="history",Xg="0.3",ef="expirer",Le={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},tf="0.3",sf="verify-api",rf="https://verify.walletconnect.com",vc="https://verify.walletconnect.org",Bi=vc,nf=`${Bi}/v3`,of=[rf,vc],af="echo",cf="https://echo.walletconnect.com",tt={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"},pt={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"},He={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"},xt={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"},At={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"},Ti={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"},hf=.1,lf="event-client",uf=86400,pf="https://pulse.walletconnect.org/batch";function df(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(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,f=0,w=0,m=g.length;w!==m&&g[w]===0;)w++,y++;for(var b=(m-w)*l+1>>>0,I=new Uint8Array(b);w!==m;){for(var A=g[w],P=0,S=b-1;(A!==0||P<f)&&S!==-1;S--,P++)A+=256*I[S]>>>0,I[S]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");f=P,w++}for(var R=b-f;R!==b&&I[R]===0;)R++;for(var v=c.repeat(y);R<b;++R)v+=i.charAt(I[R]);return v}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var f=0,w=0;g[y]===c;)f++,y++;for(var m=(g.length-y)*h+1>>>0,b=new Uint8Array(m);g[y];){var I=t[g.charCodeAt(y)];if(I===255)return;for(var A=0,P=m-1;(I!==0||A<w)&&P!==-1;P--,A++)I+=a*b[P]>>>0,b[P]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");w=A,y++}if(g[y]!==" "){for(var S=m-w;S!==m&&b[S]===0;)S++;for(var R=new Uint8Array(f+(m-S)),v=f;S!==m;)R[v++]=b[S++];return R}}}function d(g){var y=p(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:d}}var gf=df,ff=gf;const Ec=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")},yf=i=>new TextEncoder().encode(i),mf=i=>new TextDecoder().decode(i);class wf{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")}}class bf{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 Ic(this,e)}}class vf{constructor(e){this.decoders=e}or(e){return Ic(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 Ic=(i,e)=>new vf({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Ef{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new wf(e,t,s),this.decoder=new bf(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ls=({name:i,prefix:e,encode:t,decode:s})=>new Ef(i,e,t,s),ts=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=ff(t,e);return Ls({prefix:i,name:e,encode:s,decode:n=>Ec(r(n))})},If=(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},_f=(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},be=({name:i,prefix:e,bitsPerChar:t,alphabet:s})=>Ls({prefix:e,name:i,encode(r){return _f(r,s,t)},decode(r){return If(r,s,t,i)}}),Pf=Ls({prefix:"\0",name:"identity",encode:i=>mf(i),decode:i=>yf(i)});var $f=Object.freeze({__proto__:null,identity:Pf});const Sf=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Of=Object.freeze({__proto__:null,base2:Sf});const xf=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Af=Object.freeze({__proto__:null,base8:xf});const Cf=ts({prefix:"9",name:"base10",alphabet:"0123456789"});var Nf=Object.freeze({__proto__:null,base10:Cf});const Rf=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Tf=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var qf=Object.freeze({__proto__:null,base16:Rf,base16upper:Tf});const jf=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Df=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kf=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Uf=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Mf=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Lf=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Bf=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zf=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Kf=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Vf=Object.freeze({__proto__:null,base32:jf,base32upper:Df,base32pad:kf,base32padupper:Uf,base32hex:Mf,base32hexupper:Lf,base32hexpad:Bf,base32hexpadupper:zf,base32z:Kf});const Hf=ts({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ff=ts({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gf=Object.freeze({__proto__:null,base36:Hf,base36upper:Ff});const Wf=ts({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Jf=ts({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qf=Object.freeze({__proto__:null,base58btc:Wf,base58flickr:Jf});const Yf=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zf=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Xf=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ey=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ty=Object.freeze({__proto__:null,base64:Yf,base64pad:Zf,base64url:Xf,base64urlpad:ey});const _c=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),iy=_c.reduce((i,e,t)=>(i[t]=e,i),[]),sy=_c.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function ry(i){return i.reduce((e,t)=>(e+=iy[t],e),"")}function ny(i){const e=[];for(const t of i){const s=sy[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const oy=Ls({prefix:"🚀",name:"base256emoji",encode:ry,decode:ny});var ay=Object.freeze({__proto__:null,base256emoji:oy}),cy=Pc,$o=128,hy=-128,ly=Math.pow(2,31);function Pc(i,e,t){e=e||[],t=t||0;for(var s=t;i>=ly;)e[t++]=i&255|$o,i/=128;for(;i&hy;)e[t++]=i&255|$o,i>>>=7;return e[t]=i|0,Pc.bytes=t-s+1,e}var uy=Rr,py=128,So=127;function Rr(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw Rr.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&So)<<r:(o&So)*Math.pow(2,r),r+=7}while(o>=py);return Rr.bytes=n-s,t}var dy=Math.pow(2,7),gy=Math.pow(2,14),fy=Math.pow(2,21),yy=Math.pow(2,28),my=Math.pow(2,35),wy=Math.pow(2,42),by=Math.pow(2,49),vy=Math.pow(2,56),Ey=Math.pow(2,63),Iy=function(i){return i<dy?1:i<gy?2:i<fy?3:i<yy?4:i<my?5:i<wy?6:i<by?7:i<vy?8:i<Ey?9:10},_y={encode:cy,decode:uy,encodingLength:Iy},$c=_y;const Oo=(i,e,t=0)=>($c.encode(i,e,t),e),xo=i=>$c.encodingLength(i),Tr=(i,e)=>{const t=e.byteLength,s=xo(i),r=s+xo(t),n=new Uint8Array(r+t);return Oo(i,n,0),Oo(t,n,s),n.set(e,r),new Py(i,t,e,n)};class Py{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}}const Sc=({name:i,code:e,encode:t})=>new $y(i,e,t);class $y{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?Tr(this.code,t):t.then(s=>Tr(this.code,s))}else throw Error("Unknown type, must be binary type")}}const Oc=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Sy=Sc({name:"sha2-256",code:18,encode:Oc("SHA-256")}),Oy=Sc({name:"sha2-512",code:19,encode:Oc("SHA-512")});var xy=Object.freeze({__proto__:null,sha256:Sy,sha512:Oy});const xc=0,Ay="identity",Ac=Ec,Cy=i=>Tr(xc,Ac(i)),Ny={code:xc,name:Ay,encode:Ac,digest:Cy};var Ry=Object.freeze({__proto__:null,identity:Ny});new TextEncoder,new TextDecoder;const Ao={...$f,...Of,...Af,...Nf,...qf,...Vf,...Gf,...Qf,...ty,...ay};({...xy,...Ry});function Ty(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Cc(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Co=Cc("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),rr=Cc("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=Ty(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),qy={utf8:Co,"utf-8":Co,hex:Ao.base16,latin1:rr,ascii:rr,binary:rr,...Ao};function jy(i,e="utf8"){const t=qy[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 Dy=Object.defineProperty,ky=(i,e,t)=>e in i?Dy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xe=(i,e,t)=>ky(i,typeof e!="symbol"?e+"":e,t);class Uy{constructor(e,t){this.core=e,this.logger=t,Xe(this,"keychain",new Map),Xe(this,"name",kg),Xe(this,"version",Ug),Xe(this,"initialized",!1),Xe(this,"storagePrefix",nt),Xe(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),Xe(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),Xe(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),Xe(this,"get",s=>{this.isInitialized();const r=this.keychain.get(s);if(typeof r>"u"){const{message:n}=C("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(n)}return r}),Xe(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=Pe(t,this.name)}get context(){return ke(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,mr(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?wr(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var My=Object.defineProperty,Ly=(i,e,t)=>e in i?My(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ye=(i,e,t)=>Ly(i,typeof e!="symbol"?e+"":e,t);class By{constructor(e,t,s){this.core=e,this.logger=t,ye(this,"name",jg),ye(this,"keychain"),ye(this,"randomSessionIdentifier",xr()),ye(this,"initialized",!1),ye(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),ye(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),ye(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=un(r);return sh(n.publicKey)}),ye(this,"generateKeyPair",()=>{this.isInitialized();const r=Mp();return this.setPrivateKey(r.publicKey,r.privateKey)}),ye(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=un(n),a=this.randomSessionIdentifier;return await rh(a,r,Dg,o)}),ye(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Lp(a,n);return this.setSymKey(c,o)}),ye(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||ms(r);return await this.keychain.set(o,r),o}),ye(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),ye(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),ye(this,"encode",async(r,n,o)=>{this.isInitialized();const a=dc(o),c=Gr(n);if(ro(a))return Kp(c,o==null?void 0:o.encoding);if(so(a)){const p=a.senderPublicKey,d=a.receiverPublicKey;r=await this.generateSharedKey(p,d)}const h=this.getSymKey(r),{type:l,senderPublicKey:u}=a;return Bp({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),ye(this,"decode",async(r,n,o)=>{this.isInitialized();const a=Hp(n,o);if(ro(a)){const c=Vp(n,o==null?void 0:o.encoding);return Is(c)}if(so(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=zp({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return Is(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),ye(this,"getPayloadType",(r,n=We)=>{const o=Wi({encoded:r,encoding:n});return Bt(o.type)}),ye(this,"getPayloadSenderPublicKey",(r,n=We)=>{const o=Wi({encoded:r,encoding:n});return o.senderPublicKey?Ae(o.senderPublicKey,_e):void 0}),this.core=e,this.logger=Pe(t,this.name),this.keychain=s||new Uy(this.core,this.logger)}get context(){return ke(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(Io)}catch{e=xr(),await this.keychain.set(Io,e)}return jy(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zy=Object.defineProperty,Ky=Object.defineProperties,Vy=Object.getOwnPropertyDescriptors,No=Object.getOwnPropertySymbols,Hy=Object.prototype.hasOwnProperty,Fy=Object.prototype.propertyIsEnumerable,qr=(i,e,t)=>e in i?zy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Gy=(i,e)=>{for(var t in e||(e={}))Hy.call(e,t)&&qr(i,t,e[t]);if(No)for(var t of No(e))Fy.call(e,t)&&qr(i,t,e[t]);return i},Wy=(i,e)=>Ky(i,Vy(e)),Ce=(i,e,t)=>qr(i,typeof e!="symbol"?e+"":e,t);class Jy extends bg{constructor(e,t){super(e,t),this.logger=e,this.core=t,Ce(this,"messages",new Map),Ce(this,"messagesWithoutClientAck",new Map),Ce(this,"name",Mg),Ce(this,"version",Lg),Ce(this,"initialized",!1),Ce(this,"storagePrefix",nt),Ce(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}}}),Ce(this,"set",async(s,r,n)=>{this.isInitialized();const o=st(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===vs.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,Wy(Gy({},c),{[o]:r}))}return await this.persist(),o}),Ce(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),Ce(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}),Ce(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=st(r);return typeof n[o]<"u"}),Ce(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=st(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),Ce(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=Pe(e,this.name),this.core=t}get context(){return ke(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,mr(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,mr(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?wr(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?wr(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Qy=Object.defineProperty,Yy=Object.defineProperties,Zy=Object.getOwnPropertyDescriptors,Ro=Object.getOwnPropertySymbols,Xy=Object.prototype.hasOwnProperty,em=Object.prototype.propertyIsEnumerable,jr=(i,e,t)=>e in i?Qy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ls=(i,e)=>{for(var t in e||(e={}))Xy.call(e,t)&&jr(i,t,e[t]);if(Ro)for(var t of Ro(e))em.call(e,t)&&jr(i,t,e[t]);return i},nr=(i,e)=>Yy(i,Zy(e)),Fe=(i,e,t)=>jr(i,typeof e!="symbol"?e+"":e,t);class tm extends vg{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Fe(this,"events",new $t.EventEmitter),Fe(this,"name",Bg),Fe(this,"queue",new Map),Fe(this,"publishTimeout",N.toMiliseconds(N.ONE_MINUTE)),Fe(this,"initialPublishTimeout",N.toMiliseconds(N.ONE_SECOND*15)),Fe(this,"needsTransportRestart",!1),Fe(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==null?void 0:n.ttl)||_o,c=Ss(n),h=(n==null?void 0:n.prompt)||!1,l=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||ai().toString(),p={topic:s,message:r,opts:{ttl:a,relay:c,prompt:h,tag:l,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},d=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const g=new Promise(async y=>{const f=({id:m})=>{p.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(de.publish,f),y(p))};this.relayer.events.on(de.publish,f);const w=It(new Promise((m,b)=>{this.rpcPublish({topic:s,message:r,ttl:a,prompt:h,tag:l,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(m).catch(I=>{this.logger.warn(I,I==null?void 0:I.message),b(I)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await w,this.events.removeListener(de.publish,f)}catch(m){this.queue.set(u,nr(ls({},p),{attempt:1})),this.logger.warn(m,m==null?void 0:m.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:s,message:r,opts:n}}),await It(g,this.publishTimeout,d)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(u)}}),Fe(this,"on",(s,r)=>{this.events.on(s,r)}),Fe(this,"once",(s,r)=>{this.events.once(s,r)}),Fe(this,"off",(s,r)=>{this.events.off(s,r)}),Fe(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=Pe(t,this.name),this.registerEventListeners()}get context(){return ke(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=_o,prompt:h,tag:l,id:u,attestation:p,tvf:d}=e,g={method:ki(Ss().protocol).publish,params:ls({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:p},d),id:u};we((t=g.params)==null?void 0:t.prompt)&&((s=g.params)==null||delete s.prompt),we((r=g.params)==null?void 0:r.tag)&&((n=g.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const y=await this.relayer.request(g);return this.relayer.events.emit(de.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,nr(ls({},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(nr(ls({},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(Ei.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(de.connection_stalled);return}this.checkQueue()}),this.relayer.on(de.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var im=Object.defineProperty,sm=(i,e,t)=>e in i?im(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Gt=(i,e,t)=>sm(i,typeof e!="symbol"?e+"":e,t);class rm{constructor(){Gt(this,"map",new Map),Gt(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),Gt(this,"get",e=>this.map.get(e)||[]),Gt(this,"exists",(e,t)=>this.get(e).includes(t)),Gt(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)}),Gt(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var nm=Object.defineProperty,om=Object.defineProperties,am=Object.getOwnPropertyDescriptors,To=Object.getOwnPropertySymbols,cm=Object.prototype.hasOwnProperty,hm=Object.prototype.propertyIsEnumerable,Dr=(i,e,t)=>e in i?nm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qi=(i,e)=>{for(var t in e||(e={}))cm.call(e,t)&&Dr(i,t,e[t]);if(To)for(var t of To(e))hm.call(e,t)&&Dr(i,t,e[t]);return i},or=(i,e)=>om(i,am(e)),Q=(i,e,t)=>Dr(i,typeof e!="symbol"?e+"":e,t);class lm extends _g{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Q(this,"subscriptions",new Map),Q(this,"topicMap",new rm),Q(this,"events",new $t.EventEmitter),Q(this,"name",Wg),Q(this,"version",Jg),Q(this,"pending",new Map),Q(this,"cached",[]),Q(this,"initialized",!1),Q(this,"storagePrefix",nt),Q(this,"subscribeTimeout",N.toMiliseconds(N.ONE_MINUTE)),Q(this,"initialSubscribeTimeout",N.toMiliseconds(N.ONE_SECOND*15)),Q(this,"clientId"),Q(this,"batchSubscribeTopicsLimit",500),Q(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Q(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=Ss(r),o={topic:s,relay:n,transportType:r==null?void 0: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}}),Q(this,"unsubscribe",async(s,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(s,r.id,r):await this.unsubscribeByTopic(s,r)}),Q(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),Q(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),Q(this,"on",(s,r)=>{this.events.on(s,r)}),Q(this,"once",(s,r)=>{this.events.once(s,r)}),Q(this,"off",(s,r)=>{this.events.off(s,r)}),Q(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),Q(this,"start",async()=>{await this.onConnect()}),Q(this,"stop",async()=>{await this.onDisconnect()}),Q(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Q(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)}),Q(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Ei.pulse,async()=>{await this.checkPending()}),this.events.on(Re.created,async s=>{const r=Re.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(Re.deleted,async s=>{const r=Re.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=Pe(t,this.name),this.clientId=""}get context(){return ke(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=Ss(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=J("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==null?void 0:s.transportType)===ee.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:ki(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==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((s==null?void 0:s.transportType)===ee.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},N.toMiliseconds(N.ONE_SECOND)),a;const c=new Promise(async l=>{const u=p=>{p.topic===e&&(this.events.removeListener(Re.created,u),l(p.id))};this.events.on(Re.created,u);try{const p=await It(new Promise((d,g)=>{this.relayer.request(n).catch(y=>{this.logger.warn(y,y==null?void 0:y.message),g(y)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Re.created,u),l(p)}catch{}}),h=await It(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(de.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:ki(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 It(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(de.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:ki(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 It(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(de.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:ki(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,or(qi({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,qi({},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,qi({},t)),this.topicMap.set(t.topic,e),this.events.emit(Re.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}=C("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(Re.deleted,or(qi({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Re.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(Re.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=C("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=>or(qi({},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 Sl(N.toMiliseconds(N.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}=C("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 st(e+await this.getClientId())}}var um=Object.defineProperty,qo=Object.getOwnPropertySymbols,pm=Object.prototype.hasOwnProperty,dm=Object.prototype.propertyIsEnumerable,kr=(i,e,t)=>e in i?um(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,jo=(i,e)=>{for(var t in e||(e={}))pm.call(e,t)&&kr(i,t,e[t]);if(qo)for(var t of qo(e))dm.call(e,t)&&kr(i,t,e[t]);return i},H=(i,e,t)=>kr(i,typeof e!="symbol"?e+"":e,t);class gm extends Eg{constructor(e){super(e),H(this,"protocol","wc"),H(this,"version",2),H(this,"core"),H(this,"logger"),H(this,"events",new $t.EventEmitter),H(this,"provider"),H(this,"messages"),H(this,"subscriber"),H(this,"publisher"),H(this,"name",Kg),H(this,"transportExplicitlyClosed",!1),H(this,"initialized",!1),H(this,"connectionAttemptInProgress",!1),H(this,"relayUrl"),H(this,"projectId"),H(this,"packageName"),H(this,"bundleId"),H(this,"hasExperiencedNetworkDisruption",!1),H(this,"pingTimeout"),H(this,"heartBeatTimeout",N.toMiliseconds(N.THIRTY_SECONDS+N.FIVE_SECONDS)),H(this,"reconnectTimeout"),H(this,"connectPromise"),H(this,"reconnectInProgress",!1),H(this,"requestsInFlight",[]),H(this,"connectTimeout",N.toMiliseconds(N.ONE_SECOND*15)),H(this,"request",async t=>{var s,r;this.logger.debug("Publishing Request Payload");const n=t.id||ai().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}}),H(this,"resetPingTimeout",()=>{Ps()&&(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==null?void 0:o.message)}},this.heartBeatTimeout))}),H(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),H(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(de.connect)}),H(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),H(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(de.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),H(this,"registerProviderListeners",()=>{this.provider.on(Ue.payload,this.onPayloadHandler),this.provider.on(Ue.connect,this.onConnectHandler),this.provider.on(Ue.disconnect,this.onDisconnectHandler),this.provider.on(Ue.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Pe(e.logger,this.name):Wr(Ns({level:e.logger||zg})),this.messages=new Jy(this.logger,e.core),this.subscriber=new lm(this,this.logger),this.publisher=new tm(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||bc,this.projectId=e.projectId,ll()?this.packageName=On():ul()&&(this.bundleId=On()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return ke(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:ee.relay},vs.outbound)}async subscribe(e,t){var s,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((s=t==null?void 0:t.internal)==null?void 0:s.throwOnFailedPublish)>"u"?!0:(r=t==null?void 0:t.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const h=l=>{l.topic===e&&(this.subscriber.off(Re.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Re.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,jo({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 It(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 yo())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((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==null?void 0: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=ae(N.FIVE_MINUTES),n={topic:s,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,n)}this.events.emit(de.message,e),await this.recordMessageEvent(e,vs.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(Ue.disconnect,n),await It(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(Ue.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(Ue.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Ue.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,N.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,s,r,n;if(Ps())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==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new ze(new ih(yl({sdkVersion:Nr,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}),Jr(e)){if(!e.method.endsWith(Vg))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:ee.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(jo({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Qr(e)&&this.events.emit(de.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,vs.inbound),this.events.emit(de.message,e))}async acknowledgePayload(e){const t=Rs(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Ue.payload,this.onPayloadHandler),this.provider.off(Ue.connect,this.onConnectHandler),this.provider.off(Ue.disconnect,this.onDisconnectHandler),this.provider.off(Ue.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await yo();Ud(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(s=>this.logger.error(s,s==null?void 0:s.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Ei.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Bd())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t==null?void 0:t.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(de.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},N.toMiliseconds(Hg)))))}isInitialized(){if(!this.initialized){const{message:e}=C("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 fm(){}function Do(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 ko(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Uo(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const ym="[object RegExp]",mm="[object String]",wm="[object Number]",bm="[object Boolean]",Mo="[object Arguments]",vm="[object Symbol]",Em="[object Date]",Im="[object Map]",_m="[object Set]",Pm="[object Array]",$m="[object Function]",Sm="[object ArrayBuffer]",ar="[object Object]",Om="[object Error]",xm="[object DataView]",Am="[object Uint8Array]",Cm="[object Uint8ClampedArray]",Nm="[object Uint16Array]",Rm="[object Uint32Array]",Tm="[object BigUint64Array]",qm="[object Int8Array]",jm="[object Int16Array]",Dm="[object Int32Array]",km="[object BigInt64Array]",Um="[object Float32Array]",Mm="[object Float64Array]";function Lm(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function Bm(i,e,t){return Ui(i,e,void 0,void 0,void 0,void 0,t)}function Ui(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 zi(i,e,n,o)}return zi(i,e,n,o)}function zi(i,e,t,s){if(Object.is(i,e))return!0;let r=Uo(i),n=Uo(e);if(r===Mo&&(r=ar),n===Mo&&(n=ar),r!==n)return!1;switch(r){case mm:return i.toString()===e.toString();case wm:{const c=i.valueOf(),h=e.valueOf();return Lm(c,h)}case bm:case Em:case vm:return Object.is(i.valueOf(),e.valueOf());case ym:return i.source===e.source&&i.flags===e.flags;case $m: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 Im:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!Ui(h,e.get(c),c,i,e,t,s))return!1;return!0}case _m:{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(d=>Ui(u,d,void 0,i,e,t,s));if(p===-1)return!1;h.splice(p,1)}return!0}case Pm:case Am:case Cm:case Nm:case Rm:case Tm:case qm:case jm:case Dm:case km:case Um:case Mm:{if(typeof Buffer<"u"&&Buffer.isBuffer(i)!==Buffer.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!Ui(i[c],e[c],c,i,e,t,s))return!1;return!0}case Sm:return i.byteLength!==e.byteLength?!1:zi(new Uint8Array(i),new Uint8Array(e),t,s);case xm:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:zi(new Uint8Array(i),new Uint8Array(e),t,s);case Om:return i.name===e.name&&i.message===e.message;case ar:{if(!(zi(i.constructor,e.constructor,t,s)||Do(i)&&Do(e)))return!1;const c=[...Object.keys(i),...ko(i)],h=[...Object.keys(e),...ko(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 d=e[u];if(!Ui(p,d,u,i,e,t,s))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function zm(i,e){return Bm(i,e,fm)}var Km=Object.defineProperty,Lo=Object.getOwnPropertySymbols,Vm=Object.prototype.hasOwnProperty,Hm=Object.prototype.propertyIsEnumerable,Ur=(i,e,t)=>e in i?Km(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Bo=(i,e)=>{for(var t in e||(e={}))Vm.call(e,t)&&Ur(i,t,e[t]);if(Lo)for(var t of Lo(e))Hm.call(e,t)&&Ur(i,t,e[t]);return i},$e=(i,e,t)=>Ur(i,typeof e!="symbol"?e+"":e,t);class zt extends Ig{constructor(e,t,s,r=nt,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,$e(this,"map",new Map),$e(this,"version",Fg),$e(this,"cached",[]),$e(this,"initialized",!1),$e(this,"getKey"),$e(this,"storagePrefix",nt),$e(this,"recentlyDeleted",[]),$e(this,"recentlyDeletedLimit",200),$e(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!we(o)?this.map.set(this.getKey(o),o):fd(o)?this.map.set(o.id,o):yd(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),$e(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())}),$e(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),$e(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>zm(a[c],o[c]))):this.values)),$e(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=Bo(Bo({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),$e(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=Pe(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return ke(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}=C("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:s}=C("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}=C("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}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Fm=Object.defineProperty,Gm=(i,e,t)=>e in i?Fm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,z=(i,e,t)=>Gm(i,typeof e!="symbol"?e+"":e,t);class Wm{constructor(e,t){this.core=e,this.logger=t,z(this,"name",Qg),z(this,"version",Yg),z(this,"events",new Fr),z(this,"pairings"),z(this,"initialized",!1),z(this,"storagePrefix",nt),z(this,"ignoredPayloadTypes",[yt]),z(this,"registeredMethods",[]),z(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),z(this,"register",({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]}),z(this,"create",async s=>{this.isInitialized();const r=xr(),n=await this.core.crypto.setSymKey(r),o=ae(N.FIVE_MINUTES),a={protocol:wc},c={topic:n,expiry:o,relay:a,active:!1,methods:s==null?void 0:s.methods},h=oo({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:s==null?void 0:s.methods});return this.events.emit(Tt.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:s==null?void 0:s.transportType}),{topic:n,uri:h}}),z(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s==null?void 0:s.uri,trace:[tt.pairing_started]}});this.isValidPair(s,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=no(s.uri);r.props.properties.topic=n,r.addTrace(tt.pairing_uri_validation_success),r.addTrace(tt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(tt.existing_pairing),l.active)throw r.setError(pt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(tt.pairing_not_expired)}const u=c||ae(N.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(tt.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(Tt.create,p),r.addTrace(tt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(tt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(pt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(d){throw r.setError(pt.subscribe_pairing_topic_failure),d}return r.addTrace(tt.subscribe_pairing_topic_success),p}),z(this,"activate",async({topic:s})=>{this.isInitialized();const r=ae(N.FIVE_MINUTES);this.core.expirer.set(s,r),await this.pairings.update(s,{active:!0,expiry:r})}),z(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}=Ct();this.events.once(W("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),z(this,"updateExpiry",async({topic:s,expiry:r})=>{this.isInitialized(),await this.pairings.update(s,{expiry:r})}),z(this,"updateMetadata",async({topic:s,metadata:r})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:r})}),z(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),z(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",J("USER_DISCONNECTED")),await this.deletePairing(r))}),z(this,"formatUriFromPairing",s=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=s,c=this.core.crypto.keychain.get(r);return oo({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),z(this,"sendRequest",async(s,r,n)=>{const o=jt(r,n),a=await this.core.crypto.encode(s,o),c=Ri[r].req;return this.core.history.set(s,o),this.core.relayer.publish(s,a,c),o.id}),z(this,"sendResult",async(s,r,n)=>{const o=Rs(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=Ri[c].res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),z(this,"sendError",async(s,r,n)=>{const o=ga(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=Ri[c]?Ri[c].res:Ri.unregistered_method.res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),z(this,"deletePairing",async(s,r)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,J("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),r?Promise.resolve():this.core.expirer.del(s)])}),z(this,"cleanup",async()=>{const s=this.pairings.getAll().filter(r=>vt(r.expiry));await Promise.all(s.map(r=>this.deletePairing(r.topic)))}),z(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)}}),z(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)}}),z(this,"onPairingPingRequest",async(s,r)=>{const{id:n}=r;try{this.isValidPing({topic:s}),await this.sendResult(n,s,!0),this.events.emit(Tt.ping,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),z(this,"onPairingPingResponse",(s,r)=>{const{id:n}=r;setTimeout(()=>{ut(r)?this.events.emit(W("pairing_ping",n),{}):it(r)&&this.events.emit(W("pairing_ping",n),{error:r.error})},500)}),z(this,"onPairingDeleteRequest",async(s,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(Tt.delete,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),z(this,"onUnknownRpcMethodRequest",async(s,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=J("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)}}),z(this,"onUnknownRpcMethodResponse",s=>{this.registeredMethods.includes(s)||this.logger.error(J("WC_METHOD_UNSUPPORTED",s))}),z(this,"isValidPair",(s,r)=>{var n;if(!Oe(s)){const{message:a}=C("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(pt.malformed_pairing_uri),new Error(a)}if(!gd(s.uri)){const{message:a}=C("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(pt.malformed_pairing_uri),new Error(a)}const o=no(s==null?void 0:s.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=C("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(pt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=C("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(pt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&N.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(pt.pairing_expired);const{message:a}=C("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),z(this,"isValidPing",async s=>{if(!Oe(s)){const{message:n}=C("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),z(this,"isValidDisconnect",async s=>{if(!Oe(s)){const{message:n}=C("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),z(this,"isValidPairingTopic",async s=>{if(!re(s,!1)){const{message:r}=C("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(r)}if(!this.pairings.keys.includes(s)){const{message:r}=C("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(r)}if(vt(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:r}=C("EXPIRED",`pairing topic: ${s}`);throw new Error(r)}}),this.core=e,this.logger=Pe(t,this.name),this.pairings=new zt(this.core,this.logger,this.name,this.storagePrefix)}get context(){return ke(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(de.message,async e=>{const{topic:t,message:s,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==ee.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);Jr(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):Qr(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(Le.expired,async e=>{const{topic:t}=qa(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Tt.expire,{topic:t}))})}}var Jm=Object.defineProperty,Qm=(i,e,t)=>e in i?Jm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,me=(i,e,t)=>Qm(i,typeof e!="symbol"?e+"":e,t);class Ym extends wg{constructor(e,t){super(e,t),this.core=e,this.logger=t,me(this,"records",new Map),me(this,"events",new $t.EventEmitter),me(this,"name",Zg),me(this,"version",Xg),me(this,"cached",[]),me(this,"initialized",!1),me(this,"storagePrefix",nt),me(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)}),me(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:ae(N.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ve.created,o)}),me(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=it(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(Ve.updated,r))}),me(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))),me(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(Ve.deleted,n)}}),this.persist()}),me(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),me(this,"on",(s,r)=>{this.events.on(s,r)}),me(this,"once",(s,r)=>{this.events.once(s,r)}),me(this,"off",(s,r)=>{this.events.off(s,r)}),me(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=Pe(t,this.name)}get context(){return ke(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:jt(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}=C("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ve.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=C("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(Ve.created,e=>{const t=Ve.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ve.updated,e=>{const t=Ve.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ve.deleted,e=>{const t=Ve.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(Ei.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{N.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Ve.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Zm=Object.defineProperty,Xm=(i,e,t)=>e in i?Zm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ee=(i,e,t)=>Xm(i,typeof e!="symbol"?e+"":e,t);class ew extends Pg{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ee(this,"expirations",new Map),Ee(this,"events",new $t.EventEmitter),Ee(this,"name",ef),Ee(this,"version",tf),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",nt),Ee(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)}),Ee(this,"has",s=>{try{const r=this.formatTarget(s);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ee(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(Le.created,{target:n,expiration:o})}),Ee(this,"get",s=>{this.isInitialized();const r=this.formatTarget(s);return this.getExpiration(r)}),Ee(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(Le.deleted,{target:r,expiration:n})}}),Ee(this,"on",(s,r)=>{this.events.on(s,r)}),Ee(this,"once",(s,r)=>{this.events.once(s,r)}),Ee(this,"off",(s,r)=>{this.events.off(s,r)}),Ee(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=Pe(t,this.name)}get context(){return ke(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 ml(e);if(typeof e=="number")return wl(e);const{message:t}=C("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(Le.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=C("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}=C("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(s),new Error(s)}return t}checkExpiry(e,t){const{expiry:s}=t;N.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Le.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(Ei.pulse,()=>this.checkExpirations()),this.events.on(Le.created,e=>{const t=Le.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Le.expired,e=>{const t=Le.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Le.deleted,e=>{const t=Le.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var tw=Object.defineProperty,iw=(i,e,t)=>e in i?tw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,se=(i,e,t)=>iw(i,typeof e!="symbol"?e+"":e,t);class sw extends $g{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,se(this,"name",sf),se(this,"abortController"),se(this,"isDevEnv"),se(this,"verifyUrlV3",nf),se(this,"storagePrefix",nt),se(this,"version",mc),se(this,"publicKey"),se(this,"fetchPromise"),se(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&N.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),se(this,"register",async r=>{if(!Pi()||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=pi(),l=this.startAbortTimer(N.ONE_SECOND*5),u=await new Promise((p,d)=>{const g=()=>{window.removeEventListener("message",f),h.body.removeChild(y),d("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const y=h.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",g,{signal:this.abortController.signal});const f=w=>{if(w.data&&typeof w.data=="string")try{const m=JSON.parse(w.data);if(m.type==="verify_attestation"){if(gr(m.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(y),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",f),p(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};h.body.appendChild(y),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),se(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(gr(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==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),se(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(N.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}),se(this,"getVerifyUrl",r=>{let n=r||Bi;return of.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Bi}`),n=Bi),n}),se(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(N.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)}}),se(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),se(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),se(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")}}),se(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),se(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}),se(this,"validateAttestation",(r,n)=>{const o=Gp(r,n.publicKey),a={hasExpired:N.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Pe(t,this.name),this.abortController=new AbortController,this.isDevEnv=Zr(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return ke(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),N.toMiliseconds(e))}}var rw=Object.defineProperty,nw=(i,e,t)=>e in i?rw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,zo=(i,e,t)=>nw(i,typeof e!="symbol"?e+"":e,t);class ow extends Sg{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,zo(this,"context",af),zo(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${cf}/${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=Pe(t,this.context)}}var aw=Object.defineProperty,Ko=Object.getOwnPropertySymbols,cw=Object.prototype.hasOwnProperty,hw=Object.prototype.propertyIsEnumerable,Mr=(i,e,t)=>e in i?aw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ji=(i,e)=>{for(var t in e||(e={}))cw.call(e,t)&&Mr(i,t,e[t]);if(Ko)for(var t of Ko(e))hw.call(e,t)&&Mr(i,t,e[t]);return i},he=(i,e,t)=>Mr(i,typeof e!="symbol"?e+"":e,t);class lw extends Og{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,he(this,"context",lf),he(this,"storagePrefix",nt),he(this,"storageVersion",hf),he(this,"events",new Map),he(this,"shouldPersist",!1),he(this,"init",async()=>{if(!Zr())try{const r={eventId:An(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ra(this.core.relayer.protocol,this.core.relayer.version,Nr)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),he(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,h=An(),l=this.core.projectId||"",u=Date.now(),p=ji({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}),he(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 ji(ji({},a),this.setMethods(a.eventId))}),he(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),he(this,"setEventListeners",()=>{this.core.heartbeat.on(Ei.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{N.fromMiliseconds(Date.now())-N.fromMiliseconds(r.timestamp)>uf&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),he(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),he(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)}),he(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)}),he(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),he(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,ji(ji({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),he(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)}}),he(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${pf}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Nr}${n}`,{method:"POST",body:JSON.stringify(r)})}),he(this,"getAppDomain",()=>Na().url),this.logger=Pe(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 uw=Object.defineProperty,Vo=Object.getOwnPropertySymbols,pw=Object.prototype.hasOwnProperty,dw=Object.prototype.propertyIsEnumerable,Lr=(i,e,t)=>e in i?uw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ho=(i,e)=>{for(var t in e||(e={}))pw.call(e,t)&&Lr(i,t,e[t]);if(Vo)for(var t of Vo(e))dw.call(e,t)&&Lr(i,t,e[t]);return i},X=(i,e,t)=>Lr(i,typeof e!="symbol"?e+"":e,t);let gw=class Nc extends gg{constructor(e){var t;super(e),X(this,"protocol",yc),X(this,"version",mc),X(this,"name",Cr),X(this,"relayUrl"),X(this,"projectId"),X(this,"customStoragePrefix"),X(this,"events",new $t.EventEmitter),X(this,"logger"),X(this,"heartbeat"),X(this,"relayer"),X(this,"crypto"),X(this,"storage"),X(this,"history"),X(this,"expirer"),X(this,"pairing"),X(this,"verify"),X(this,"echoClient"),X(this,"linkModeSupportedApps"),X(this,"eventClient"),X(this,"initialized",!1),X(this,"logChunkController"),X(this,"on",(a,c)=>this.events.on(a,c)),X(this,"once",(a,c)=>this.events.once(a,c)),X(this,"off",(a,c)=>this.events.off(a,c)),X(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),X(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ee.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(e==null?void 0: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==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||bc,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Ns({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:Tg.logger,name:Cr}),{logger:n,chunkLoggerController:o}=eh({opts:r,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0: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=Pe(n,this.name),this.heartbeat=new th,this.crypto=new By(this,this.logger,e==null?void 0:e.keychain),this.history=new Ym(this,this.logger),this.expirer=new ew(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new ug(Ho(Ho({},qg),e==null?void 0:e.storageOptions)),this.relayer=new gm({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Wm(this,this.logger),this.verify=new sw(this,this.logger,this.storage),this.echoClient=new ow(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new lw(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Nc(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(Gg,s),t}get context(){return ke(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(Po,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(Po)||[],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 process<"u"&&Rg.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const fw=gw,Rc="wc",Tc=2,qc="client",an=`${Rc}@${Tc}:${qc}:`,cr={name:qc,logger:"error"},Fo="WALLETCONNECT_DEEPLINK_CHOICE",yw="proposal",Go="Proposal expired",mw="session",Wt=N.SEVEN_DAYS,ww="engine",le={wc_sessionPropose:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1104},res:{ttl:N.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1106},res:{ttl:N.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1112},res:{ttl:N.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1114},res:{ttl:N.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:N.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:N.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1119}}},hr={min:N.FIVE_MINUTES,max:N.SEVEN_DAYS},et={idle:"IDLE",active:"ACTIVE"},Wo={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},bw="request",vw=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Ew="wc",Iw="auth",_w="authKeys",Pw="pairingTopics",$w="requests",Bs=`${Ew}@${1.5}:${Iw}:`,Es=`${Bs}:PUB_KEY`;var Sw=Object.defineProperty,Ow=Object.defineProperties,xw=Object.getOwnPropertyDescriptors,Jo=Object.getOwnPropertySymbols,Aw=Object.prototype.hasOwnProperty,Cw=Object.prototype.propertyIsEnumerable,Br=(i,e,t)=>e in i?Sw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Y=(i,e)=>{for(var t in e||(e={}))Aw.call(e,t)&&Br(i,t,e[t]);if(Jo)for(var t of Jo(e))Cw.call(e,t)&&Br(i,t,e[t]);return i},Ie=(i,e)=>Ow(i,xw(e)),E=(i,e,t)=>Br(i,typeof e!="symbol"?e+"":e,t);class Nw extends Ng{constructor(e){super(e),E(this,"name",ww),E(this,"events",new Fr),E(this,"initialized",!1),E(this,"requestQueue",{state:et.idle,queue:[]}),E(this,"sessionRequestQueue",{state:et.idle,queue:[]}),E(this,"requestQueueDelay",N.ONE_SECOND),E(this,"expectedPairingMethodMap",new Map),E(this,"recentlyDeletedMap",new Map),E(this,"recentlyDeletedLimit",200),E(this,"relayMessageCache",[]),E(this,"pendingSessions",new Map),E(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(le)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay)))}),E(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=Ie(Y({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=hd(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 P=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=P.active}}catch(P){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),P}if(!l||!p){const{topic:P,uri:S}=await this.client.core.pairing.create();l=P,u=S}if(!l){const{message:P}=C("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(P)}const d=await this.client.core.crypto.generateKeyPair(),g=le.wc_sessionPropose.req.ttl||N.FIVE_MINUTES,y=ae(g),f=Ie(Y(Y({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:wc}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:mt()}),w=W("session_connect",f.id),{reject:m,resolve:b,done:I}=Ct(g,Go),A=({id:P})=>{P===f.id&&(this.client.events.off("proposal_expire",A),this.pendingSessions.delete(f.id),this.events.emit(w,{error:{message:Go,code:0}}))};return this.client.events.on("proposal_expire",A),this.events.once(w,({error:P,session:S})=>{this.client.events.off("proposal_expire",A),P?m(P):S&&b(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:u,approval:I}}),E(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}}),E(this,"approve",async t=>{var s,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(s=t==null?void 0:t.id)==null?void 0:s.toString(),trace:[He.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(v){throw o.setError(xt.no_internet_connection),v}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(v){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(xt.proposal_not_found),v}try{await this.isValidApprove(t)}catch(v){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(xt.session_approve_namespace_validation_failure),v}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=t,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:y,requiredNamespaces:f,optionalNamespaces:w}=d;let m=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});m||(m=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:He.session_approve_started,properties:{topic:g,trace:[He.session_approve_started,He.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),I=y.publicKey,A=await this.client.core.crypto.generateSharedKey(b,I),P=Y(Y(Y({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:b,metadata:this.client.metadata},expiry:ae(Wt)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),S=ee.relay;m.addTrace(He.subscribing_session_topic);try{await this.client.core.relayer.subscribe(A,{transportType:S})}catch(v){throw m.setError(xt.subscribe_session_topic_failure),v}m.addTrace(He.subscribe_session_topic_success);const R=Ie(Y({},P),{topic:A,requiredNamespaces:f,optionalNamespaces:w,pairingTopic:g,acknowledged:!1,self:P.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:b,transportType:ee.relay});await this.client.session.set(A,R),m.addTrace(He.store_session);try{m.addTrace(He.publishing_session_settle),await this.sendRequest({topic:A,method:"wc_sessionSettle",params:P,throwOnFailedPublish:!0}).catch(v=>{throw m==null||m.setError(xt.session_settle_publish_failure),v}),m.addTrace(He.session_settle_publish_success),m.addTrace(He.publishing_session_approve),await this.sendResult({id:a,topic:g,result:{relay:{protocol:c??"irn"},responderPublicKey:b},throwOnFailedPublish:!0}).catch(v=>{throw m==null||m.setError(xt.session_approve_publish_failure),v}),m.addTrace(He.session_approve_publish_success)}catch(v){throw this.client.logger.error(v),this.client.session.delete(A,J("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(A),v}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:y.metadata}),await this.client.proposal.delete(a,J("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(A,ae(Wt)),{topic:A,acknowledged:()=>Promise.resolve(this.client.session.get(A))}}),E(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:le.wc_sessionPropose.reject}),await this.client.proposal.delete(s,J("USER_DISCONNECTED")))}),E(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}=Ct(),c=mt(),h=ai().toString(),l=this.client.session.get(s).namespaces;return this.events.once(W("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}}),E(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=mt(),{done:n,resolve:o,reject:a}=Ct();return this.events.once(W("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,ae(Wt)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),E(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:s,request:r,topic:n,expiry:o=le.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===ee.relay&&await this.confirmOnlineStateOrThrow();const c=mt(),h=ai().toString(),{done:l,resolve:u,reject:p}=Ct(o,"Request expired. Please try again.");this.events.once(W("session_request",c),({error:w,result:m})=>{w?p(w):u(m)});const d="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:{request:Ie(Y({},r),{expiryTimestamp:ae(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(w=>p(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const y={request:Ie(Y({},r),{expiryTimestamp:ae(o)}),chainId:s},f=this.shouldSetTVF(d,y);return await Promise.all([new Promise(async w=>{await this.sendRequest(Y({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:y,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,y)})).catch(m=>p(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),w()}),new Promise(async w=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const b=await Il(this.client.core.storage,Fo);await bl({id:c,topic:n,wcDeepLink:b})}w()}),l()]).then(w=>w[2])}),E(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===ee.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);ut(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):it(r)&&await this.sendError({id:n,topic:s,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),E(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=mt(),n=ai().toString(),{done:o,resolve:a,reject:c}=Ct();this.events.once(W("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}))}),E(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:s,event:r,chainId:n}=t,o=ai().toString(),a=mt();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),E(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:J("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}=C("MISMATCHED_TOPIC",`Session or pairing topic not found: ${s}`);throw new Error(r)}}),E(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(s=>pd(s,t)))),E(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),E(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?ee.link_mode:ee.relay;o===ee.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:p,exp:d,nbf:g,methods:y=[],expiry:f}=t,w=[...t.resources||[]],{topic:m,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:b}});const I=await this.client.core.crypto.generateKeyPair(),A=ms(I);if(await Promise.all([this.client.auth.authKeys.set(Es,{responseTopic:A,publicKey:I}),this.client.auth.pairingTopics.set(A,{topic:A,pairingTopic:m})]),await this.client.core.relayer.subscribe(A,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),y.length>0){const{namespace:$}=ui(a[0]);let U=gu($,"request",y);ys(w)&&(U=yu(U,w.pop())),w.push(U)}const P=f&&f>le.wc_sessionAuthenticate.req.ttl?f:le.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:p??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:d,nbf:g,resources:w},requester:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:ae(P)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},v={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:ae(le.wc_sessionPropose.req.ttl),id:mt()},{done:k,resolve:q,reject:D}=Ct(P,"Request expired"),M=mt(),_=W("session_connect",v.id),x=W("session_request",M),O=async({error:$,session:U})=>{this.events.off(x,T),$?D($):U&&q({session:U})},T=async $=>{var U,L,B;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),$.error){const oe=J("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return $.error.code===oe.code?void 0:(this.events.off(_,O),D($.error.message))}await this.deleteProposal(v.id),this.events.off(_,O);const{cacaos:Z,responder:G}=$.result,ie=[],ce=[];for(const oe of Z){await kn({cacao:oe,projectId:this.client.core.projectId})||(this.client.logger.error(oe,"Signature verification failed"),D(J("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ot}=oe,ot=ys(Ot.resources),Ye=[br(Ot.iss)],at=$s(Ot.iss);if(ot){const ct=Un(ot),is=Mn(ot);ie.push(...ct),Ye.push(...is)}for(const ct of Ye)ce.push(`${ct}:${at}`)}const ve=await this.client.core.crypto.generateSharedKey(I,G.publicKey);let ne;ie.length>0&&(ne={topic:ve,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:G,controller:G.publicKey,expiry:ae(Wt),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:lo([...new Set(ie)],[...new Set(ce)]),transportType:o},await this.client.core.relayer.subscribe(ve,{transportType:o}),await this.client.session.set(ve,ne),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:G.metadata}),ne=this.client.session.get(ve)),(U=this.client.metadata.redirect)!=null&&U.linkMode&&(L=G.metadata.redirect)!=null&&L.linkMode&&(B=G.metadata.redirect)!=null&&B.universal&&s&&(this.client.core.addLinkModeSupportedApp(G.metadata.redirect.universal),this.client.session.update(ve,{transportType:ee.link_mode})),q({auths:Z,session:ne})};this.events.once(_,O),this.events.once(x,T);let j;try{if(n){const $=jt("wc_sessionAuthenticate",S,M);this.client.core.history.set(m,$);const U=await this.client.core.crypto.encode("",$,{type:es,encoding:Et});j=cs(s,m,U)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:S,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:M}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:v,expiry:le.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:v.id})])}catch($){throw this.events.off(_,O),this.events.off(x,T),$}return await this.setProposal(v.id,v),await this.setAuthRequest(M,{request:Ie(Y({},S),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:j??b,response:k}}),E(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[At.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(Ti.no_internet_connection),f}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(Ti.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||ee.relay;a===ee.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=ms(c),u={type:yt,receiverPublicKey:c,senderPublicKey:h},p=[],d=[];for(const f of r){if(!await kn({cacao:f,projectId:this.client.core.projectId})){n.setError(Ti.invalid_cacao);const A=J("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:A,encodeOpts:u}),new Error(A.message)}n.addTrace(At.cacaos_verified);const{p:w}=f,m=ys(w.resources),b=[br(w.iss)],I=$s(w.iss);if(m){const A=Un(m),P=Mn(m);p.push(...A),b.push(...P)}for(const A of b)d.push(`${A}:${I}`)}const g=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(At.create_authenticated_session_topic);let y;if((p==null?void 0:p.length)>0){y={topic:g,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ae(Wt),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:lo([...new Set(p)],[...new Set(d)]),transportType:a},n.addTrace(At.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(f){throw n.setError(Ti.subscribe_authenticated_session_topic_failure),f}n.addTrace(At.subscribe_authenticated_session_topic_success),await this.client.session.set(g,y),n.addTrace(At.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(At.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(f){throw n.setError(Ti.authenticated_session_approve_publish_failure),f}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}}),E(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===ee.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ms(o),h={type:yt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:s,topic:c,error:r,encodeOpts:h,rpcOpts:le.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,J("USER_DISCONNECTED"))}),E(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return Ka(s,r)}),E(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)}),E(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)}}),E(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,J("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(Fo).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,J("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=et.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),E(this,"deleteProposal",async(t,s)=>{if(s)try{const r=this.client.proposal.get(t),n=this.client.core.eventClient.getEvent({topic:r.pairingTopic});n==null||n.setError(xt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,J("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),E(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=et.idle,this.client.events.emit("session_request_expire",{id:t}))}),E(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)])}),E(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}))}),E(this,"setProposal",async(t,s)=>{this.client.core.expirer.set(t,ae(le.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),E(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=ee.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})}),E(this,"setPendingSessionRequest",async t=>{const{id:s,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ae(le.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})}),E(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=jt(r,n,c);let d;const g=!!l;try{const w=g?Et:We;d=await this.client.core.crypto.encode(s,p,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),w}let y;if(vw.includes(r)){const w=st(JSON.stringify(p)),m=st(d);y=await this.client.core.verify.register({id:m,decryptedId:w})}const f=le[r].req;if(f.attestation=y,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(s,p),g){const w=cs(l,s,d);await global.Linking.openURL(w,this.client.name)}else{const w=le[r].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=Ie(Y({},u),{correlationId:p.id}),h?(w.internal=Ie(Y({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,d,w)):this.client.core.relayer.publish(s,d,w).catch(m=>this.client.logger.error(m))}return p.id}),E(this,"sendResult",async t=>{const{id:s,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=Rs(s,n);let l;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const g=u?Et:We;l=await this.client.core.crypto.encode(r,h,Ie(Y({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let p,d;try{p=await this.client.core.history.get(r,s);const g=p.request;try{this.shouldSetTVF(g.method,g.params)&&(d=this.getTVFParams(s,g.params,n))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),g}if(u){const g=cs(c,r,l);await global.Linking.openURL(g,this.client.name)}else{const g=p.request.method,y=le[g].res;y.tvf=Ie(Y({},d),{correlationId:s}),o?(y.internal=Ie(Y({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,y)):this.client.core.relayer.publish(r,l,y).catch(f=>this.client.logger.error(f))}await this.client.core.history.resolve(h)}),E(this,"sendError",async t=>{const{id:s,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=ga(s,n);let l;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=u?Et:We;l=await this.client.core.crypto.encode(r,h,Ie(Y({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),d}let p;try{p=await this.client.core.history.get(r,s)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${r}, ${s}) failed`),d}if(u){const d=cs(c,r,l);await global.Linking.openURL(d,this.client.name)}else{const d=p.request.method,g=a||le[d].res;this.client.core.relayer.publish(r,l,g)}await this.client.core.history.resolve(h)}),E(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;vt(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=>{vt(r.expiryTimestamp)&&s.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...s.map(r=>this.deleteProposal(r))])}),E(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),E(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),E(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===et.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=et.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=et.idle}),E(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}`)}}),E(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}`)}}),E(this,"onRelayEventUnknownPayload",t=>{const{topic:s}=t,{message:r}=C("MISSING_OR_INVALID",`Decoded payload on topic ${s} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),E(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)}),E(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==null||h.setError(pt.proposal_listener_not_found)),this.isValidConnect(Y({},r.params));const l=a.expiryTimestamp||ae(le.wc_sessionPropose.req.ttl),u=Y({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,u);const p=await this.getVerifyContext({attestationId:n,hash:st(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});h==null||h.addTrace(tt.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:le.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),E(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(ut(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(it(s)){await this.client.proposal.delete(n,J("USER_DISCONNECTED"));const o=W("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})}}),E(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,d=[...this.pendingSessions.values()].find(f=>f.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const g=this.client.proposal.get(d.proposalId),y=Ie(Y(Y(Y({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),{transportType:ee.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(W("session_connect",d.proposalId),{session:y}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.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)}}),E(this,"onSessionSettleResponse",async(t,s)=>{const{id:r}=s;ut(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(W("session_approve",r),{})):it(s)&&(await this.client.session.delete(t,J("USER_DISCONNECTED")),this.events.emit(W("session_approve",r),{error:s.error}))}),E(this,"onSessionUpdateRequest",async(t,s)=>{const{params:r,id:n}=s;try{const o=`${t}_session_update`,a=Ni.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:J("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Y({topic:t},r));try{Ni.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 Ni.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)}}),E(this,"isRequestOutOfSync",(t,s)=>s.toString().slice(0,-3)<t.toString().slice(0,-3)),E(this,"onSessionUpdateResponse",(t,s)=>{const{id:r}=s,n=W("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ut(s)?this.events.emit(W("session_update",r),{}):it(s)&&this.events.emit(W("session_update",r),{error:s.error})}),E(this,"onSessionExtendRequest",async(t,s)=>{const{id:r}=s;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ae(Wt)),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)}}),E(this,"onSessionExtendResponse",(t,s)=>{const{id:r}=s,n=W("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ut(s)?this.events.emit(W("session_extend",r),{}):it(s)&&this.events.emit(W("session_extend",r),{error:s.error})}),E(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)}}),E(this,"onSessionPingResponse",(t,s)=>{const{id:r}=s,n=W("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);ut(s)?this.events.emit(W("session_ping",r),{}):it(s)&&this.events.emit(W("session_ping",r),{error:s.error})},500)}),E(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(de.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:J("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),E(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(Y({topic:o},p));const d=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:st(JSON.stringify(jt("wc_sessionRequest",p,u))),encryptedId:h,metadata:d.peer.metadata,transportType:l}),y={id:u,topic:o,params:p,verifyContext:g};await this.setPendingSessionRequest(y),l===ee.link_mode&&(s=d.peer.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp((r=d.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(d){await this.sendError({id:u,topic:o,error:d}),this.client.logger.error(d)}}),E(this,"onSessionRequestResponse",(t,s)=>{const{id:r}=s,n=W("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ut(s)?this.events.emit(W("session_request",r),{result:s.result}):it(s)&&this.events.emit(W("session_request",r),{error:s.error})}),E(this,"onSessionEventRequest",async(t,s)=>{const{id:r,params:n}=s;try{const o=`${t}_session_event_${n.event.name}`,a=Ni.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Y({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),Ni.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),E(this,"onSessionAuthenticateResponse",(t,s)=>{const{id:r}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:s}),ut(s)?this.events.emit(W("session_request",r),{result:s.result}):it(s)&&this.events.emit(W("session_request",r),{error:s.error})}),E(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:st(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),d={requester:h,pairingTopic:r,id:n.id,authPayload:l,verifyContext:p,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:d,pairingTopic:r,transportType:c}),c===ee.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),d={type:yt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:d,rpcOpts:le.wc_sessionAuthenticate.autoReject,appLink:p})}}),E(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),E(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=et.idle,this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay))}),E(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=W("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(W("session_request",n.request.id),{error:s})})}),E(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===et.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=et.active,this.emitSessionRequest(t)}catch(s){this.client.logger.error(s)}}),E(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),E(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:jt("wc_sessionPropose",Ie(Y({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id)})}),E(this,"isValidConnect",async t=>{if(!Oe(t)){const{message:h}=C("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(we(s)||await this.isValidPairingTopic(s),!Pd(c)){const{message:h}=C("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!we(r)&&Pt(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(!we(n)&&Pt(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),we(o)||this.validateSessionProps(o,"sessionProperties"),!we(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)}`)}}),E(this,"validateNamespaces",(t,s)=>{const r=_d(t,"connect()",s);if(r)throw new Error(r.message)}),E(this,"isValidApprove",async t=>{if(!Oe(t))throw new Error(C("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=tr(r,"approve()");if(h)throw new Error(h.message);const l=go(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!re(n,!0)){const{message:u}=C("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(we(o)||this.validateSessionProps(o,"sessionProperties"),!we(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(", ")}`)}}),E(this,"isValidReject",async t=>{if(!Oe(t)){const{message:n}=C("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:s,reason:r}=t;if(this.checkRecentlyDeleted(s),await this.isValidProposalId(s),!Sd(r)){const{message:n}=C("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),E(this,"isValidSessionSettleRequest",t=>{if(!Oe(t)){const{message:h}=C("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:s,controller:r,namespaces:n,expiry:o}=t;if(!fc(s)){const{message:h}=C("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=md(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=tr(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(vt(o)){const{message:h}=C("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),E(this,"isValidUpdate",async t=>{if(!Oe(t)){const{message:c}=C("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=tr(r,"update()");if(o)throw new Error(o.message);const a=go(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),E(this,"isValidExtend",async t=>{if(!Oe(t)){const{message:r}=C("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:s}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s)}),E(this,"isValidRequest",async t=>{if(!Oe(t)){const{message:c}=C("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(!po(a,n)){const{message:c}=C("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!Od(r)){const{message:c}=C("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!Cd(a,n,r.method)){const{message:c}=C("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!qd(o,hr)){const{message:c}=C("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${hr.min} and ${hr.max}`);throw new Error(c)}}),E(this,"isValidRespond",async t=>{var s;if(!Oe(t)){const{message:o}=C("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==null?void 0:t.response)!=null&&s.id&&this.cleanupAfterResponse(t),o}if(!xd(n)){const{message:o}=C("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),E(this,"isValidPing",async t=>{if(!Oe(t)){const{message:r}=C("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),E(this,"isValidEmit",async t=>{if(!Oe(t)){const{message:a}=C("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(!po(o,n)){const{message:a}=C("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Ad(r)){const{message:a}=C("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Nd(o,n,r.name)){const{message:a}=C("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),E(this,"isValidDisconnect",async t=>{if(!Oe(t)){const{message:r}=C("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),E(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(!re(r,!1))throw new Error("uri is required parameter");if(!re(n,!1))throw new Error("domain is required parameter");if(!re(o,!1))throw new Error("nonce is required parameter");if([...new Set(s.map(c=>ui(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ui(s[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),E(this,"getVerifyContext",async t=>{const{attestationId:s,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||Bi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ee.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}),E(this,"validateSessionProps",(t,s)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=C("MISSING_OR_INVALID",`${s} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),E(this,"getPendingAuthRequest",t=>{const s=this.client.auth.requests.get(t);return typeof s=="object"?s:void 0}),E(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)}}}),E(this,"checkRecentlyDeleted",t=>{const s=this.recentlyDeletedMap.get(t);if(s){const{message:r}=C("MISSING_OR_INVALID",`Record was recently deleted - ${s}: ${t}`);throw new Error(r)}}),E(this,"isLinkModeEnabled",(t,s)=>{var r,n,o,a,c,h,l,u,p;return!t||s!==ee.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==null?void 0:t.redirect)==null?void 0:l.universal)!==void 0&&((u=t==null?void 0:t.redirect)==null?void 0:u.universal)!==""&&((p=t==null?void 0:t.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),E(this,"getAppLinkIfEnabled",(t,s)=>{var r;return this.isLinkModeEnabled(t,s)?(r=t==null?void 0:t.redirect)==null?void 0:r.universal:void 0}),E(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const s=xn(t,"topic")||"",r=decodeURIComponent(xn(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:ee.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),E(this,"registerLinkModeListeners",async()=>{var t;if(Zr()||St()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const s=global==null?void 0: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)}}}),E(this,"shouldSetTVF",(t,s)=>{if(!s||t!=="wc_sessionRequest")return!1;const{request:r}=s;return Object.keys(Wo).includes(r.method)}),E(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return Ie(Y({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{}}),E(this,"isValidContractData",t=>{var s;if(!t)return!1;try{const r=(t==null?void 0:t.data)||((s=t==null?void 0: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}),E(this,"extractTxHashesFromResult",(t,s)=>{try{const r=Wo[t];if(typeof s=="string")return[s];const n=s[r.key];if(Je(n))return t==="solana_signAllTransactions"?n.map(o=>eu(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}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(de.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(Es)?this.client.auth.authKeys.get(Es):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===ee.link_mode?Et:We});Jr(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:st(s)})):Qr(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(Le.expired,async e=>{const{topic:t,id:s}=qa(e.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,C("EXPIRED"),!0);if(s&&this.client.auth.requests.keys.includes(s))return await this.deletePendingAuthRequest(s,C("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(Tt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Tt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!re(e,!1)){const{message:t}=C("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}=C("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(vt(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=C("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!re(e,!1)){const{message:t}=C("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}=C("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(vt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=C("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=C("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(re(e,!1)){const{message:t}=C("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=C("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!$d(e)){const{message:t}=C("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=C("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(vt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=C("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class Rw extends zt{constructor(e,t){super(e,t,yw,an),this.core=e,this.logger=t}}let Tw=class extends zt{constructor(e,t){super(e,t,mw,an),this.core=e,this.logger=t}};class qw extends zt{constructor(e,t){super(e,t,bw,an,s=>s.id),this.core=e,this.logger=t}}class jw extends zt{constructor(e,t){super(e,t,_w,Bs,()=>Es),this.core=e,this.logger=t}}class Dw extends zt{constructor(e,t){super(e,t,Pw,Bs),this.core=e,this.logger=t}}class kw extends zt{constructor(e,t){super(e,t,$w,Bs,s=>s.id),this.core=e,this.logger=t}}var Uw=Object.defineProperty,Mw=(i,e,t)=>e in i?Uw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,lr=(i,e,t)=>Mw(i,typeof e!="symbol"?e+"":e,t);class Lw{constructor(e,t){this.core=e,this.logger=t,lr(this,"authKeys"),lr(this,"pairingTopics"),lr(this,"requests"),this.authKeys=new jw(this.core,this.logger),this.pairingTopics=new Dw(this.core,this.logger),this.requests=new kw(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var Bw=Object.defineProperty,zw=(i,e,t)=>e in i?Bw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,K=(i,e,t)=>zw(i,typeof e!="symbol"?e+"":e,t);let Kw=class jc extends Cg{constructor(e){super(e),K(this,"protocol",Rc),K(this,"version",Tc),K(this,"name",cr.name),K(this,"metadata"),K(this,"core"),K(this,"logger"),K(this,"events",new $t.EventEmitter),K(this,"engine"),K(this,"session"),K(this,"proposal"),K(this,"pendingRequest"),K(this,"auth"),K(this,"signConfig"),K(this,"on",(s,r)=>this.events.on(s,r)),K(this,"once",(s,r)=>this.events.once(s,r)),K(this,"off",(s,r)=>this.events.off(s,r)),K(this,"removeListener",(s,r)=>this.events.removeListener(s,r)),K(this,"removeAllListeners",s=>this.events.removeAllListeners(s)),K(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"pair",async s=>{try{return await this.engine.pair(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"approve",async s=>{try{return await this.engine.approve(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"reject",async s=>{try{return await this.engine.reject(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"update",async s=>{try{return await this.engine.update(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"extend",async s=>{try{return await this.engine.extend(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"request",async s=>{try{return await this.engine.request(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"respond",async s=>{try{return await this.engine.respond(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"ping",async s=>{try{return await this.engine.ping(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"emit",async s=>{try{return await this.engine.emit(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"find",s=>{try{return this.engine.find(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}}),K(this,"authenticate",async(s,r)=>{try{return await this.engine.authenticate(s,r)}catch(n){throw this.logger.error(n.message),n}}),K(this,"formatAuthMessage",s=>{try{return this.engine.formatAuthMessage(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"approveSessionAuthenticate",async s=>{try{return await this.engine.approveSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"rejectSessionAuthenticate",async s=>{try{return await this.engine.rejectSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||cr.name,this.metadata=dl(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Wr(Ns({level:(e==null?void 0:e.logger)||cr.logger}));this.core=(e==null?void 0:e.core)||new fw(e),this.logger=Pe(t,this.name),this.session=new Tw(this.core,this.logger),this.proposal=new Rw(this.core,this.logger),this.pendingRequest=new qw(this.core,this.logger),this.engine=new Nw(this),this.auth=new Lw(this.core,this.logger)}static async init(e){const t=new jc(e);return await t.initialize(),t}get context(){return ke(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},N.toMiliseconds(N.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Qo="error",Vw="wss://relay.walletconnect.org",Hw="wc",Fw="universal_provider",us=`${Hw}@2:${Fw}:`,Dc="https://rpc.walletconnect.org/v1/",oi="generic",Gw=`${Dc}bundler`,Ke={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Ww(){}function cn(i){return i==null||typeof i!="object"&&typeof i!="function"}function hn(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Jw(i){if(cn(i))return i;if(Array.isArray(i)||hn(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 Yo(i){return typeof i=="object"&&i!==null}function kc(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Uc(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Qw="[object RegExp]",Mc="[object String]",Lc="[object Number]",Bc="[object Boolean]",zc="[object Arguments]",Yw="[object Symbol]",Zw="[object Date]",Xw="[object Map]",eb="[object Set]",tb="[object Array]",ib="[object ArrayBuffer]",sb="[object Object]",rb="[object DataView]",nb="[object Uint8Array]",ob="[object Uint8ClampedArray]",ab="[object Uint16Array]",cb="[object Uint32Array]",hb="[object Int8Array]",lb="[object Int16Array]",ub="[object Int32Array]",pb="[object Float32Array]",db="[object Float64Array]";function gb(i,e){return li(i,void 0,i,new Map,e)}function li(i,e,t,s=new Map,r=void 0){const n=r==null?void 0:r(i,e,t,s);if(n!=null)return n;if(cn(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]=li(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,li(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(li(a,void 0,t,s,r));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(i))return i.subarray();if(hn(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=li(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),qt(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),qt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),qt(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,qt(o,i,t,s,r),o}if(typeof i=="object"&&fb(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),qt(o,i,t,s,r),o}return i}function qt(i,e,t=i,s,r){const n=[...Object.keys(e),...kc(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=li(e[a],a,t,s,r))}}function fb(i){switch(Uc(i)){case zc:case tb:case ib:case rb:case Bc:case Zw:case pb:case db:case hb:case lb:case ub:case Xw:case Lc:case sb:case Qw:case eb:case Mc:case Yw:case nb:case ob:case ab:case cb:return!0;default:return!1}}function yb(i,e){return gb(i,(t,s,r,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case Lc:case Mc:case Bc:{const o=new i.constructor(i==null?void 0:i.valueOf());return qt(o,i),o}case zc:{const o={};return qt(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function Zo(i){return yb(i)}function Xo(i){return i!==null&&typeof i=="object"&&Uc(i)==="[object Arguments]"}function mb(i){return hn(i)}function wb(i){var t;if(typeof i!="object"||i==null)return!1;if(Object.getPrototypeOf(i)===null)return!0;if(Object.prototype.toString.call(i)!=="[object Object]"){const s=i[Symbol.toStringTag];return s==null||!((t=Object.getOwnPropertyDescriptor(i,Symbol.toStringTag))!=null&&t.writable)?!1:i.toString()===`[object ${s}]`}let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function bb(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=zr(r,o,s,new Map)}return r}function zr(i,e,t,s){if(cn(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(s.has(e))return Jw(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),...kc(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(Xo(a)&&(a={...a}),Xo(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=Zo(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 d=u[p];l[d]=c[d]}c=l}else c=[];const h=t(c,a,o,i,e,s);h!=null?i[o]=h:Array.isArray(a)||Yo(c)&&Yo(a)?i[o]=zr(c,a,t,s):c==null&&wb(a)?i[o]=zr({},a,t,s):c==null&&mb(a)?i[o]=Zo(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function vb(i,...e){return bb(i,...e,Ww)}var Eb=Object.defineProperty,Ib=Object.defineProperties,_b=Object.getOwnPropertyDescriptors,ea=Object.getOwnPropertySymbols,Pb=Object.prototype.hasOwnProperty,$b=Object.prototype.propertyIsEnumerable,ta=(i,e,t)=>e in i?Eb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ps=(i,e)=>{for(var t in e||(e={}))Pb.call(e,t)&&ta(i,t,e[t]);if(ea)for(var t of ea(e))$b.call(e,t)&&ta(i,t,e[t]);return i},Sb=(i,e)=>Ib(i,_b(e));function De(i,e,t){var s;const r=ui(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${Dc}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Kt(i){return i.includes(":")?i.split(":")[1]:i}function Kc(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function Ob(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 ds(i={},e={}){const t=ia(i),s=ia(e);return vb(t,s)}function ia(i){var e,t,s,r,n;const o={};if(!Pt(i))return o;for(const[a,c]of Object.entries(i)){const h=Ms(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],p=c.rpcMap||{},d=hi(a);o[d]=Sb(ps(ps({},o[d]),c),{chains:rt(h,(e=o[d])==null?void 0:e.chains),methods:rt(l,(t=o[d])==null?void 0:t.methods),events:rt(u,(s=o[d])==null?void 0:s.events)}),(Pt(p)||Pt(((r=o[d])==null?void 0:r.rpcMap)||{}))&&(o[d].rpcMap=ps(ps({},p),(n=o[d])==null?void 0:n.rpcMap))}return o}function sa(i){return i.includes(":")?i.split(":")[2]:i}function ra(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=Ms(t)?[t]:s.chains?s.chains:Kc(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function ur(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 Vc={},F=i=>Vc[i],pr=(i,e)=>{Vc[i]=e};var xb=Object.defineProperty,Ab=(i,e,t)=>e in i?xb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Jt=(i,e,t)=>Ab(i,typeof e!="symbol"?e+"":e,t);class Cb{constructor(e){Jt(this,"name","polkadot"),Jt(this,"client"),Jt(this,"httpProviders"),Jt(this,"events"),Jt(this,"namespace"),Jt(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Kt(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var Nb=Object.defineProperty,Rb=Object.defineProperties,Tb=Object.getOwnPropertyDescriptors,na=Object.getOwnPropertySymbols,qb=Object.prototype.hasOwnProperty,jb=Object.prototype.propertyIsEnumerable,Kr=(i,e,t)=>e in i?Nb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oa=(i,e)=>{for(var t in e||(e={}))qb.call(e,t)&&Kr(i,t,e[t]);if(na)for(var t of na(e))jb.call(e,t)&&Kr(i,t,e[t]);return i},aa=(i,e)=>Rb(i,Tb(e)),Qt=(i,e,t)=>Kr(i,typeof e!="symbol"?e+"":e,t);class Db{constructor(e){Qt(this,"name","eip155"),Qt(this,"client"),Qt(this,"chainId"),Qt(this,"namespace"),Qt(this,"httpProviders"),Qt(this,"events"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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||De(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("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(Kt(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==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[h])return u==null?void 0:u[h];const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:aa(oa({},l.sessionProperties||{}),{capabilities:aa(oa({},u||{}),{[h]:p})})})}catch(d){console.warn("Failed to update session with capabilities",d)}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(jt("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`${Gw}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var kb=Object.defineProperty,Ub=(i,e,t)=>e in i?kb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Yt=(i,e,t)=>Ub(i,typeof e!="symbol"?e+"":e,t);class Mb{constructor(e){Yt(this,"name","solana"),Yt(this,"client"),Yt(this,"httpProviders"),Yt(this,"events"),Yt(this,"namespace"),Yt(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Kt(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var Lb=Object.defineProperty,Bb=(i,e,t)=>e in i?Lb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Zt=(i,e,t)=>Bb(i,typeof e!="symbol"?e+"":e,t);class zb{constructor(e){Zt(this,"name","cosmos"),Zt(this,"client"),Zt(this,"httpProviders"),Zt(this,"events"),Zt(this,"namespace"),Zt(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Kt(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var Kb=Object.defineProperty,Vb=(i,e,t)=>e in i?Kb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xt=(i,e,t)=>Vb(i,typeof e!="symbol"?e+"":e,t);class Hb{constructor(e){Xt(this,"name","algorand"),Xt(this,"client"),Xt(this,"httpProviders"),Xt(this,"events"),Xt(this,"namespace"),Xt(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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||De(`${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(Ke.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||De(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new ze(new Qe(s,F("disableProviderPing")))}}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,ei=(i,e,t)=>Gb(i,typeof e!="symbol"?e+"":e,t);class Wb{constructor(e){ei(this,"name","cip34"),ei(this,"client"),ei(this,"httpProviders"),ei(this,"events"),ei(this,"namespace"),ei(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Kt(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 ze(new Qe(s,F("disableProviderPing")))}}var Jb=Object.defineProperty,Qb=(i,e,t)=>e in i?Jb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ti=(i,e,t)=>Qb(i,typeof e!="symbol"?e+"":e,t);class Yb{constructor(e){ti(this,"name","elrond"),ti(this,"client"),ti(this,"httpProviders"),ti(this,"events"),ti(this,"namespace"),ti(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Kt(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var Zb=Object.defineProperty,Xb=(i,e,t)=>e in i?Zb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ii=(i,e,t)=>Xb(i,typeof e!="symbol"?e+"":e,t);class ev{constructor(e){ii(this,"name","multiversx"),ii(this,"client"),ii(this,"httpProviders"),ii(this,"events"),ii(this,"namespace"),ii(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Kt(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var tv=Object.defineProperty,iv=(i,e,t)=>e in i?tv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,si=(i,e,t)=>iv(i,typeof e!="symbol"?e+"":e,t);class sv{constructor(e){si(this,"name","near"),si(this,"client"),si(this,"httpProviders"),si(this,"events"),si(this,"namespace"),si(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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||De(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(Ke.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||De(e,this.namespace);return typeof s>"u"?void 0:new ze(new Qe(s,F("disableProviderPing")))}}var rv=Object.defineProperty,nv=(i,e,t)=>e in i?rv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ri=(i,e,t)=>nv(i,typeof e!="symbol"?e+"":e,t);class ov{constructor(e){ri(this,"name","tezos"),ri(this,"client"),ri(this,"httpProviders"),ri(this,"events"),ri(this,"namespace"),ri(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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||De(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(Ke.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||De(e,this.namespace);return typeof s>"u"?void 0:new ze(new Qe(s))}}var av=Object.defineProperty,cv=(i,e,t)=>e in i?av(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ni=(i,e,t)=>cv(i,typeof e!="symbol"?e+"":e,t);class hv{constructor(e){ni(this,"name",oi),ni(this,"client"),ni(this,"httpProviders"),ni(this,"events"),ni(this,"namespace"),ni(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=ui(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var lv=Object.defineProperty,uv=Object.defineProperties,pv=Object.getOwnPropertyDescriptors,ca=Object.getOwnPropertySymbols,dv=Object.prototype.hasOwnProperty,gv=Object.prototype.propertyIsEnumerable,Vr=(i,e,t)=>e in i?lv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,gs=(i,e)=>{for(var t in e||(e={}))dv.call(e,t)&&Vr(i,t,e[t]);if(ca)for(var t of ca(e))gv.call(e,t)&&Vr(i,t,e[t]);return i},dr=(i,e)=>uv(i,pv(e)),Me=(i,e,t)=>Vr(i,typeof e!="symbol"?e+"":e,t);let fv=class Hc{constructor(e){Me(this,"client"),Me(this,"namespaces"),Me(this,"optionalNamespaces"),Me(this,"sessionProperties"),Me(this,"scopedProperties"),Me(this,"events",new Fr),Me(this,"rpcProviders",{}),Me(this,"session"),Me(this,"providerOpts"),Me(this,"logger"),Me(this,"uri"),Me(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Wr(Ns({level:(e==null?void 0:e.logger)||Qo})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Hc(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:gs({},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,Rs(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:J("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=ra(this.session.namespaces);this.namespaces=ds(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=ra(r.namespaces);return this.namespaces=ds(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===oi?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(Je(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 Kw.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Qo,relayUrl:this.providerOpts.relayUrl||Vw,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=>hi(t)))];pr("client",this.client),pr("events",this.events),pr("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=Ob(t,this.session),r=Kc(s),n=ds(this.namespaces,this.optionalNamespaces),o=dr(gs({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new Db({namespace:o});break;case"algorand":this.rpcProviders[t]=new Hb({namespace:o});break;case"solana":this.rpcProviders[t]=new Mb({namespace:o});break;case"cosmos":this.rpcProviders[t]=new zb({namespace:o});break;case"polkadot":this.rpcProviders[t]=new Cb({namespace:o});break;case"cip34":this.rpcProviders[t]=new Wb({namespace:o});break;case"elrond":this.rpcProviders[t]=new Yb({namespace:o});break;case"multiversx":this.rpcProviders[t]=new ev({namespace:o});break;case"near":this.rpcProviders[t]=new sv({namespace:o});break;case"tezos":this.rpcProviders[t]=new ov({namespace:o});break;default:this.rpcProviders[oi]?this.rpcProviders[oi].updateNamespace(o):this.rpcProviders[oi]=new hv({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&&Je(o)&&this.events.emit("accountsChanged",o.map(sa))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=hi(o),h=ur(o)!==ur(a)?`${c}:${ur(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=dr(gs({},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",dr(gs({},J("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Ke.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[oi]}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=ds(t,s),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,s]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(o=>hi(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=hi(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(sa);if(!Je(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(`${us}/${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(`${us}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${us}/${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(us)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const yv=fv,mv="wc",wv="ethereum_provider",bv=`${mv}@2:${wv}:`,vv="https://rpc.walletconnect.org/v1/",xs=["eth_sendTransaction","personal_sign"],Fc=["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"],As=["chainChanged","accountsChanged"],Gc=["chainChanged","accountsChanged","message","disconnect","connect"],Ev=async()=>{const{createAppKit:i}=await pa(()=>import("./core-f4taWsy5.js").then(e=>e.X),__vite__mapDeps([6,1,2,3,4,5]));return i};var Iv=Object.defineProperty,_v=Object.defineProperties,Pv=Object.getOwnPropertyDescriptors,ha=Object.getOwnPropertySymbols,$v=Object.prototype.hasOwnProperty,Sv=Object.prototype.propertyIsEnumerable,Hr=(i,e,t)=>e in i?Iv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Nt=(i,e)=>{for(var t in e||(e={}))$v.call(e,t)&&Hr(i,t,e[t]);if(ha)for(var t of ha(e))Sv.call(e,t)&&Hr(i,t,e[t]);return i},Di=(i,e)=>_v(i,Pv(e)),Ne=(i,e,t)=>Hr(i,typeof e!="symbol"?e+"":e,t);function Cs(i){return Number(i[0].split(":")[1])}function fs(i){return`0x${i.toString(16)}`}function Ov(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!Je(e))throw new Error("Invalid chains");const c={chains:e,methods:s||xs,events:n||As,rpcMap:Nt({},e.length?{[Cs(e)]:a[Cs(e)]}:{})},h=n==null?void 0:n.filter(d=>!As.includes(d)),l=s==null?void 0:s.filter(d=>!xs.includes(d));if(!t&&!o&&!r&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=(h==null?void 0:h.length)&&(l==null?void 0:l.length)||!t,p={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(r!=null&&r.length?r:Fc))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Gc))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?p:void 0}}class zs{constructor(){Ne(this,"events",new $t.EventEmitter),Ne(this,"namespace","eip155"),Ne(this,"accounts",[]),Ne(this,"signer"),Ne(this,"chainId",1),Ne(this,"modal"),Ne(this,"rpc"),Ne(this,"STORAGE_KEY",bv),Ne(this,"on",(e,t)=>(this.events.on(e,t),this)),Ne(this,"once",(e,t)=>(this.events.once(e,t),this)),Ne(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),Ne(this,"off",(e,t)=>(this.events.off(e,t),this)),Ne(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new zs;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}=Ov(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(Di(Nt({namespaces:Nt({},s&&{[this.namespace]:s})},r&&{optionalNamespaces:{[this.namespace]:r}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:u})).then(p=>{a(p)}).catch(p=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(p.message))})});if(!n)return;const o=_n(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:fs(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==null?void 0: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(Di(Nt({},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=_n(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:fs(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",fs(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",Di(Nt({},J("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",fs(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==null?void 0:e.chains)!=null?t:[],n=(s=e==null?void 0: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==null?void 0:e.methods)||xs:[],c=r.length?(e==null?void 0:e.events)||As:[],h=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],u=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),p=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:r==null?void 0:r.map(d=>this.formatChainId(d)),optionalChains:n.map(d=>this.formatChainId(d)),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?Cs(this.rpc.chains):Cs(this.rpc.optionalChains),this.signer=await yv.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 Ev(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return Uv}),n=r(Di(Nt({},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(Di(Nt({},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&&Je(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=(r==null?void 0:r[n])||this.getRpcUrl(n)})),s&&Je(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s==null?void 0:s.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=(r==null?void 0:r[n])||this.getRpcUrl(n)}))}getRpcUrl(e,t){var s;return((s=this.rpc.rpcMap)==null?void 0:s[e])||`${vv}?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==null?void 0:t.accounts),this.setAccounts(t==null?void 0: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 xv=zs;var Av=Object.defineProperty,Cv=Object.defineProperties,Nv=Object.getOwnPropertyDescriptors,la=Object.getOwnPropertySymbols,Rv=Object.prototype.hasOwnProperty,Tv=Object.prototype.propertyIsEnumerable,ua=(i,e,t)=>e in i?Av(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wc=(i,e)=>{for(var t in e||(e={}))Rv.call(e,t)&&ua(i,t,e[t]);if(la)for(var t of la(e))Tv.call(e,t)&&ua(i,t,e[t]);return i},qv=(i,e)=>Cv(i,Nv(e));function jv(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 Dv=i=>{const[e,t]=i.split(":");return Jc({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function kv(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(Dv).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:jv(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:qv(Wc({},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(g=>({id:g.id,name:g.name,links:g.links})),...(i.desktopWallets||[]).map(g=>({id:g.id,name:g.name,links:{native:g.links.native,universal:g.links.universal}}))],p=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],d=u.filter(g=>!p.includes(g.id));d.length&&(l.customWallets=d)}return l}function Jc(i){return Wc({formatters:void 0,fees:void 0,serializers:void 0},i)}var Uv=Object.freeze({__proto__:null,convertWCMToAppKitOptions:kv,defineChain:Jc});const gE=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:xv,OPTIONAL_EVENTS:Gc,OPTIONAL_METHODS:Fc,REQUIRED_EVENTS:As,REQUIRED_METHODS:xs,default:zs},Symbol.toStringTag,{value:"Module"}));export{qh as H,fn as a,Ph as b,Hv as c,Vv as d,Ts as e,Wv as f,Gv as g,gE as i,Fv as r,Ia as t,jh as w};