@wormhole-foundation/wormhole-connect 3.0.2-beta.0-development → 3.0.2-beta.1-development

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{basic-ChNCp6rI.js → basic-PUjrTVXb.js} +1 -1
  3. package/dist/assets/{evm-DSirgd5b.js → evm-CO5UWnAY.js} +2 -2
  4. package/dist/assets/{index-L-lC4rqb.js → index-1lzfHdT2.js} +1 -1
  5. package/dist/assets/{index-CHfaLf5J.js → index-DBVZDYF7.js} +1 -1
  6. package/dist/assets/index-DKlPX3ZI.js +1 -0
  7. package/dist/assets/{index-BtCrMDAu.js → index-Ddk7n7Ti.js} +1 -1
  8. package/dist/assets/{index-HhyysXFu.js → index-DyUmO4PR.js} +1 -1
  9. package/dist/assets/{index-BiwA3Bbq.js → index-MMzKxP1N.js} +1 -1
  10. package/dist/assets/{secp256k1-Cd7rIav0.js → secp256k1-0LtSM2L1.js} +1 -1
  11. package/dist/assets/{secp256k1-BQBOR8e3.js → secp256k1-DwTU3j1N.js} +1 -1
  12. package/dist/assets/{solana-DcwLWeKT.js → solana-DlGdMBSL.js} +4 -4
  13. package/dist/assets/{w3m-modal-DdptuLHe.js → w3m-modal-DD9Jgepz.js} +1 -1
  14. package/dist/main.js +72 -70
  15. package/dist/src/AppRouter.d.ts.map +1 -1
  16. package/dist/src/config/mainnet/tokens.d.ts.map +1 -1
  17. package/dist/src/config/testnet/tokens.d.ts.map +1 -1
  18. package/dist/src/config/tokens.d.ts +1 -1
  19. package/dist/src/config/tokens.d.ts.map +1 -1
  20. package/dist/src/exports/index.d.ts +2 -2
  21. package/dist/src/exports/index.d.ts.map +1 -1
  22. package/dist/src/hooks/useFetchQuotes.d.ts.map +1 -1
  23. package/dist/src/icons/Chains/PLUME.d.ts.map +1 -1
  24. package/dist/src/icons/PoweredBy.d.ts.map +1 -1
  25. package/dist/src/icons/Routing.d.ts +5 -0
  26. package/dist/src/icons/Routing.d.ts.map +1 -0
  27. package/dist/src/icons/Tokens/PLUME.d.ts.map +1 -1
  28. package/dist/src/store/transferInput.d.ts +1 -1
  29. package/dist/src/store/transferInput.d.ts.map +1 -1
  30. package/dist/src/utils/coingecko.d.ts.map +1 -1
  31. package/dist/src/utils/formatNumber.d.ts +23 -0
  32. package/dist/src/utils/formatNumber.d.ts.map +1 -0
  33. package/dist/src/utils/index.d.ts +3 -1
  34. package/dist/src/utils/index.d.ts.map +1 -1
  35. package/dist/src/utils/routes.d.ts +12 -0
  36. package/dist/src/utils/routes.d.ts.map +1 -0
  37. package/dist/src/views/v2/Bridge/AmountInput/index.d.ts.map +1 -1
  38. package/dist/src/views/v2/Bridge/AssetPicker/TokenItem.d.ts.map +1 -1
  39. package/dist/src/views/v2/Bridge/Routes/SingleRoute.d.ts.map +1 -1
  40. package/dist/src/views/v2/Redeem/TransactionDetails/index.d.ts.map +1 -1
  41. package/dist/src/views/v3/Bridge/AmountInput/index.d.ts.map +1 -1
  42. package/dist/src/views/v3/Bridge/AssetPicker/TokenItem.d.ts.map +1 -1
  43. package/dist/src/views/v3/Bridge/AssetPicker/index.d.ts.map +1 -1
  44. package/dist/src/views/v3/Bridge/GasSlider/index.d.ts.map +1 -1
  45. package/dist/src/views/v3/Bridge/Routes/Eta.d.ts +6 -0
  46. package/dist/src/views/v3/Bridge/Routes/Eta.d.ts.map +1 -0
  47. package/dist/src/views/v3/Bridge/Routes/RouteBadge.d.ts.map +1 -1
  48. package/dist/src/views/v3/Bridge/Routes/RoutesBottomSheet.d.ts +7 -6
  49. package/dist/src/views/v3/Bridge/Routes/RoutesBottomSheet.d.ts.map +1 -1
  50. package/dist/src/views/v3/Bridge/Routes/RoutesLink.d.ts +7 -0
  51. package/dist/src/views/v3/Bridge/Routes/RoutesLink.d.ts.map +1 -0
  52. package/dist/src/views/v3/Bridge/Routes/RoutesList.d.ts +2 -1
  53. package/dist/src/views/v3/Bridge/Routes/RoutesList.d.ts.map +1 -1
  54. package/dist/src/views/v3/Bridge/Routes/RoutesLoader.d.ts +4 -0
  55. package/dist/src/views/v3/Bridge/Routes/RoutesLoader.d.ts.map +1 -0
  56. package/dist/src/views/v3/Bridge/Routes/RoutesModal.d.ts +6 -5
  57. package/dist/src/views/v3/Bridge/Routes/RoutesModal.d.ts.map +1 -1
  58. package/dist/src/views/v3/Bridge/Routes/SingleRoute.d.ts +1 -0
  59. package/dist/src/views/v3/Bridge/Routes/SingleRoute.d.ts.map +1 -1
  60. package/dist/src/views/v3/Bridge/Routes/index.d.ts.map +1 -1
  61. package/dist/src/views/v3/Redeem/TransactionDetails/index.d.ts.map +1 -1
  62. package/lib/account-Br8E7RB6.js +1 -0
  63. package/lib/{account-BTK2b2Fv.mjs → account-CVa_3S2g.mjs} +1 -1
  64. package/lib/{address-8wLqn60W.mjs → address-BApwdEpr.mjs} +96 -96
  65. package/lib/address-BwQqFkyh.js +1 -0
  66. package/lib/address-C2pxq9b2.js +1 -0
  67. package/lib/{address-n0gAFMrZ.mjs → address-f6joE_ig.mjs} +12 -12
  68. package/lib/aptos-CMRGggVs.js +2 -0
  69. package/lib/{aptos-CK-j196x.js → aptos-CTKQNmlP.js} +1 -1
  70. package/lib/{aptos-B-DJQlwt.mjs → aptos-CfFbx7uf.mjs} +9 -9
  71. package/lib/{aptos-Bwcz9wZX.mjs → aptos-fozuppXh.mjs} +3 -3
  72. package/lib/{basic-DHWVLmCq.mjs → basic-BA2aRJJn.mjs} +2 -2
  73. package/lib/{basic-B5ZFelC_.js → basic-DUWaF2I0.js} +1 -1
  74. package/lib/{basic-E2M-9h1u.js → basic-DeiUayOA.js} +1 -1
  75. package/lib/{basic-Pour9Ggp.mjs → basic-DoC8u7J8.mjs} +2 -2
  76. package/lib/{blake2b-C5HyObld.mjs → blake2b-BGxWUAjG.mjs} +23 -23
  77. package/lib/blake2b-Fj1aPKgL.js +1 -0
  78. package/lib/{browser-ponyfill-jK8MKVVg.mjs → browser-ponyfill-D5AN8ZPp.mjs} +1 -1
  79. package/lib/browser-ponyfill-Dn6gsMYK.js +2 -0
  80. package/lib/{chain-Bm6u6eUF.mjs → chain-DAw2I5H8.mjs} +1 -1
  81. package/lib/chain-DnPXlO8g.js +1 -0
  82. package/lib/chunk-KJH4KKG6-BjF7YUcU.js +470 -0
  83. package/lib/{chunk-KJH4KKG6-DJsu-Y-X.mjs → chunk-KJH4KKG6-DmVjhXO7.mjs} +144 -144
  84. package/lib/{constants-Cf2YMjNo.js → constants-BtNs_2F4.js} +1 -1
  85. package/lib/{constants-B7AbX6qr.mjs → constants-Dcc2nVaW.mjs} +3 -3
  86. package/lib/contract-BEHYQLvJ.js +1 -0
  87. package/lib/{contract-llnN6ki0.mjs → contract-BkMAZomO.mjs} +123 -123
  88. package/lib/{core-CF5c7Vev.mjs → core-BHV42Qa0.mjs} +25 -26
  89. package/lib/core-CV23yxnG.js +889 -0
  90. package/lib/create-CHcGblj6.js +1 -0
  91. package/lib/{create-Dm87_0zG.mjs → create-CKLtL7hr.mjs} +1 -1
  92. package/lib/{evm-BYIGg8e4.mjs → evm-Bf7qbM19.mjs} +42 -42
  93. package/lib/{evm-B2hUWkt7.js → evm-ClWkquRx.js} +2 -2
  94. package/lib/{evm-fvvpk-li.mjs → evm-DhMoy8cH.mjs} +6 -6
  95. package/lib/{evm-DFNbMHoa.js → evm-tXmzU9Xp.js} +2 -2
  96. package/lib/executor.js +1 -1
  97. package/lib/executor.mjs +145 -138
  98. package/lib/hosted.js +1 -1
  99. package/lib/hosted.mjs +1 -1
  100. package/lib/{index-Cwo5AKUC.mjs → index-1rCCpdwd.mjs} +5 -5
  101. package/lib/{index-DBCa3k0j.mjs → index-3HvzWPL7.mjs} +9 -9
  102. package/lib/{index-MOwE6ses.mjs → index-B7ztYPhr.mjs} +21 -22
  103. package/lib/index-BM-0SeYB.js +1 -0
  104. package/lib/{index-DiQ8Ytrt.mjs → index-BTnpftLz.mjs} +1 -1
  105. package/lib/{index-BiCMaXJS.js → index-BWQMi6Rj.js} +1 -1
  106. package/lib/index-BbgKw2pu.js +1 -0
  107. package/lib/index-BblcpkoK.js +1 -0
  108. package/lib/index-Bfblsmud.js +1 -0
  109. package/lib/{index-C_0yAOSX.mjs → index-BfkFXEnG.mjs} +25082 -24072
  110. package/lib/{index-fi1sh8vr.mjs → index-BijBPDRn.mjs} +2 -2
  111. package/lib/index-BoquY9R2.js +337 -0
  112. package/lib/index-C2NtsO9Q.js +1 -0
  113. package/lib/{index-CNuk-XLX.mjs → index-C4JmrizV.mjs} +4 -4
  114. package/lib/index-C8TtXpOf.js +1 -0
  115. package/lib/index-CB8kOyIP.js +1 -0
  116. package/lib/index-CInVjUCW.js +1 -0
  117. package/lib/{index-BF11RebI.mjs → index-CLTklDbp.mjs} +1 -1
  118. package/lib/index-CQvgeH_r.js +1 -0
  119. package/lib/{index-DzYjoSJp.mjs → index-CUnOYRFQ.mjs} +23 -24
  120. package/lib/{index-DGh9LzN1.mjs → index-CWe_BTdo.mjs} +31 -31
  121. package/lib/{index-2Bz1Np4K.mjs → index-CZ91lJ9M.mjs} +5 -5
  122. package/lib/{index-Dgy1FO7C.js → index-CgyVnj6U.js} +1 -1
  123. package/lib/{index-BzJcFdt_.mjs → index-Clr2JjoJ.mjs} +44 -44
  124. package/lib/index-CnnCCv6Q.js +1 -0
  125. package/lib/{index-CJnRWlFf.mjs → index-CwxGLNEk.mjs} +48 -49
  126. package/lib/index-D7BLfz05.js +1 -0
  127. package/lib/index-DM7C-wvQ.js +3 -0
  128. package/lib/{index-DhIh3xiW.mjs → index-DNy_sNGr.mjs} +8 -8
  129. package/lib/{index-BZaRg0yd.mjs → index-DVcaDWmz.mjs} +1 -1
  130. package/lib/{index-CsAigASU.mjs → index-DWOP9OBp.mjs} +17 -17
  131. package/lib/{index-CTLz8Fz0.mjs → index-Dda5qc2t.mjs} +13 -14
  132. package/lib/{index-CLBXF_zH.mjs → index-DeaiBvpG.mjs} +16 -16
  133. package/lib/index-HOuGP-7b.js +1 -0
  134. package/lib/{index-Dt2uNp-N.mjs → index-KZve3tYJ.mjs} +4 -4
  135. package/lib/{index-CJDBidKv.mjs → index-SIyXqCAN.mjs} +41 -41
  136. package/lib/index-WhVYPMUr.js +1 -0
  137. package/lib/index-hmjT4xa7.js +1 -0
  138. package/lib/index-ledagFNU.js +1 -0
  139. package/lib/index-pbRVlgcN.js +1 -0
  140. package/lib/{index-BpQXUhR4.mjs → index-qK7AyMAk.mjs} +23 -27
  141. package/lib/index-ttZu99PZ.js +1 -0
  142. package/lib/{index.es-BqRBGIq6.mjs → index.es-BXRQf6Oi.mjs} +25 -26
  143. package/lib/index.es-BjGaOok5.js +11 -0
  144. package/lib/index.es-D6S74vhi.js +27 -0
  145. package/lib/{index.es-DgCZuUzB.mjs → index.es-cOw8juwf.mjs} +741 -737
  146. package/lib/index.js +1 -1
  147. package/lib/index.mjs +17 -16
  148. package/lib/mayan.js +3 -3
  149. package/lib/mayan.mjs +918 -891
  150. package/lib/mint-CL36R6ED.js +1 -0
  151. package/lib/{mint-Dc-VsiAn.mjs → mint-DunEG1jV.mjs} +32 -33
  152. package/lib/ntt.js +1 -1
  153. package/lib/ntt.mjs +2332 -2373
  154. package/lib/platform-7vCWzCny.js +1 -0
  155. package/lib/platform-BKhoO9So.js +1 -0
  156. package/lib/{platform-B95L0Vxv.mjs → platform-BN6LFtXE.mjs} +16 -16
  157. package/lib/{platform-DnP_1wGA.mjs → platform-BYLu9SzP.mjs} +4 -4
  158. package/lib/platform-Bbe26nx7.js +1 -0
  159. package/lib/{platform-DiG7WY9Z.mjs → platform-DCgWqmh1.mjs} +4 -4
  160. package/lib/{provider-jsonrpc-CRABh2gN.mjs → provider-jsonrpc-Bmgnrmpy.mjs} +155 -155
  161. package/lib/provider-jsonrpc-CbtP2Ffg.js +1 -0
  162. package/lib/{secp256k1-zHHDNAlH.mjs → secp256k1-BDQEvyHq.mjs} +1 -1
  163. package/lib/{secp256k1-obBDPYM-.mjs → secp256k1-C77Oh9AA.mjs} +1 -1
  164. package/lib/{secp256k1-2hq3Jk4g.mjs → secp256k1-CCn2vlXj.mjs} +1 -1
  165. package/lib/{secp256k1-B94G4gyy.js → secp256k1-CHAR40au.js} +1 -1
  166. package/lib/{secp256k1-DCcAh19h.js → secp256k1-D-DmPYcJ.js} +1 -1
  167. package/lib/{secp256k1-CjndBUS7.js → secp256k1-DYWDlveU.js} +1 -1
  168. package/lib/{signer-N_ccpPOz.mjs → signer-BIcn81N5.mjs} +18 -18
  169. package/lib/signer-H7atraks.js +1 -0
  170. package/lib/{solana-_Ha4YgiP.mjs → solana-B0QSg7B3.mjs} +30 -30
  171. package/lib/solana-Cs5VyB20.js +900 -0
  172. package/lib/solana-uvHG8JV5.js +1 -0
  173. package/lib/solana-zyfOlbhb.mjs +18 -0
  174. package/lib/{solanaEmbed.esm-DK5RIquB.mjs → solanaEmbed.esm-BqdznDuW.mjs} +623 -622
  175. package/lib/solanaEmbed.esm-D8vtESE6.js +10 -0
  176. package/lib/src/AppRouter.d.ts.map +1 -1
  177. package/lib/src/config/mainnet/tokens.d.ts.map +1 -1
  178. package/lib/src/config/testnet/tokens.d.ts.map +1 -1
  179. package/lib/src/config/tokens.d.ts +1 -1
  180. package/lib/src/config/tokens.d.ts.map +1 -1
  181. package/lib/src/exports/index.d.ts +2 -2
  182. package/lib/src/exports/index.d.ts.map +1 -1
  183. package/lib/src/hooks/useFetchQuotes.d.ts.map +1 -1
  184. package/lib/src/icons/Chains/PLUME.d.ts.map +1 -1
  185. package/lib/src/icons/PoweredBy.d.ts.map +1 -1
  186. package/lib/src/icons/Routing.d.ts +5 -0
  187. package/lib/src/icons/Routing.d.ts.map +1 -0
  188. package/lib/src/icons/Tokens/PLUME.d.ts.map +1 -1
  189. package/lib/src/store/transferInput.d.ts +1 -1
  190. package/lib/src/store/transferInput.d.ts.map +1 -1
  191. package/lib/src/utils/coingecko.d.ts.map +1 -1
  192. package/lib/src/utils/formatNumber.d.ts +23 -0
  193. package/lib/src/utils/formatNumber.d.ts.map +1 -0
  194. package/lib/src/utils/index.d.ts +3 -1
  195. package/lib/src/utils/index.d.ts.map +1 -1
  196. package/lib/src/utils/routes.d.ts +12 -0
  197. package/lib/src/utils/routes.d.ts.map +1 -0
  198. package/lib/src/views/v2/Bridge/AmountInput/index.d.ts.map +1 -1
  199. package/lib/src/views/v2/Bridge/AssetPicker/TokenItem.d.ts.map +1 -1
  200. package/lib/src/views/v2/Bridge/Routes/SingleRoute.d.ts.map +1 -1
  201. package/lib/src/views/v2/Redeem/TransactionDetails/index.d.ts.map +1 -1
  202. package/lib/src/views/v3/Bridge/AmountInput/index.d.ts.map +1 -1
  203. package/lib/src/views/v3/Bridge/AssetPicker/TokenItem.d.ts.map +1 -1
  204. package/lib/src/views/v3/Bridge/AssetPicker/index.d.ts.map +1 -1
  205. package/lib/src/views/v3/Bridge/GasSlider/index.d.ts.map +1 -1
  206. package/lib/src/views/v3/Bridge/Routes/Eta.d.ts +6 -0
  207. package/lib/src/views/v3/Bridge/Routes/Eta.d.ts.map +1 -0
  208. package/lib/src/views/v3/Bridge/Routes/RouteBadge.d.ts.map +1 -1
  209. package/lib/src/views/v3/Bridge/Routes/RoutesBottomSheet.d.ts +7 -6
  210. package/lib/src/views/v3/Bridge/Routes/RoutesBottomSheet.d.ts.map +1 -1
  211. package/lib/src/views/v3/Bridge/Routes/RoutesLink.d.ts +7 -0
  212. package/lib/src/views/v3/Bridge/Routes/RoutesLink.d.ts.map +1 -0
  213. package/lib/src/views/v3/Bridge/Routes/RoutesList.d.ts +2 -1
  214. package/lib/src/views/v3/Bridge/Routes/RoutesList.d.ts.map +1 -1
  215. package/lib/src/views/v3/Bridge/Routes/RoutesLoader.d.ts +4 -0
  216. package/lib/src/views/v3/Bridge/Routes/RoutesLoader.d.ts.map +1 -0
  217. package/lib/src/views/v3/Bridge/Routes/RoutesModal.d.ts +6 -5
  218. package/lib/src/views/v3/Bridge/Routes/RoutesModal.d.ts.map +1 -1
  219. package/lib/src/views/v3/Bridge/Routes/SingleRoute.d.ts +1 -0
  220. package/lib/src/views/v3/Bridge/Routes/SingleRoute.d.ts.map +1 -1
  221. package/lib/src/views/v3/Bridge/Routes/index.d.ts.map +1 -1
  222. package/lib/src/views/v3/Redeem/TransactionDetails/index.d.ts.map +1 -1
  223. package/lib/{sui-CQcQ6w_P.mjs → sui-B38DyOqM.mjs} +44 -44
  224. package/lib/{sui-BplKFZQu.mjs → sui-BpfnZR4f.mjs} +3 -3
  225. package/lib/sui-CT9MWY38.js +1 -0
  226. package/lib/{sui-_hvmCvD8.js → sui-DXQAMRQJ.js} +1 -1
  227. package/lib/{tokens-DNv0ZNvU.js → tokens-CmINcwKk.js} +31 -31
  228. package/lib/{tokens-Dl4YwW18.mjs → tokens-YxAPPVy3.mjs} +1726 -1724
  229. package/lib/transfer-BQ72fByU.js +1 -0
  230. package/lib/transfer-bTW0j9yh.mjs +58 -0
  231. package/lib/units-Ckije3Qv.js +1 -0
  232. package/lib/{units-DPWUSE6J.mjs → units-CtyvuzxQ.mjs} +13 -13
  233. package/lib/unsignedTransaction-C6Qp42VS.js +1 -0
  234. package/lib/{unsignedTransaction-DwcUilyN.mjs → unsignedTransaction-CXB-QCUC.mjs} +18 -18
  235. package/lib/{w3m-modal-BJILsxDp.mjs → w3m-modal-B7LUHLWC.mjs} +2 -2
  236. package/lib/{w3m-modal-D4CpFxO2.mjs → w3m-modal-BOTzBqbc.mjs} +2 -2
  237. package/lib/{w3m-modal-CrfHWSrF.js → w3m-modal-BTb03-7B.js} +1 -1
  238. package/lib/{w3m-modal-CBG2MSPp.js → w3m-modal-xmdf4r6V.js} +1 -1
  239. package/lib/web3-COTIsLs8.js +22 -0
  240. package/lib/{address-B-XN4tFw.mjs → web3-DYVeiqSa.mjs} +6599 -6576
  241. package/package.json +32 -32
  242. package/dist/assets/index-BWPgrXHs.js +0 -1
  243. package/lib/account-cRt2xMoW.js +0 -1
  244. package/lib/address-BGujeWtN.js +0 -22
  245. package/lib/address-C7DIAk4M.js +0 -1
  246. package/lib/address-KNhRm6oe.js +0 -1
  247. package/lib/aptos-f5TqmvqV.js +0 -2
  248. package/lib/blake2b-B-MRXUPb.js +0 -1
  249. package/lib/browser-ponyfill-CE6vRkjp.js +0 -2
  250. package/lib/chain-Hsn22HAP.js +0 -1
  251. package/lib/chunk-KJH4KKG6-CoyI75Ig.js +0 -470
  252. package/lib/contract-D2fTrJgn.js +0 -1
  253. package/lib/core-v0G9f7LX.js +0 -889
  254. package/lib/create-DoZZ7ciL.js +0 -1
  255. package/lib/index-B8-KKWD-.js +0 -1
  256. package/lib/index-BHbvgOMD.js +0 -1
  257. package/lib/index-BHfUgvSV.js +0 -1
  258. package/lib/index-BTKC7Hou.js +0 -1
  259. package/lib/index-BWXglAWd.js +0 -1
  260. package/lib/index-Bpp8C4u8.js +0 -1
  261. package/lib/index-CF2fHBHJ.js +0 -3
  262. package/lib/index-CTPz98nv.js +0 -1
  263. package/lib/index-ClMoiji-.js +0 -1
  264. package/lib/index-ClsVcH6F.js +0 -1
  265. package/lib/index-CqOI6LVu.js +0 -1
  266. package/lib/index-DCz_4mcz.js +0 -1
  267. package/lib/index-DKksdvND.js +0 -335
  268. package/lib/index-DRv3ZpVL.js +0 -1
  269. package/lib/index-DYqo8IhM.js +0 -1
  270. package/lib/index-DZubce9o.js +0 -1
  271. package/lib/index-DprM_IpB.js +0 -1
  272. package/lib/index-DshEQYMA.js +0 -1
  273. package/lib/index-JrM783SN.js +0 -1
  274. package/lib/index.es-C6YhioMN.js +0 -27
  275. package/lib/index.es-D3Xxxr8I.js +0 -11
  276. package/lib/mint-DlXC3sGi.js +0 -1
  277. package/lib/platform-B1XoDKoN.js +0 -1
  278. package/lib/platform-COuZC5Zc.js +0 -1
  279. package/lib/platform-NG3efAb2.js +0 -1
  280. package/lib/provider-jsonrpc-pXNHQF7n.js +0 -1
  281. package/lib/signer-CCa6npZ3.js +0 -1
  282. package/lib/solana-BJ3aReZw.mjs +0 -18
  283. package/lib/solana-BwyVgP30.js +0 -1
  284. package/lib/solana-CanFuMgA.js +0 -900
  285. package/lib/solanaEmbed.esm-C--1F7Lx.js +0 -10
  286. package/lib/sui-Bs83Gy5Z.js +0 -1
  287. package/lib/units-BvcKDiAx.js +0 -1
  288. package/lib/unsignedTransaction-dN_5EJf5.js +0 -1
  289. package/lib/web3-Bu_6UejS.mjs +0 -67
  290. package/lib/web3-Doz_0RHD.js +0 -1
@@ -1,11 +0,0 @@
1
- "use strict";const He=require("./index-DKksdvND.js"),q=require("./address-BGujeWtN.js"),u=require("./index.es-C6YhioMN.js");function Oi(i,{strict:e=!0}={}){return!i||typeof i!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(i):i.startsWith("0x")}function Tr(i){return Oi(i,{strict:!1})?Math.ceil((i.length-2)/2):i.length}const Ao="2.23.2";let di={getDocsUrl:({docsBaseUrl:i,docsPath:e="",docsSlug:t})=>e?`${i??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${Ao}`};class Ot extends Error{constructor(e,t={}){var a;const s=(()=>{var c;return t.cause instanceof Ot?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),r=t.cause instanceof Ot&&t.cause.docsPath||t.docsPath,n=(a=di.getDocsUrl)==null?void 0:a.call(di,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...s?[`Details: ${s}`]:[],...di.version?[`Version: ${di.version}`]:[]].join(`
2
- `);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Ao}walk(e){return xo(this,e)}}function xo(i,e){return e!=null&&e(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?xo(i.cause,e):e?null:i}class Ro extends Ot{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 ai(i,{dir:e,size:t=32}={}){return typeof i=="string"?lc(i,{dir:e,size:t}):uc(i,{dir:e,size:t})}function lc(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new Ro({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function uc(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new Ro({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 pc extends Ot{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 dc extends Ot{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ci(i,{size:e}){if(Tr(i)>e)throw new dc({givenSize:Tr(i),maxSize:e})}function zs(i,e={}){const{signed:t}=e;e.size&&ci(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 gc(i,e={}){return Number(zs(i,e))}const fc=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Hs(i,e={}){return typeof i=="number"||typeof i=="bigint"?No(i,e):typeof i=="string"?wc(i,e):typeof i=="boolean"?yc(i,e):Co(i,e)}function yc(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?(ci(t,{size:e.size}),ai(t,{size:e.size})):t}function Co(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=fc[i[r]];const s=`0x${t}`;return typeof e.size=="number"?(ci(s,{size:e.size}),ai(s,{dir:"right",size:e.size})):s}function No(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 pc({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?ai(a,{size:s}):a}const mc=new TextEncoder;function wc(i,e={}){const t=mc.encode(i);return Co(t,e)}const bc=new TextEncoder;function vc(i,e={}){return typeof i=="number"||typeof i=="bigint"?Ic(i,e):typeof i=="boolean"?Ec(i,e):Oi(i)?To(i,e):jo(i,e)}function Ec(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?(ci(t,{size:e.size}),ai(t,{size:e.size})):t}const it={zero:48,nine:57,A:65,F:70,a:97,f:102};function jr(i){if(i>=it.zero&&i<=it.nine)return i-it.zero;if(i>=it.A&&i<=it.F)return i-(it.A-10);if(i>=it.a&&i<=it.f)return i-(it.a-10)}function To(i,e={}){let t=i;e.size&&(ci(t,{size:e.size}),t=ai(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=jr(s.charCodeAt(a++)),h=jr(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new Ot(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function Ic(i,e){const t=No(i,e);return To(t)}function jo(i,e={}){const t=bc.encode(i);return typeof e.size=="number"?(ci(t,{size:e.size}),ai(t,{dir:"right",size:e.size})):t}function ss(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function _c(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ti(i,...e){if(!_c(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 Pc(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ss(i.outputLen),ss(i.blockLen)}function Vs(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 qo(i,e){Ti(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Bi=BigInt(2**32-1),qr=BigInt(32);function $c(i,e=!1){return e?{h:Number(i&Bi),l:Number(i>>qr&Bi)}:{h:Number(i>>qr&Bi)|0,l:Number(i&Bi)|0}}function Sc(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}=$c(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Oc=(i,e,t)=>i<<t|e>>>32-t,Ac=(i,e,t)=>e<<t|i>>>32-t,xc=(i,e,t)=>e<<t-32|i>>>64-t,Rc=(i,e,t)=>i<<t-32|e>>>64-t,Tt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Cc(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Nc(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Tc(i,e){return i<<32-e|i>>>e}const kr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function jc(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Dr(i){for(let e=0;e<i.length;e++)i[e]=jc(i[e])}function qc(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function vr(i){return typeof i=="string"&&(i=qc(i)),Ti(i),i}function kc(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Ti(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 ko{clone(){return this._cloneInto()}}function Do(i){const e=s=>i().update(vr(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Dc(i=32){if(Tt&&typeof Tt.getRandomValues=="function")return Tt.getRandomValues(new Uint8Array(i));if(Tt&&typeof Tt.randomBytes=="function")return Tt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Fo=[],Uo=[],Mo=[],Fc=BigInt(0),gi=BigInt(1),Uc=BigInt(2),Mc=BigInt(7),Lc=BigInt(256),Bc=BigInt(113);for(let i=0,e=gi,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Fo.push(2*(5*s+t)),Uo.push((i+1)*(i+2)/2%64);let r=Fc;for(let n=0;n<7;n++)e=(e<<gi^(e>>Mc)*Bc)%Lc,e&Uc&&(r^=gi<<(gi<<BigInt(n))-gi);Mo.push(r)}const[zc,Hc]=Sc(Mo,!0),Fr=(i,e,t)=>t>32?xc(i,e,t):Oc(i,e,t),Ur=(i,e,t)=>t>32?Rc(i,e,t):Ac(i,e,t);function Vc(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],p=Fr(h,l,1)^t[a],d=Ur(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=p,i[o+g+1]^=d}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Uo[o],c=Fr(r,n,a),h=Ur(r,n,a),l=Fo[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]^=zc[s],i[1]^=Hc[s]}t.fill(0)}class Er extends ko{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,ss(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Cc(this.state)}keccak(){kr||Dr(this.state32),Vc(this.state32,this.rounds),kr||Dr(this.state32),this.posOut=0,this.pos=0}update(e){Vs(this);const{blockLen:t,state:s}=this;e=vr(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){Vs(this,!1),Ti(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 ss(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(qo(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 Er(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 Kc=(i,e,t)=>Do(()=>new Er(e,i,t)),Lo=Kc(1,136,256/8);function Bo(i,e){const t=e||"hex",s=Lo(Oi(i,{strict:!1})?vc(i):i);return t==="bytes"?s:Hs(s)}class Gc 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 vs=new Gc(8192);function Wc(i,e){if(vs.has(`${i}.${e}`))return vs.get(`${i}.${e}`);const t=i.substring(2).toLowerCase(),s=Bo(jo(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 vs.set(`${i}.${e}`,n),n}function Jc(i){const e=Bo(`0x${i.substring(4)}`).substring(26);return Wc(`0x${e}`)}async function Qc({hash:i,signature:e}){const t=Oi(i)?i:Hs(i),{secp256k1:s}=await Promise.resolve().then(()=>require("./secp256k1-CjndBUS7.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:p,yParity:d}=e,g=Number(d??p),f=Mr(g);return new s.Signature(zs(h),zs(l)).addRecoveryBit(f)}const o=Oi(e)?e:Hs(e),a=gc(`0x${o.slice(130)}`),c=Mr(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Mr(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 Yc({hash:i,signature:e}){return Jc(await Qc({hash:i,signature:e}))}function Zc(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),p=l.charCodeAt(0);if(e[p]!==255)throw new TypeError(l+" is ambiguous");e[p]=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,p=0,d=0;const g=h.length;for(;d!==g&&h[d]===0;)d++,l++;const f=(g-d)*n+1>>>0,w=new Uint8Array(f);for(;d!==g;){let m=h[d],v=0;for(let P=f-1;(m!==0||v<p)&&P!==-1;P--,v++)m+=256*w[P]>>>0,w[P]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");p=v,d++}let y=f-p;for(;y!==f&&w[y]===0;)y++;let b=s.repeat(l);for(;y<f;++y)b+=i.charAt(w[y]);return b}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,p=0,d=0;for(;h[l]===s;)p++,l++;const g=(h.length-l)*r+1>>>0,f=new Uint8Array(g);for(;l<h.length;){const m=h.charCodeAt(l);if(m>255)return;let v=e[m];if(v===255)return;let P=0;for(let R=g-1;(v!==0||P<d)&&R!==-1;R--,P++)v+=t*f[R]>>>0,f[R]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");d=P,l++}let w=g-d;for(;w!==g&&f[w]===0;)w++;const y=new Uint8Array(p+(g-w));let b=p;for(;w!==g;)y[b++]=f[w++];return y}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 Xc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const zo=Zc(Xc),eh=":";function Xt(i){const[e,t]=i.split(eh);return{namespace:e,reference:t}}function Lr(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 Ho(i,e){return i.includes(":")?[i]:e.chains||[]}var th=Object.defineProperty,ih=Object.defineProperties,sh=Object.getOwnPropertyDescriptors,Br=Object.getOwnPropertySymbols,rh=Object.prototype.hasOwnProperty,nh=Object.prototype.propertyIsEnumerable,zr=(i,e,t)=>e in i?th(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Hr=(i,e)=>{for(var t in e||(e={}))rh.call(e,t)&&zr(i,t,e[t]);if(Br)for(var t of Br(e))nh.call(e,t)&&zr(i,t,e[t]);return i},oh=(i,e)=>ih(i,sh(e));const ah="ReactNative",Ne={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},ch="js";function rs(){return typeof q.dist.process<"u"&&typeof q.dist.process.versions<"u"&&typeof q.dist.process.versions.node<"u"}function yt(){return!u.getDocument_1()&&!!u.getNavigator_1()&&navigator.product===ah}function hh(){return yt()&&typeof q.dist.global<"u"&&typeof(q.dist.global==null?void 0:q.dist.global.Platform)<"u"&&(q.dist.global==null?void 0:q.dist.global.Platform.OS)==="android"}function lh(){return yt()&&typeof q.dist.global<"u"&&typeof(q.dist.global==null?void 0:q.dist.global.Platform)<"u"&&(q.dist.global==null?void 0:q.dist.global.Platform.OS)==="ios"}function hi(){return!rs()&&!!u.getNavigator_1()&&!!u.getDocument_1()}function ji(){return yt()?Ne.reactNative:rs()?Ne.node:hi()?Ne.browser:Ne.unknown}function Vr(){var i;try{return yt()&&typeof q.dist.global<"u"&&typeof(q.dist.global==null?void 0:q.dist.global.Application)<"u"?(i=q.dist.global.Application)==null?void 0:i.applicationId:void 0}catch{return}}function uh(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 ph(i){var e,t;const s=Vo();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!=="")),oh(Hr(Hr({},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 Vo(){return u.getWindowMetadata_1()||{name:"",description:"",url:"",icons:[""]}}function dh(){if(ji()===Ne.reactNative&&typeof q.dist.global<"u"&&typeof(q.dist.global==null?void 0:q.dist.global.Platform)<"u"){const{OS:t,Version:s}=q.dist.global.Platform;return[t,s].join("-")}const i=u.detect();if(i===null)return"unknown";const e=i.os?i.os.replace(" ","").toLowerCase():"unknown";return i.type==="browser"?[e,i.name,i.version].join("-"):[e,i.version].join("-")}function gh(){var i;const e=ji();return e===Ne.browser?[e,((i=u.getLocation_1())==null?void 0:i.host)||"unknown"].join(":"):e}function Ko(i,e,t){const s=dh(),r=gh();return[[i,e].join("-"),[ch,t].join("-"),s,r].join("/")}function fh({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Ko(i,e,s),p={auth:r,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=uh(h[1]||"",p);return h[0]+"?"+d}function $t(i,e){return i.filter(t=>e.includes(t)).length===i.length}function Ks(i){return Object.fromEntries(i.entries())}function Gs(i){return new Map(Object.entries(i))}function vt(i=u.cjs.FIVE_MINUTES,e){const t=u.cjs.toMiliseconds(i||u.cjs.FIVE_MINUTES);let s,r,n,o;return{resolve:a=>{n&&s&&(clearTimeout(n),s(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const h=new Error(e);o=Promise.reject(h),c(h)},t),s=a,r=c})}}function dt(i,e,t){return new Promise(async(s,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await i;s(o)}catch(o){r(o)}clearTimeout(n)})}function Go(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 yh(i){return Go("topic",i)}function mh(i){return Go("id",i)}function Wo(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 ce(i,e){return u.cjs.fromMiliseconds(Date.now()+u.cjs.toMiliseconds(i))}function ut(i){return Date.now()>=u.cjs.toMiliseconds(i)}function J(i,e){return`${i}${e?`:${e}`:""}`}function Ye(i=[],e=[]){return[...new Set([...i,...e])]}async function wh({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=bh(n,i,e),a=ji();if(a===Ne.browser){if(!((s=u.getDocument_1())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}vh(o)}else a===Ne.reactNative&&typeof(q.dist.global==null?void 0:q.dist.global.Linking)<"u"&&await q.dist.global.Linking.openURL(o)}catch(r){console.error(r)}}function bh(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}${Ph(s,!0)}`}else r=`${r}/wc?${s}`;return r}function vh(i){let e="_self";_h()?e="_top":(Ih()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function Eh(i,e){let t="";try{if(hi()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function Kr(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function Gr(){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 Ir(){return typeof q.dist.process<"u"&&q.dist.process.env.IS_VITEST==="true"}function Ih(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function _h(){try{return window.self!==window.top}catch{return!1}}function Ph(i,e=!1){const t=q.dist.Buffer.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Jo(i){return q.dist.Buffer.from(i,"base64").toString("utf-8")}function $h(i){return new Promise(e=>setTimeout(e,i))}function Ai(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Sh(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function qi(i,...e){if(!Sh(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 _r(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ai(i.outputLen),Ai(i.blockLen)}function ei(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 Qo(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 zi=BigInt(2**32-1),Wr=BigInt(32);function Oh(i,e=!1){return e?{h:Number(i&zi),l:Number(i>>Wr&zi)}:{h:Number(i>>Wr&zi)|0,l:Number(i&zi)|0}}function Ah(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}=Oh(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const xh=(i,e,t)=>i<<t|e>>>32-t,Rh=(i,e,t)=>e<<t|i>>>32-t,Ch=(i,e,t)=>e<<t-32|i>>>64-t,Nh=(i,e,t)=>i<<t-32|e>>>64-t,jt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Th(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Es(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Ke(i,e){return i<<32-e|i>>>e}const Jr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function jh(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Qr(i){for(let e=0;e<i.length;e++)i[e]=jh(i[e])}function qh(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function ti(i){return typeof i=="string"&&(i=qh(i)),qi(i),i}function kh(...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 Pr=class{clone(){return this._cloneInto()}};function Yo(i){const e=s=>i().update(ti(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function li(i=32){if(jt&&typeof jt.getRandomValues=="function")return jt.getRandomValues(new Uint8Array(i));if(jt&&typeof jt.randomBytes=="function")return jt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Zo=[],Xo=[],ea=[],Dh=BigInt(0),fi=BigInt(1),Fh=BigInt(2),Uh=BigInt(7),Mh=BigInt(256),Lh=BigInt(113);for(let i=0,e=fi,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Zo.push(2*(5*s+t)),Xo.push((i+1)*(i+2)/2%64);let r=Dh;for(let n=0;n<7;n++)e=(e<<fi^(e>>Uh)*Lh)%Mh,e&Fh&&(r^=fi<<(fi<<BigInt(n))-fi);ea.push(r)}const[Bh,zh]=Ah(ea,!0),Yr=(i,e,t)=>t>32?Ch(i,e,t):xh(i,e,t),Zr=(i,e,t)=>t>32?Nh(i,e,t):Rh(i,e,t);function Hh(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],p=Yr(h,l,1)^t[a],d=Zr(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=p,i[o+g+1]^=d}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Xo[o],c=Yr(r,n,a),h=Zr(r,n,a),l=Zo[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)}let Vh=class ta extends Pr{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,Ai(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Th(this.state)}keccak(){Jr||Qr(this.state32),Hh(this.state32,this.rounds),Jr||Qr(this.state32),this.posOut=0,this.pos=0}update(e){ei(this);const{blockLen:t,state:s}=this;e=ti(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){ei(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 Ai(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Qo(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 ta(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 Kh=(i,e,t)=>Yo(()=>new Vh(e,i,t)),Gh=Kh(1,136,256/8),Wh="https://rpc.walletconnect.org/v1";function ia(i){const e=`Ethereum Signed Message:
3
- ${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+q.dist.Buffer.from(Gh(t)).toString("hex")}async function Jh(i,e,t,s,r,n){switch(t.t){case"eip191":return await Qh(i,e,t.s);case"eip1271":return await Yh(i,e,t.s,s,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function Qh(i,e,t){return(await Yc({hash:ia(e),signature:t})).toLowerCase()===i.toLowerCase()}async function Yh(i,e,t,s,r,n){const o=Xt(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),p=ia(e).substring(2),d=a+p+c+h+l,g=await fetch(`${n||Wh}/?chainId=${s}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:Zh(),jsonrpc:"2.0",method:"eth_call",params:[{to:i,data:d},"latest"]})}),{result:f}=await g.json();return f?f.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Zh(){return Date.now()+Math.floor(Math.random()*1e3)}function Xh(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=q.dist.Buffer.from(i,"base64").slice(1,65);return zo.encode(n)}var el=Object.defineProperty,tl=Object.defineProperties,il=Object.getOwnPropertyDescriptors,Xr=Object.getOwnPropertySymbols,sl=Object.prototype.hasOwnProperty,rl=Object.prototype.propertyIsEnumerable,en=(i,e,t)=>e in i?el(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,nl=(i,e)=>{for(var t in e||(e={}))sl.call(e,t)&&en(i,t,e[t]);if(Xr)for(var t of Xr(e))rl.call(e,t)&&en(i,t,e[t]);return i},ol=(i,e)=>tl(i,il(e));const al="did:pkh:",$r=i=>i==null?void 0:i.split(":"),cl=i=>{const e=i&&$r(i);if(e)return i.includes(al)?e[3]:e[1]},Ws=i=>{const e=i&&$r(i);if(e)return e[2]+":"+e[3]},ns=i=>{const e=i&&$r(i);if(e)return e.pop()};async function tn(i){const{cacao:e,projectId:t}=i,{s,p:r}=e,n=sa(r,r.iss),o=ns(r.iss);return await Jh(o,n,s,Ws(r.iss),t)}const sa=(i,e)=>{const t=`${i.domain} wants you to sign in with your Ethereum account:`,s=ns(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: ${cl(e)}`,c=`Nonce: ${i.nonce}`,h=`Issued At: ${i.iat}`,l=i.exp?`Expiration Time: ${i.exp}`:void 0,p=i.nbf?`Not Before: ${i.nbf}`:void 0,d=i.requestId?`Request ID: ${i.requestId}`:void 0,g=i.resources?`Resources:${i.resources.map(w=>`
4
- - ${w}`).join("")}`:void 0,f=Xi(i.resources);if(f){const w=xi(f);r=ml(r,w)}return[t,s,"",r,"",n,o,a,c,h,l,p,d,g].filter(w=>w!=null).join(`
5
- `)};function hl(i){return q.dist.Buffer.from(JSON.stringify(i)).toString("base64")}function ll(i){return JSON.parse(q.dist.Buffer.from(i,"base64").toString("utf-8"))}function At(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 ul(i,e,t,s={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[i]:pl(e,t,s)}}}function pl(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 ra(i){return At(i),`urn:recap:${hl(i).replace(/=/g,"")}`}function xi(i){const e=ll(i.replace("urn:recap:",""));return At(e),e}function dl(i,e,t){const s=ul(i,e,t);return ra(s)}function gl(i){return i&&i.includes("urn:recap:")}function fl(i,e){const t=xi(i),s=xi(e),r=yl(t,s);return ra(r)}function yl(i,e){At(i),At(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]=ol(nl({},s.att[r]),{[a]:((c=i.att[r])==null?void 0:c[a])||((h=e.att[r])==null?void 0:h[a])})})}),s}function ml(i="",e){At(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(p=>({ability:p.split("/")[0],action:p.split("/")[1]}));c.sort((p,d)=>p.action.localeCompare(d.action));const h={};c.forEach(p=>{h[p.ability]||(h[p.ability]=[]),h[p.ability].push(p.action)});const l=Object.keys(h).map(p=>(r++,`(${r}) '${p}': '${h[p].join("', '")}' for '${a}'.`));s.push(l.join(", ").replace(".,","."))});const n=s.join(" "),o=`${t}${n}`;return`${i?i+" ":""}${o}`}function sn(i){var e;const t=xi(i);At(t);const s=(e=t.att)==null?void 0:e.eip155;return s?Object.keys(s).map(r=>r.split("/")[1]):[]}function rn(i){const e=xi(i);At(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 Xi(i){if(!i)return;const e=i==null?void 0:i[i.length-1];return gl(e)?e:void 0}function Is(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function na(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ce(i,...e){if(!na(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 nn(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 wl(i,e){Ce(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function on(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const gt=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),bl=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),vl=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!vl)throw new Error("Non little-endian hardware is not supported");function El(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function Js(i){if(typeof i=="string")i=El(i);else if(na(i))i=Qs(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function Il(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function _l(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 Pl=(i,e)=>{function t(s,...r){if(Ce(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?Ce(h):Ce(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&Ce(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");Ce(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ce(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(Ce(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 an(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&&!$l(e))throw new Error("invalid output, must be aligned");return e}function cn(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 $l(i){return i.byteOffset%4===0}function Qs(i){return Uint8Array.from(i)}function ii(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const oa=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),Sl=oa("expand 16-byte k"),Ol=oa("expand 32-byte k"),Al=gt(Sl),xl=gt(Ol);function V(i,e){return i<<e|i>>>32-e}function Ys(i){return i.byteOffset%4===0}const Hi=64,Rl=16,aa=2**32-1,hn=new Uint32Array;function Cl(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(Hi),l=gt(h),p=Ys(r)&&Ys(n),d=p?gt(r):hn,g=p?gt(n):hn;for(let f=0;f<c;o++){if(i(e,t,s,l,o,a),o>=aa)throw new Error("arx: counter overflow");const w=Math.min(Hi,c-f);if(p&&w===Hi){const y=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let b=0,m;b<Rl;b++)m=y+b,g[m]=d[m]^l[b];f+=Hi;continue}for(let y=0,b;y<w;y++)b=f+y,n[b]=r[b]^h[y];f+=w}}function Nl(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=Il({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return Is(r),Is(o),on(n),on(t),(a,c,h,l,p=0)=>{Ce(a),Ce(c),Ce(h);const d=h.length;if(l===void 0&&(l=new Uint8Array(d)),Ce(l),Is(p),p<0||p>=aa)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const g=[];let f=a.length,w,y;if(f===32)g.push(w=Qs(a)),y=xl;else if(f===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),y=Al,g.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${f}`);Ys(c)||g.push(c=Qs(c));const b=gt(w);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(y,b,gt(c.subarray(0,16)),b),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 P=new Uint8Array(12);P.set(c,n?0:12-c.length),c=P,g.push(c)}const v=gt(c);return Cl(i,y,b,v,h,l,p,o),ii(...g),l}}const fe=(i,e)=>i[e++]&255|(i[e++]&255)<<8;class Tl{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=Js(e),Ce(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],p=o[4],d=o[5],g=o[6],f=o[7],w=o[8],y=o[9],b=fe(e,t+0),m=fe(e,t+2),v=fe(e,t+4),P=fe(e,t+6),R=fe(e,t+8),$=fe(e,t+10),O=fe(e,t+12),N=fe(e,t+14);let E=n[0]+(b&8191),F=n[1]+((b>>>13|m<<3)&8191),j=n[2]+((m>>>10|v<<6)&8191),D=n[3]+((v>>>7|P<<9)&8191),M=n[4]+((P>>>4|R<<12)&8191),_=n[5]+(R>>>1&8191),x=n[6]+((R>>>14|$<<2)&8191),A=n[7]+(($>>>11|O<<5)&8191),T=n[8]+((O>>>8|N<<8)&8191),k=n[9]+(N>>>5|r),S=0,U=S+E*a+F*(5*y)+j*(5*w)+D*(5*f)+M*(5*g);S=U>>>13,U&=8191,U+=_*(5*d)+x*(5*p)+A*(5*l)+T*(5*h)+k*(5*c),S+=U>>>13,U&=8191;let L=S+E*c+F*a+j*(5*y)+D*(5*w)+M*(5*f);S=L>>>13,L&=8191,L+=_*(5*g)+x*(5*d)+A*(5*p)+T*(5*l)+k*(5*h),S+=L>>>13,L&=8191;let B=S+E*h+F*c+j*a+D*(5*y)+M*(5*w);S=B>>>13,B&=8191,B+=_*(5*f)+x*(5*g)+A*(5*d)+T*(5*p)+k*(5*l),S+=B>>>13,B&=8191;let X=S+E*l+F*h+j*c+D*a+M*(5*y);S=X>>>13,X&=8191,X+=_*(5*w)+x*(5*f)+A*(5*g)+T*(5*d)+k*(5*p),S+=X>>>13,X&=8191;let W=S+E*p+F*l+j*h+D*c+M*a;S=W>>>13,W&=8191,W+=_*(5*y)+x*(5*w)+A*(5*f)+T*(5*g)+k*(5*d),S+=W>>>13,W&=8191;let se=S+E*d+F*p+j*l+D*h+M*c;S=se>>>13,se&=8191,se+=_*a+x*(5*y)+A*(5*w)+T*(5*f)+k*(5*g),S+=se>>>13,se&=8191;let he=S+E*g+F*d+j*p+D*l+M*h;S=he>>>13,he&=8191,he+=_*c+x*a+A*(5*y)+T*(5*w)+k*(5*f),S+=he>>>13,he&=8191;let ve=S+E*f+F*g+j*d+D*p+M*l;S=ve>>>13,ve&=8191,ve+=_*h+x*c+A*a+T*(5*y)+k*(5*w),S+=ve>>>13,ve&=8191;let oe=S+E*w+F*f+j*g+D*d+M*p;S=oe>>>13,oe&=8191,oe+=_*l+x*h+A*c+T*a+k*(5*y),S+=oe>>>13,oe&=8191;let ae=S+E*y+F*w+j*f+D*g+M*d;S=ae>>>13,ae&=8191,ae+=_*p+x*l+A*h+T*c+k*a,S+=ae>>>13,ae&=8191,S=(S<<2)+S|0,S=S+U|0,U=S&8191,S=S>>>13,L+=S,n[0]=U,n[1]=L,n[2]=B,n[3]=X,n[4]=W,n[5]=se,n[6]=he,n[7]=ve,n[8]=oe,n[9]=ae}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;ii(s)}update(e){nn(this);const{buffer:t,blockLen:s}=this;e=Js(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(){ii(this.h,this.r,this.buffer,this.pad)}digestInto(e){nn(this),wl(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 jl(i){const e=(s,r)=>i(r).update(Js(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const ql=jl(i=>new Tl(i));function kl(i,e,t,s,r,n=20){let o=i[0],a=i[1],c=i[2],h=i[3],l=e[0],p=e[1],d=e[2],g=e[3],f=e[4],w=e[5],y=e[6],b=e[7],m=r,v=t[0],P=t[1],R=t[2],$=o,O=a,N=c,E=h,F=l,j=p,D=d,M=g,_=f,x=w,A=y,T=b,k=m,S=v,U=P,L=R;for(let X=0;X<n;X+=2)$=$+F|0,k=V(k^$,16),_=_+k|0,F=V(F^_,12),$=$+F|0,k=V(k^$,8),_=_+k|0,F=V(F^_,7),O=O+j|0,S=V(S^O,16),x=x+S|0,j=V(j^x,12),O=O+j|0,S=V(S^O,8),x=x+S|0,j=V(j^x,7),N=N+D|0,U=V(U^N,16),A=A+U|0,D=V(D^A,12),N=N+D|0,U=V(U^N,8),A=A+U|0,D=V(D^A,7),E=E+M|0,L=V(L^E,16),T=T+L|0,M=V(M^T,12),E=E+M|0,L=V(L^E,8),T=T+L|0,M=V(M^T,7),$=$+j|0,L=V(L^$,16),A=A+L|0,j=V(j^A,12),$=$+j|0,L=V(L^$,8),A=A+L|0,j=V(j^A,7),O=O+D|0,k=V(k^O,16),T=T+k|0,D=V(D^T,12),O=O+D|0,k=V(k^O,8),T=T+k|0,D=V(D^T,7),N=N+M|0,S=V(S^N,16),_=_+S|0,M=V(M^_,12),N=N+M|0,S=V(S^N,8),_=_+S|0,M=V(M^_,7),E=E+F|0,U=V(U^E,16),x=x+U|0,F=V(F^x,12),E=E+F|0,U=V(U^E,8),x=x+U|0,F=V(F^x,7);let B=0;s[B++]=o+$|0,s[B++]=a+O|0,s[B++]=c+N|0,s[B++]=h+E|0,s[B++]=l+F|0,s[B++]=p+j|0,s[B++]=d+D|0,s[B++]=g+M|0,s[B++]=f+_|0,s[B++]=w+x|0,s[B++]=y+A|0,s[B++]=b+T|0,s[B++]=m+k|0,s[B++]=v+S|0,s[B++]=P+U|0,s[B++]=R+L|0}const Dl=Nl(kl,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Fl=new Uint8Array(16),ln=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(Fl.subarray(t))},Ul=new Uint8Array(32);function un(i,e,t,s,r){const n=i(e,t,Ul),o=ql.create(n);r&&ln(o,r),ln(o,s);const a=new Uint8Array(16),c=bl(a);cn(c,0,BigInt(r?r.length:0),!0),cn(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return ii(n,a),h}const Ml=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=an(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=un(i,e,t,a,s);return n.set(c,o),ii(c),n},decrypt(r,n){n=an(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=un(i,e,t,o,s);if(!_l(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),ii(c),n}}),ca=Pl({blockSize:64,nonceLength:12,tagLength:16},Ml(Dl));let ha=class extends Pr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,_r(e);const s=ti(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 ei(this),this.iHash.update(e),this}digestInto(e){ei(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 us=(i,e,t)=>new ha(i,e).update(t).digest();us.create=(i,e)=>new ha(i,e);function Ll(i,e,t){return _r(i),t===void 0&&(t=new Uint8Array(i.outputLen)),us(i,ti(t),ti(e))}const _s=new Uint8Array([0]),pn=new Uint8Array;function Bl(i,e,t,s=32){if(_r(i),Ai(s),s>255*i.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(s/i.outputLen);t===void 0&&(t=pn);const n=new Uint8Array(r*i.outputLen),o=us.create(i,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let h=0;h<r;h++)_s[0]=h+1,a.update(h===0?pn:c).update(t).update(_s).digestInto(c),n.set(c,i.outputLen*h),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),_s.fill(0),n.slice(0,s)}const zl=(i,e,t,s,r)=>Bl(i,Ll(i,e,t),s,r);function Hl(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 Vl(i,e,t){return i&e^~i&t}function Kl(i,e,t){return i&e^i&t^e&t}let Gl=class extends Pr{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=Es(this.buffer)}update(e){ei(this);const{view:t,buffer:s,blockLen:r}=this;e=ti(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=Es(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){ei(this),Qo(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 p=o;p<r;p++)t[p]=0;Hl(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=Es(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 p=0;p<h;p++)a.setUint32(4*p,l[p],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 Wl=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]),ht=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lt=new Uint32Array(64);class Jl extends Gl{constructor(){super(64,32,8,!1),this.A=ht[0]|0,this.B=ht[1]|0,this.C=ht[2]|0,this.D=ht[3]|0,this.E=ht[4]|0,this.F=ht[5]|0,this.G=ht[6]|0,this.H=ht[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 p=0;p<16;p++,t+=4)lt[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){const d=lt[p-15],g=lt[p-2],f=Ke(d,7)^Ke(d,18)^d>>>3,w=Ke(g,17)^Ke(g,19)^g>>>10;lt[p]=w+lt[p-7]+f+lt[p-16]|0}let{A:s,B:r,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let p=0;p<64;p++){const d=Ke(a,6)^Ke(a,11)^Ke(a,25),g=l+d+Vl(a,c,h)+Wl[p]+lt[p]|0,f=(Ke(s,2)^Ke(s,13)^Ke(s,22))+Kl(s,r,n)|0;l=h,h=c,c=a,a=o+g|0,o=n,n=r,r=s,s=g+f|0}s=s+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(s,r,n,o,a,c,h,l)}roundClean(){lt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const ki=Yo(()=>new Jl);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ps=BigInt(0),ds=BigInt(1),Ql=BigInt(2);function xt(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Di(i){if(!xt(i))throw new Error("Uint8Array expected")}function si(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const Yl=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function ri(i){Di(i);let e="";for(let t=0;t<i.length;t++)e+=Yl[i[t]];return e}function Qt(i){const e=i.toString(16);return e.length&1?"0"+e:e}function Sr(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?ps:BigInt("0x"+i)}const st={_0:48,_9:57,A:65,F:70,a:97,f:102};function dn(i){if(i>=st._0&&i<=st._9)return i-st._0;if(i>=st.A&&i<=st.F)return i-(st.A-10);if(i>=st.a&&i<=st.f)return i-(st.a-10)}function ni(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=dn(i.charCodeAt(n)),a=dn(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 St(i){return Sr(ri(i))}function Ri(i){return Di(i),Sr(ri(Uint8Array.from(i).reverse()))}function oi(i,e){return ni(i.toString(16).padStart(e*2,"0"))}function gs(i,e){return oi(i,e).reverse()}function Zl(i){return ni(Qt(i))}function Re(i,e,t){let s;if(typeof e=="string")try{s=ni(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(xt(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 Ci(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Di(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 Xl(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 eu(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const Ps=i=>typeof i=="bigint"&&ps<=i;function fs(i,e,t){return Ps(i)&&Ps(e)&&Ps(t)&&e<=i&&i<t}function at(i,e,t,s){if(!fs(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function la(i){let e;for(e=0;i>ps;i>>=ds,e+=1);return e}function tu(i,e){return i>>BigInt(e)&ds}function iu(i,e,t){return i|(t?ds:ps)<<BigInt(e)}const Or=i=>(Ql<<BigInt(i-1))-ds,$s=i=>new Uint8Array(i),gn=i=>Uint8Array.from(i);function ua(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=$s(i),r=$s(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=$s())=>{r=a(gn([0]),l),s=a(),l.length!==0&&(r=a(gn([1]),l),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const p=[];for(;l<e;){s=a();const d=s.slice();p.push(d),l+=s.length}return Ci(...p)};return(l,p)=>{o(),c(l);let d;for(;!(d=p(h()));)c();return o(),d}}const su={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"||xt(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 ui(i,e,t={}){const s=(r,n,o)=>{const a=su[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 ru=()=>{throw new Error("not implemented")};function Zs(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 nu=Object.freeze({__proto__:null,isBytes:xt,abytes:Di,abool:si,bytesToHex:ri,numberToHexUnpadded:Qt,hexToNumber:Sr,hexToBytes:ni,bytesToNumberBE:St,bytesToNumberLE:Ri,numberToBytesBE:oi,numberToBytesLE:gs,numberToVarBytesBE:Zl,ensureBytes:Re,concatBytes:Ci,equalBytes:Xl,utf8ToBytes:eu,inRange:fs,aInRange:at,bitLen:la,bitGet:tu,bitSet:iu,bitMask:Or,createHmacDrbg:ua,validateObject:ui,notImplemented:ru,memoized:Zs});const ge=BigInt(0),ie=BigInt(1),It=BigInt(2),ou=BigInt(3),Xs=BigInt(4),fn=BigInt(5),yn=BigInt(8);function Se(i,e){const t=i%e;return t>=ge?t:e+t}function pa(i,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===ie)return ge;let s=ie;for(;e>ge;)e&ie&&(s=s*i%t),i=i*i%t,e>>=ie;return s}function Le(i,e,t){let s=i;for(;e-- >ge;)s*=s,s%=t;return s}function er(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=Se(i,e),s=e,r=ge,n=ie;for(;t!==ge;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==ie)throw new Error("invert: does not exist");return Se(r,e)}function au(i){const e=(i-ie)/It;let t,s,r;for(t=i-ie,s=0;t%It===ge;t/=It,s++);for(r=It;r<i&&pa(r,e,i)!==i-ie;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+ie)/Xs;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+ie)/It;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),p=o.pow(a,t);for(;!o.eql(p,o.ONE);){if(o.eql(p,o.ZERO))return o.ZERO;let d=1;for(let f=o.sqr(p);d<c&&!o.eql(f,o.ONE);d++)f=o.sqr(f);const g=o.pow(h,ie<<BigInt(c-d-1));h=o.sqr(g),l=o.mul(l,g),p=o.mul(p,h),c=d}return l}}function cu(i){if(i%Xs===ou){const e=(i+ie)/Xs;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===fn){const e=(i-fn)/yn;return function(t,s){const r=t.mul(s,It),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,It),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 au(i)}const hu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function lu(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=hu.reduce((s,r)=>(s[r]="function",s),e);return ui(i,t)}function uu(i,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return i.ONE;if(t===ie)return e;let s=i.ONE,r=e;for(;t>ge;)t&ie&&(s=i.mul(s,r)),r=i.sqr(r),t>>=ie;return s}function pu(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 da(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function ga(i,e,t=!1,s={}){if(i<=ge)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=da(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:Or(r),ZERO:ge,ONE:ie,create:c=>Se(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&ie)===ie,neg:c=>Se(-c,i),eql:(c,h)=>c===h,sqr:c=>Se(c*c,i),add:(c,h)=>Se(c+h,i),sub:(c,h)=>Se(c-h,i),mul:(c,h)=>Se(c*h,i),pow:(c,h)=>uu(a,c,h),div:(c,h)=>Se(c*er(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>er(c,i),sqrt:s.sqrt||(c=>(o||(o=cu(i)),o(a,c))),invertBatch:c=>pu(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?gs(c,n):oi(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?Ri(c):St(c)}});return Object.freeze(a)}function fa(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 ya(i){const e=fa(i);return e+Math.ceil(e/2)}function du(i,e,t=!1){const s=i.length,r=fa(e),n=ya(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?Ri(i):St(i),a=Se(o,e-ie)+ie;return t?gs(a,r):oi(a,r)}const mn=BigInt(0),Vi=BigInt(1);function Ss(i,e){const t=e.negate();return i?t:e}function ma(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function Os(i,e){ma(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function gu(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 fu(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 As=new WeakMap,wa=new WeakMap;function xs(i){return wa.get(i)||1}function yu(i,e){return{constTimeNegate:Ss,hasPrecomputes(t){return xs(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>mn;)s&Vi&&(r=r.add(n)),n=n.double(),s>>=Vi;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=Os(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}=Os(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),l=2**t,p=BigInt(t);for(let d=0;d<n;d++){const g=d*o;let f=Number(r&h);r>>=p,f>o&&(f-=l,r+=Vi);const w=g,y=g+Math.abs(f)-1,b=d%2!==0,m=f<0;f===0?c=c.add(Ss(b,s[w])):a=a.add(Ss(m,s[y]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=Os(t,e),c=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let p=0;p<o;p++){const d=p*a;if(r===mn)break;let g=Number(r&c);if(r>>=l,g>a&&(g-=h,r+=Vi),g===0)continue;let f=s[d+Math.abs(g)-1];g<0&&(f=f.negate()),n=n.add(f)}return n},getPrecomputes(t,s,r){let n=As.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&As.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){ma(s,e),wa.set(t,s),As.delete(t)}}}function mu(i,e,t,s){if(gu(t,i),fu(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=la(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 p=h;p>=0;p-=o){c.fill(r);for(let g=0;g<s.length;g++){const f=s[g],w=Number(f>>BigInt(p)&BigInt(a));c[w]=c[w].add(t[g])}let d=r;for(let g=c.length-1,f=r;g>0;g--)f=f.add(c[g]),d=d.add(f);if(l=l.add(d),p!==0)for(let g=0;g<o;g++)l=l.double()}return l}function ba(i){return lu(i.Fp),ui(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...da(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const qt=BigInt(0),Rs=BigInt(1);function wu(i){return ui(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function bu(i){const e=wu(i),{P:t}=e,s=m=>Se(m,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),c=e.powPminus2||(m=>pa(m,t-BigInt(2),t));function h(m,v,P){const R=s(m*(v-P));return v=s(v-R),P=s(P+R),[v,P]}const l=(e.a-BigInt(2))/BigInt(4);function p(m,v){at("u",m,qt,t),at("scalar",v,qt,t);const P=v,R=m;let $=Rs,O=qt,N=m,E=Rs,F=qt,j;for(let M=BigInt(r-1);M>=qt;M--){const _=P>>M&Rs;F^=_,j=h(F,$,N),$=j[0],N=j[1],j=h(F,O,E),O=j[0],E=j[1],F=_;const x=$+O,A=s(x*x),T=$-O,k=s(T*T),S=A-k,U=N+E,L=N-E,B=s(L*x),X=s(U*T),W=B+X,se=B-X;N=s(W*W),E=s(R*s(se*se)),$=s(A*k),O=s(S*(A+s(l*S)))}j=h(F,$,N),$=j[0],N=j[1],j=h(F,O,E),O=j[0],E=j[1];const D=c(O);return s($*D)}function d(m){return gs(s(m),n)}function g(m){const v=Re("u coordinate",m,n);return o===32&&(v[31]&=127),Ri(v)}function f(m){const v=Re("scalar",m),P=v.length;if(P!==n&&P!==o){let R=""+n+" or "+o;throw new Error("invalid scalar, expected "+R+" bytes, got "+P)}return Ri(a(v))}function w(m,v){const P=g(v),R=f(m),$=p(P,R);if($===qt)throw new Error("invalid private or public key received");return d($)}const y=d(e.Gu);function b(m){return w(m,y)}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(m,v)=>w(m,v),getPublicKey:m=>b(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:y}}const tr=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const vu=BigInt(1),wn=BigInt(2),Eu=BigInt(3),Iu=BigInt(5);BigInt(8);function _u(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=tr,o=i*i%n*i%n,a=Le(o,wn,n)*o%n,c=Le(a,vu,n)*i%n,h=Le(c,Iu,n)*c%n,l=Le(h,e,n)*h%n,p=Le(l,t,n)*l%n,d=Le(p,s,n)*p%n,g=Le(d,r,n)*d%n,f=Le(g,r,n)*d%n,w=Le(f,e,n)*h%n;return{pow_p_5_8:Le(w,wn,n)*i%n,b2:o}}function Pu(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}const ir=bu({P:tr,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=tr,{pow_p_5_8:t,b2:s}=_u(i);return Se(Le(t,Eu,e)*s,e)},adjustScalarBytes:Pu,randomBytes:li});function bn(i){i.lowS!==void 0&&si("lowS",i.lowS),i.prehash!==void 0&&si("prehash",i.prehash)}function $u(i){const e=ba(i);ui(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:Su,hexToBytes:Ou}=nu;class Au extends Error{constructor(e=""){super(e)}}const nt={Err:Au,_tlv:{encode:(i,e)=>{const{Err:t}=nt;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=Qt(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?Qt(r.length/2|128):"";return Qt(i)+n+r+e},decode(i,e){const{Err:t}=nt;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}=nt;if(i<ot)throw new e("integer: negative integers are not allowed");let t=Qt(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}=nt;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 Su(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=nt,r=typeof i=="string"?Ou(i):i;Di(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}=nt,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},ot=BigInt(0),pe=BigInt(1);BigInt(2);const vn=BigInt(3);BigInt(4);function xu(i){const e=$u(i),{Fp:t}=e,s=ga(e.n,e.nBitLength),r=e.toBytes||((w,y,b)=>{const m=y.toAffine();return Ci(Uint8Array.from([4]),t.toBytes(m.x),t.toBytes(m.y))}),n=e.fromBytes||(w=>{const y=w.subarray(1),b=t.fromBytes(y.subarray(0,t.BYTES)),m=t.fromBytes(y.subarray(t.BYTES,2*t.BYTES));return{x:b,y:m}});function o(w){const{a:y,b}=e,m=t.sqr(w),v=t.mul(m,w);return t.add(t.add(v,t.mul(w,y)),b)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(w){return fs(w,pe,e.n)}function c(w){const{allowedPrivateKeyLengths:y,nByteLength:b,wrapPrivateKey:m,n:v}=e;if(y&&typeof w!="bigint"){if(xt(w)&&(w=ri(w)),typeof w!="string"||!y.includes(w.length))throw new Error("invalid private key");w=w.padStart(b*2,"0")}let P;try{P=typeof w=="bigint"?w:St(Re("private key",w,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof w)}return m&&(P=Se(P,v)),at("private key",P,pe,v),P}function h(w){if(!(w instanceof d))throw new Error("ProjectivePoint expected")}const l=Zs((w,y)=>{const{px:b,py:m,pz:v}=w;if(t.eql(v,t.ONE))return{x:b,y:m};const P=w.is0();y==null&&(y=P?t.ONE:t.inv(v));const R=t.mul(b,y),$=t.mul(m,y),O=t.mul(v,y);if(P)return{x:t.ZERO,y:t.ZERO};if(!t.eql(O,t.ONE))throw new Error("invZ was invalid");return{x:R,y:$}}),p=Zs(w=>{if(w.is0()){if(e.allowInfinityPoint&&!t.is0(w.py))return;throw new Error("bad point: ZERO")}const{x:y,y:b}=w.toAffine();if(!t.isValid(y)||!t.isValid(b))throw new Error("bad point: x or y not FE");const m=t.sqr(b),v=o(y);if(!t.eql(m,v))throw new Error("bad point: equation left != right");if(!w.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(y,b,m){if(this.px=y,this.py=b,this.pz=m,y==null||!t.isValid(y))throw new Error("x required");if(b==null||!t.isValid(b))throw new Error("y required");if(m==null||!t.isValid(m))throw new Error("z required");Object.freeze(this)}static fromAffine(y){const{x:b,y:m}=y||{};if(!y||!t.isValid(b)||!t.isValid(m))throw new Error("invalid affine point");if(y instanceof d)throw new Error("projective point not allowed");const v=P=>t.eql(P,t.ZERO);return v(b)&&v(m)?d.ZERO:new d(b,m,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){const b=t.invertBatch(y.map(m=>m.pz));return y.map((m,v)=>m.toAffine(b[v])).map(d.fromAffine)}static fromHex(y){const b=d.fromAffine(n(Re("pointHex",y)));return b.assertValidity(),b}static fromPrivateKey(y){return d.BASE.multiply(c(y))}static msm(y,b){return mu(d,s,y,b)}_setWindowSize(y){f.setWindowSize(this,y)}assertValidity(){p(this)}hasEvenY(){const{y}=this.toAffine();if(t.isOdd)return!t.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){h(y);const{px:b,py:m,pz:v}=this,{px:P,py:R,pz:$}=y,O=t.eql(t.mul(b,$),t.mul(P,v)),N=t.eql(t.mul(m,$),t.mul(R,v));return O&&N}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){const{a:y,b}=e,m=t.mul(b,vn),{px:v,py:P,pz:R}=this;let $=t.ZERO,O=t.ZERO,N=t.ZERO,E=t.mul(v,v),F=t.mul(P,P),j=t.mul(R,R),D=t.mul(v,P);return D=t.add(D,D),N=t.mul(v,R),N=t.add(N,N),$=t.mul(y,N),O=t.mul(m,j),O=t.add($,O),$=t.sub(F,O),O=t.add(F,O),O=t.mul($,O),$=t.mul(D,$),N=t.mul(m,N),j=t.mul(y,j),D=t.sub(E,j),D=t.mul(y,D),D=t.add(D,N),N=t.add(E,E),E=t.add(N,E),E=t.add(E,j),E=t.mul(E,D),O=t.add(O,E),j=t.mul(P,R),j=t.add(j,j),E=t.mul(j,D),$=t.sub($,E),N=t.mul(j,F),N=t.add(N,N),N=t.add(N,N),new d($,O,N)}add(y){h(y);const{px:b,py:m,pz:v}=this,{px:P,py:R,pz:$}=y;let O=t.ZERO,N=t.ZERO,E=t.ZERO;const F=e.a,j=t.mul(e.b,vn);let D=t.mul(b,P),M=t.mul(m,R),_=t.mul(v,$),x=t.add(b,m),A=t.add(P,R);x=t.mul(x,A),A=t.add(D,M),x=t.sub(x,A),A=t.add(b,v);let T=t.add(P,$);return A=t.mul(A,T),T=t.add(D,_),A=t.sub(A,T),T=t.add(m,v),O=t.add(R,$),T=t.mul(T,O),O=t.add(M,_),T=t.sub(T,O),E=t.mul(F,A),O=t.mul(j,_),E=t.add(O,E),O=t.sub(M,E),E=t.add(M,E),N=t.mul(O,E),M=t.add(D,D),M=t.add(M,D),_=t.mul(F,_),A=t.mul(j,A),M=t.add(M,_),_=t.sub(D,_),_=t.mul(F,_),A=t.add(A,_),D=t.mul(M,A),N=t.add(N,D),D=t.mul(T,A),O=t.mul(x,O),O=t.sub(O,D),D=t.mul(x,M),E=t.mul(T,E),E=t.add(E,D),new d(O,N,E)}subtract(y){return this.add(y.negate())}is0(){return this.equals(d.ZERO)}wNAF(y){return f.wNAFCached(this,y,d.normalizeZ)}multiplyUnsafe(y){const{endo:b,n:m}=e;at("scalar",y,ot,m);const v=d.ZERO;if(y===ot)return v;if(this.is0()||y===pe)return this;if(!b||f.hasPrecomputes(this))return f.wNAFCachedUnsafe(this,y,d.normalizeZ);let{k1neg:P,k1:R,k2neg:$,k2:O}=b.splitScalar(y),N=v,E=v,F=this;for(;R>ot||O>ot;)R&pe&&(N=N.add(F)),O&pe&&(E=E.add(F)),F=F.double(),R>>=pe,O>>=pe;return P&&(N=N.negate()),$&&(E=E.negate()),E=new d(t.mul(E.px,b.beta),E.py,E.pz),N.add(E)}multiply(y){const{endo:b,n:m}=e;at("scalar",y,pe,m);let v,P;if(b){const{k1neg:R,k1:$,k2neg:O,k2:N}=b.splitScalar(y);let{p:E,f:F}=this.wNAF($),{p:j,f:D}=this.wNAF(N);E=f.constTimeNegate(R,E),j=f.constTimeNegate(O,j),j=new d(t.mul(j.px,b.beta),j.py,j.pz),v=E.add(j),P=F.add(D)}else{const{p:R,f:$}=this.wNAF(y);v=R,P=$}return d.normalizeZ([v,P])[0]}multiplyAndAddUnsafe(y,b,m){const v=d.BASE,P=($,O)=>O===ot||O===pe||!$.equals(v)?$.multiplyUnsafe(O):$.multiply(O),R=P(this,b).add(P(y,m));return R.is0()?void 0:R}toAffine(y){return l(this,y)}isTorsionFree(){const{h:y,isTorsionFree:b}=e;if(y===pe)return!0;if(b)return b(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:y,clearCofactor:b}=e;return y===pe?this:b?b(d,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return si("isCompressed",y),this.assertValidity(),r(d,this,y)}toHex(y=!0){return si("isCompressed",y),ri(this.toRawBytes(y))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);const g=e.nBitLength,f=yu(d,e.endo?Math.ceil(g/2):g);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Ru(i){const e=ba(i);return ui(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Cu(i){const e=Ru(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(_){return Se(_,s)}function a(_){return er(_,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:p}=xu({...e,toBytes(_,x,A){const T=x.toAffine(),k=t.toBytes(T.x),S=Ci;return si("isCompressed",A),A?S(Uint8Array.from([x.hasEvenY()?2:3]),k):S(Uint8Array.from([4]),k,t.toBytes(T.y))},fromBytes(_){const x=_.length,A=_[0],T=_.subarray(1);if(x===r&&(A===2||A===3)){const k=St(T);if(!fs(k,pe,t.ORDER))throw new Error("Point is not on curve");const S=l(k);let U;try{U=t.sqrt(S)}catch(B){const X=B instanceof Error?": "+B.message:"";throw new Error("Point is not on curve"+X)}const L=(U&pe)===pe;return(A&1)===1!==L&&(U=t.neg(U)),{x:k,y:U}}else if(x===n&&A===4){const k=t.fromBytes(T.subarray(0,t.BYTES)),S=t.fromBytes(T.subarray(t.BYTES,2*t.BYTES));return{x:k,y:S}}else{const k=r,S=n;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+S+", got "+x)}}}),d=_=>ri(oi(_,e.nByteLength));function g(_){const x=s>>pe;return _>x}function f(_){return g(_)?o(-_):_}const w=(_,x,A)=>St(_.slice(x,A));class y{constructor(x,A,T){this.r=x,this.s=A,this.recovery=T,this.assertValidity()}static fromCompact(x){const A=e.nByteLength;return x=Re("compactSignature",x,A*2),new y(w(x,0,A),w(x,A,2*A))}static fromDER(x){const{r:A,s:T}=nt.toSig(Re("DER",x));return new y(A,T)}assertValidity(){at("r",this.r,pe,s),at("s",this.s,pe,s)}addRecoveryBit(x){return new y(this.r,this.s,x)}recoverPublicKey(x){const{r:A,s:T,recovery:k}=this,S=$(Re("msgHash",x));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");const U=k===2||k===3?A+e.n:A;if(U>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=k&1?"03":"02",B=c.fromHex(L+d(U)),X=a(U),W=o(-S*X),se=o(T*X),he=c.BASE.multiplyAndAddUnsafe(B,W,se);if(!he)throw new Error("point at infinify");return he.assertValidity(),he}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return ni(this.toDERHex())}toDERHex(){return nt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ni(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const b={isValidPrivateKey(_){try{return h(_),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const _=ya(e.n);return du(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 v(_){const x=xt(_),A=typeof _=="string",T=(x||A)&&_.length;return x?T===r||T===n:A?T===2*r||T===2*n:_ instanceof c}function P(_,x,A=!0){if(v(_))throw new Error("first arg must be private key");if(!v(x))throw new Error("second arg must be public key");return c.fromHex(x).multiply(h(_)).toRawBytes(A)}const R=e.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");const x=St(_),A=_.length*8-e.nBitLength;return A>0?x>>BigInt(A):x},$=e.bits2int_modN||function(_){return o(R(_))},O=Or(e.nBitLength);function N(_){return at("num < 2^"+e.nBitLength,_,ot,O),oi(_,e.nByteLength)}function E(_,x,A=F){if(["recovered","canonical"].some(oe=>oe in A))throw new Error("sign() legacy options not supported");const{hash:T,randomBytes:k}=e;let{lowS:S,prehash:U,extraEntropy:L}=A;S==null&&(S=!0),_=Re("msgHash",_),bn(A),U&&(_=Re("prehashed msgHash",T(_)));const B=$(_),X=h(x),W=[N(X),N(B)];if(L!=null&&L!==!1){const oe=L===!0?k(t.BYTES):L;W.push(Re("extraEntropy",oe))}const se=Ci(...W),he=B;function ve(oe){const ae=R(oe);if(!p(ae))return;const mt=a(ae),Xe=c.BASE.multiply(ae).toAffine(),Ve=o(Xe.x);if(Ve===ot)return;const et=o(mt*o(he+Ve*X));if(et===ot)return;let tt=(Xe.x===Ve?0:2)|Number(Xe.y&pe),Li=et;return S&&g(et)&&(Li=f(et),tt^=1),new y(Ve,Li,tt)}return{seed:se,k2sig:ve}}const F={lowS:e.lowS,prehash:!1},j={lowS:e.lowS,prehash:!1};function D(_,x,A=F){const{seed:T,k2sig:k}=E(_,x,A),S=e;return ua(S.hash.outputLen,S.nByteLength,S.hmac)(T,k)}c.BASE._setWindowSize(8);function M(_,x,A,T=j){var et;const k=_;x=Re("msgHash",x),A=Re("publicKey",A);const{lowS:S,prehash:U,format:L}=T;if(bn(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 k=="string"||xt(k),X=!B&&!L&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!B&&!X)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let W,se;try{if(X&&(W=new y(k.r,k.s)),B){try{L!=="compact"&&(W=y.fromDER(k))}catch(tt){if(!(tt instanceof nt.Err))throw tt}!W&&L!=="der"&&(W=y.fromCompact(k))}se=c.fromHex(A)}catch{return!1}if(!W||S&&W.hasHighS())return!1;U&&(x=e.hash(x));const{r:he,s:ve}=W,oe=$(x),ae=a(ve),mt=o(oe*ae),Xe=o(he*ae),Ve=(et=c.BASE.multiplyAndAddUnsafe(se,mt,Xe))==null?void 0:et.toAffine();return Ve?o(Ve.x)===he:!1}return{CURVE:e,getPublicKey:m,getSharedSecret:P,sign:D,verify:M,ProjectivePoint:c,Signature:y,utils:b}}function Nu(i){return{hash:i,hmac:(e,...t)=>us(i,e,kh(...t)),randomBytes:li}}function Tu(i,e){const t=s=>Cu({...i,...Nu(s)});return{...t(e),create:t}}const va=ga(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),ju=va.create(BigInt("-3")),qu=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),ku=Tu({a:ju,b:qu,Fp:va,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},ki),Ea="base10",_e="base16",Be="base64pad",pt="base64url",Fi="utf8",Ia=0,ct=1,Ui=2,Du=0,En=1,Pi=12,Ar=32;function Fu(){const i=ir.utils.randomPrivateKey(),e=ir.getPublicKey(i);return{privateKey:u.toString(i,_e),publicKey:u.toString(e,_e)}}function sr(){const i=li(Ar);return u.toString(i,_e)}function Uu(i,e){const t=ir.getSharedSecret(u.fromString(i,_e),u.fromString(e,_e)),s=zl(ki,t,void 0,void 0,Ar);return u.toString(s,_e)}function es(i){const e=ki(u.fromString(i,_e));return u.toString(e,_e)}function Qe(i){const e=ki(u.fromString(i,Fi));return u.toString(e,_e)}function _a(i){return u.fromString(`${i}`,Ea)}function Rt(i){return Number(u.toString(i,Ea))}function Pa(i){return i.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function $a(i){const e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Mu(i){const e=_a(typeof i.type<"u"?i.type:Ia);if(Rt(e)===ct&&typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof i.senderPublicKey<"u"?u.fromString(i.senderPublicKey,_e):void 0,s=typeof i.iv<"u"?u.fromString(i.iv,_e):li(Pi),r=u.fromString(i.symKey,_e),n=ca(r,s).encrypt(u.fromString(i.message,Fi)),o=Sa({type:e,sealed:n,iv:s,senderPublicKey:t});return i.encoding===pt?Pa(o):o}function Lu(i){const e=u.fromString(i.symKey,_e),{sealed:t,iv:s}=Ni({encoded:i.encoded,encoding:i.encoding}),r=ca(e,s).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return u.toString(r,Fi)}function Bu(i,e){const t=_a(Ui),s=li(Pi),r=u.fromString(i,Fi),n=Sa({type:t,sealed:r,iv:s});return e===pt?Pa(n):n}function zu(i,e){const{sealed:t}=Ni({encoded:i,encoding:e});return u.toString(t,Fi)}function Sa(i){if(Rt(i.type)===Ui)return u.toString(u.concat([i.type,i.sealed]),Be);if(Rt(i.type)===ct){if(typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return u.toString(u.concat([i.type,i.senderPublicKey,i.iv,i.sealed]),Be)}return u.toString(u.concat([i.type,i.iv,i.sealed]),Be)}function Ni(i){const e=(i.encoding||Be)===pt?$a(i.encoded):i.encoded,t=u.fromString(e,Be),s=t.slice(Du,En),r=En;if(Rt(s)===ct){const c=r+Ar,h=c+Pi,l=t.slice(r,c),p=t.slice(c,h),d=t.slice(h);return{type:s,sealed:d,iv:p,senderPublicKey:l}}if(Rt(s)===Ui){const c=t.slice(r),h=li(Pi);return{type:s,sealed:c,iv:h}}const n=r+Pi,o=t.slice(r,n),a=t.slice(n);return{type:s,sealed:a,iv:o}}function Hu(i,e){const t=Ni({encoded:i,encoding:e==null?void 0:e.encoding});return Oa({type:Rt(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?u.toString(t.senderPublicKey,_e):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Oa(i){const e=(i==null?void 0:i.type)||Ia;if(e===ct){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 In(i){return i.type===ct&&typeof i.senderPublicKey=="string"&&typeof i.receiverPublicKey=="string"}function _n(i){return i.type===Ui}function Vu(i){const e=q.dist.Buffer.from(i.x,"base64"),t=q.dist.Buffer.from(i.y,"base64");return u.concat([new Uint8Array([4]),e,t])}function Ku(i,e){const[t,s,r]=i.split("."),n=q.dist.Buffer.from($a(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=ki(c),l=Vu(e);if(!ku.verify(u.concat([o,a]),h,l))throw new Error("Invalid signature");return u.sn(i).payload}const Gu="irn";function os(i){return(i==null?void 0:i.relay)||{protocol:Gu}}function Ii(i){const e=u.C[i];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${i}`);return e}function Wu(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 Pn(i){if(!i.includes("wc:")){const h=Jo(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:Ju(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:Wu(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Ju(i){return i.startsWith("//")?i.substring(2):i}function Qu(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 $n(i){const e=new URLSearchParams,t=Qu(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 Ki(i,e,t){return`${i}?wc_ev=${t}&topic=${e}`}var Yu=Object.defineProperty,Zu=Object.defineProperties,Xu=Object.getOwnPropertyDescriptors,Sn=Object.getOwnPropertySymbols,ep=Object.prototype.hasOwnProperty,tp=Object.prototype.propertyIsEnumerable,On=(i,e,t)=>e in i?Yu(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ip=(i,e)=>{for(var t in e||(e={}))ep.call(e,t)&&On(i,t,e[t]);if(Sn)for(var t of Sn(e))tp.call(e,t)&&On(i,t,e[t]);return i},sp=(i,e)=>Zu(i,Xu(e));function pi(i){const e=[];return i.forEach(t=>{const[s,r]=t.split(":");e.push(`${s}:${r}`)}),e}function rp(i){const e=[];return Object.values(i).forEach(t=>{e.push(...pi(t.accounts))}),e}function np(i,e){const t=[];return Object.values(i).forEach(s=>{pi(s.accounts).includes(e)&&t.push(...s.methods)}),t}function op(i,e){const t=[];return Object.values(i).forEach(s=>{pi(s.accounts).includes(e)&&t.push(...s.events)}),t}function ys(i){return i.includes(":")}function Yt(i){return ys(i)?i.split(":")[0]:i}function An(i){var e,t,s;const r={};if(!ft(i))return r;for(const[n,o]of Object.entries(i)){const a=ys(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],l=Yt(n);r[l]=sp(ip({},r[l]),{chains:Ye(a,(e=r[l])==null?void 0:e.chains),methods:Ye(c,(t=r[l])==null?void 0:t.methods),events:Ye(h,(s=r[l])==null?void 0:s.events)})}return r}function ap(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 xn(i,e){e=e.map(s=>s.replace("did:pkh:",""));const t=ap(e);for(const[s,r]of Object.entries(t))r.methods?r.methods=Ye(r.methods,i):r.methods=i,r.events=["chainChanged","accountsChanged"];return t}function cp(i,e){var t,s,r,n,o,a;const c=An(i),h=An(e),l={},p=Object.keys(c).concat(Object.keys(h));for(const d of p)l[d]={chains:Ye((t=c[d])==null?void 0:t.chains,(s=h[d])==null?void 0:s.chains),methods:Ye((r=c[d])==null?void 0:r.methods,(n=h[d])==null?void 0:n.methods),events:Ye((o=c[d])==null?void 0:o.events,(a=h[d])==null?void 0:a.events)};return l}const hp={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}},lp={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}=lp[i];return{message:e?`${t} ${e}`:t,code:s}}function Q(i,e){const{message:t,code:s}=hp[i];return{message:e?`${t} ${e}`:t,code:s}}function ze(i,e){return!!Array.isArray(i)}function ft(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}function we(i){return typeof i>"u"}function ne(i,e){return e&&we(i)?!0:typeof i=="string"&&!!i.trim().length}function xr(i,e){return e&&we(i)?!0:typeof i=="number"&&!isNaN(i)}function up(i,e){const{requiredNamespaces:t}=e,s=Object.keys(i.namespaces),r=Object.keys(t);let n=!0;return $t(r,s)?(s.forEach(o=>{const{accounts:a,methods:c,events:h}=i.namespaces[o],l=pi(a),p=t[o];(!$t(Ho(o,p),l)||!$t(p.methods,c)||!$t(p.events,h))&&(n=!1)}),n):!1}function as(i){return ne(i,!1)&&i.includes(":")?i.split(":").length===2:!1}function pp(i){if(ne(i,!1)&&i.includes(":")){const e=i.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&as(t)}}return!1}function dp(i){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(ne(i,!1)){if(e(i))return!0;const t=Jo(i);return e(t)}}catch{}return!1}function gp(i){var e;return(e=i==null?void 0:i.proposer)==null?void 0:e.publicKey}function fp(i){return i==null?void 0:i.topic}function yp(i,e){let t=null;return ne(i==null?void 0:i.publicKey,!1)||(t=C("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function Rn(i){let e=!0;return ze(i)?i.length&&(e=i.every(t=>ne(t,!1))):e=!1,e}function mp(i,e,t){let s=null;return ze(e)&&e.length?e.forEach(r=>{s||as(r)||(s=Q("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):as(i)||(s=Q("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 wp(i,e,t){let s=null;return Object.entries(i).forEach(([r,n])=>{if(s)return;const o=mp(r,Ho(r,n),`${e} ${t}`);o&&(s=o)}),s}function bp(i,e){let t=null;return ze(i)?i.forEach(s=>{t||pp(s)||(t=Q("UNSUPPORTED_ACCOUNTS",`${e}, account ${s} should be a string and conform to "namespace:chainId:address" format`))}):t=Q("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function vp(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=bp(s==null?void 0:s.accounts,`${e} namespace`);r&&(t=r)}),t}function Ep(i,e){let t=null;return Rn(i==null?void 0:i.methods)?Rn(i==null?void 0:i.events)||(t=Q("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Q("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function Aa(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=Ep(s,`${e}, namespace`);r&&(t=r)}),t}function Ip(i,e,t){let s=null;if(i&&ft(i)){const r=Aa(i,e);r&&(s=r);const n=wp(i,e,t);n&&(s=n)}else s=C("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return s}function Cs(i,e){let t=null;if(i&&ft(i)){const s=Aa(i,e);s&&(t=s);const r=vp(i,e);r&&(t=r)}else t=C("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function xa(i){return ne(i.protocol,!0)}function _p(i,e){let t=!1;return i?i&&ze(i)&&i.length&&i.forEach(s=>{t=xa(s)}):t=!0,t}function Pp(i){return typeof i=="number"}function $e(i){return typeof i<"u"&&typeof i!==null}function $p(i){return!(!i||typeof i!="object"||!i.code||!xr(i.code,!1)||!i.message||!ne(i.message,!1))}function Sp(i){return!(we(i)||!ne(i.method,!1))}function Op(i){return!(we(i)||we(i.result)&&we(i.error)||!xr(i.id,!1)||!ne(i.jsonrpc,!1))}function Ap(i){return!(we(i)||!ne(i.name,!1))}function Cn(i,e){return!(!as(e)||!rp(i).includes(e))}function xp(i,e,t){return ne(t,!1)?np(i,e).includes(t):!1}function Rp(i,e,t){return ne(t,!1)?op(i,e).includes(t):!1}function Nn(i,e,t){let s=null;const r=Cp(i),n=Np(e),o=Object.keys(r),a=Object.keys(n),c=Tn(Object.keys(i)),h=Tn(Object.keys(e)),l=c.filter(p=>!h.includes(p));return l.length&&(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
6
- Required: ${l.toString()}
7
- Received: ${Object.keys(e).toString()}`)),$t(o,a)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces.
8
- Required: ${o.toString()}
9
- Approved: ${a.toString()}`)),Object.keys(e).forEach(p=>{if(!p.includes(":")||s)return;const d=pi(e[p].accounts);d.includes(p)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${p}
10
- Required: ${p}
11
- Approved: ${d.toString()}`))}),o.forEach(p=>{s||($t(r[p].methods,n[p].methods)?$t(r[p].events,n[p].events)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${p}`)):s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${p}`))}),s}function Cp(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 Tn(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Np(i){const e={};return Object.keys(i).forEach(t=>{if(t.includes(":"))e[t]=i[t];else{const s=pi(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 Tp(i,e){return xr(i,!1)&&i<=e.max&&i>=e.min}function jn(){const i=ji();return new Promise(e=>{switch(i){case Ne.browser:e(jp());break;case Ne.reactNative:e(qp());break;case Ne.node:e(kp());break;default:e(!0)}})}function jp(){return hi()&&(navigator==null?void 0:navigator.onLine)}async function qp(){if(yt()&&typeof q.dist.global<"u"&&q.dist.global!=null&&q.dist.global.NetInfo){const i=await(q.dist.global==null?void 0:q.dist.global.NetInfo.fetch());return i==null?void 0:i.isConnected}return!0}function kp(){return!0}function Dp(i){switch(ji()){case Ne.browser:Fp(i);break;case Ne.reactNative:Up(i);break}}function Fp(i){!yt()&&hi()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function Up(i){var e;yt()&&typeof q.dist.global<"u"&&q.dist.global!=null&&q.dist.global.NetInfo&&((e=q.dist.global)==null||e.NetInfo.addEventListener(t=>i(t==null?void 0:t.isConnected)))}function Mp(){var i;return hi()&&u.getDocument_1()?((i=u.getDocument_1())==null?void 0:i.visibilityState)==="visible":!0}const Ns={};class yi{static get(e){return Ns[e]}static set(e,t){Ns[e]=t}static delete(e){delete Ns[e]}}var Lp=Object.defineProperty,Bp=(i,e,t)=>e in i?Lp(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qn=(i,e,t)=>Bp(i,typeof e!="symbol"?e+"":e,t);let zp=class extends u.IEvents{constructor(e){super(),this.opts=e,qn(this,"protocol","wc"),qn(this,"version",2)}};var Hp=Object.defineProperty,Vp=(i,e,t)=>e in i?Hp(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Kp=(i,e,t)=>Vp(i,e+"",t);let Gp=class extends u.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,Kp(this,"records",new Map)}},Wp=class{constructor(e,t){this.logger=e,this.core=t}};class Jp extends u.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}let Qp=class extends u.IEvents{constructor(e){super()}},Yp=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},Zp=class extends u.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},Xp=class extends u.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},ed=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},td=class{constructor(e,t){this.projectId=e,this.logger=t}},id=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var sd=Object.defineProperty,rd=(i,e,t)=>e in i?sd(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,kn=(i,e,t)=>rd(i,typeof e!="symbol"?e+"":e,t);let nd=class{constructor(e){this.opts=e,kn(this,"protocol","wc"),kn(this,"version",2)}},od=class{constructor(e){this.client=e}};const Ra="wc",Ca=2,rr="core",Ze=`${Ra}@2:${rr}:`,ad={logger:"error"},cd={database:":memory:"},hd="crypto",Dn="client_ed25519_seed",ld=u.cjs.ONE_DAY,ud="keychain",pd="0.3",dd="messages",gd="0.3",Fn=u.cjs.SIX_HOURS,fd="publisher",Na="irn",yd="error",Ta="wss://relay.walletconnect.org",md="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"},wd="_subscription",je={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},bd=.1,nr="2.21.1",te={link_mode:"link_mode",relay:"relay"},ts={inbound:"inbound",outbound:"outbound"},vd="0.3",Ed="WALLETCONNECT_CLIENT_ID",Un="WALLETCONNECT_LINK_MODE_APPS",xe={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Id="subscription",_d="0.3",Pd="pairing",$d="0.3",mi={wc_pairingDelete:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:u.cjs.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:u.cjs.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:0},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:0}}},_t={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Fe={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Sd="history",Od="0.3",Ad="expirer",ke={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},xd="0.3",Rd="verify-api",Cd="https://verify.walletconnect.com",ja="https://verify.walletconnect.org",$i=ja,Nd=`${$i}/v3`,Td=[Cd,ja],jd="echo",qd="https://echo.walletconnect.com",Je={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"},rt={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"},Ue={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"},wt={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"},bt={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"},wi={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"},kd=.1,Dd="event-client",Fd=86400,Ud="https://pulse.walletconnect.org/batch";function Md(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 p(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var w=0,y=0,b=0,m=f.length;b!==m&&f[b]===0;)b++,w++;for(var v=(m-b)*l+1>>>0,P=new Uint8Array(v);b!==m;){for(var R=f[b],$=0,O=v-1;(R!==0||$<y)&&O!==-1;O--,$++)R+=256*P[O]>>>0,P[O]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");y=$,b++}for(var N=v-y;N!==v&&P[N]===0;)N++;for(var E=c.repeat(w);N<v;++N)E+=i.charAt(P[N]);return E}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var w=0;if(f[w]!==" "){for(var y=0,b=0;f[w]===c;)y++,w++;for(var m=(f.length-w)*h+1>>>0,v=new Uint8Array(m);f[w];){var P=t[f.charCodeAt(w)];if(P===255)return;for(var R=0,$=m-1;(P!==0||R<b)&&$!==-1;$--,R++)P+=a*v[$]>>>0,v[$]=P%256>>>0,P=P/256>>>0;if(P!==0)throw new Error("Non-zero carry");b=R,w++}if(f[w]!==" "){for(var O=m-b;O!==m&&v[O]===0;)O++;for(var N=new Uint8Array(y+(m-O)),E=y;O!==m;)N[E++]=v[O++];return N}}}function g(f){var w=d(f);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:d,decode:g}}var Ld=Md,Bd=Ld;const qa=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")},zd=i=>new TextEncoder().encode(i),Hd=i=>new TextDecoder().decode(i);class Vd{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 Kd{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 ka(this,e)}}class Gd{constructor(e){this.decoders=e}or(e){return ka(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 ka=(i,e)=>new Gd({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Wd{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Vd(e,t,s),this.decoder=new Kd(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ms=({name:i,prefix:e,encode:t,decode:s})=>new Wd(i,e,t,s),Mi=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=Bd(t,e);return ms({prefix:i,name:e,encode:s,decode:n=>qa(r(n))})},Jd=(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 p=r[i[l]];if(p===void 0)throw new SyntaxError(`Non-${s} character`);c=c<<t|p,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},Qd=(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})=>ms({prefix:e,name:i,encode(r){return Qd(r,s,t)},decode(r){return Jd(r,s,t,i)}}),Yd=ms({prefix:"\0",name:"identity",encode:i=>Hd(i),decode:i=>zd(i)});var Zd=Object.freeze({__proto__:null,identity:Yd});const Xd=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var eg=Object.freeze({__proto__:null,base2:Xd});const tg=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ig=Object.freeze({__proto__:null,base8:tg});const sg=Mi({prefix:"9",name:"base10",alphabet:"0123456789"});var rg=Object.freeze({__proto__:null,base10:sg});const ng=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),og=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ag=Object.freeze({__proto__:null,base16:ng,base16upper:og});const cg=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hg=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),lg=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ug=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),pg=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dg=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),gg=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fg=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yg=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mg=Object.freeze({__proto__:null,base32:cg,base32upper:hg,base32pad:lg,base32padupper:ug,base32hex:pg,base32hexupper:dg,base32hexpad:gg,base32hexpadupper:fg,base32z:yg});const wg=Mi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bg=Mi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vg=Object.freeze({__proto__:null,base36:wg,base36upper:bg});const Eg=Mi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ig=Mi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var _g=Object.freeze({__proto__:null,base58btc:Eg,base58flickr:Ig});const Pg=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$g=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Sg=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Og=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ag=Object.freeze({__proto__:null,base64:Pg,base64pad:$g,base64url:Sg,base64urlpad:Og});const Da=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),xg=Da.reduce((i,e,t)=>(i[t]=e,i),[]),Rg=Da.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function Cg(i){return i.reduce((e,t)=>(e+=xg[t],e),"")}function Ng(i){const e=[];for(const t of i){const s=Rg[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const Tg=ms({prefix:"🚀",name:"base256emoji",encode:Cg,decode:Ng});var jg=Object.freeze({__proto__:null,base256emoji:Tg}),qg=Fa,Mn=128,kg=-128,Dg=Math.pow(2,31);function Fa(i,e,t){e=e||[],t=t||0;for(var s=t;i>=Dg;)e[t++]=i&255|Mn,i/=128;for(;i&kg;)e[t++]=i&255|Mn,i>>>=7;return e[t]=i|0,Fa.bytes=t-s+1,e}var Fg=or,Ug=128,Ln=127;function or(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw or.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&Ln)<<r:(o&Ln)*Math.pow(2,r),r+=7}while(o>=Ug);return or.bytes=n-s,t}var Mg=Math.pow(2,7),Lg=Math.pow(2,14),Bg=Math.pow(2,21),zg=Math.pow(2,28),Hg=Math.pow(2,35),Vg=Math.pow(2,42),Kg=Math.pow(2,49),Gg=Math.pow(2,56),Wg=Math.pow(2,63),Jg=function(i){return i<Mg?1:i<Lg?2:i<Bg?3:i<zg?4:i<Hg?5:i<Vg?6:i<Kg?7:i<Gg?8:i<Wg?9:10},Qg={encode:qg,decode:Fg,encodingLength:Jg},Ua=Qg;const Bn=(i,e,t=0)=>(Ua.encode(i,e,t),e),zn=i=>Ua.encodingLength(i),ar=(i,e)=>{const t=e.byteLength,s=zn(i),r=s+zn(t),n=new Uint8Array(r+t);return Bn(i,n,0),Bn(t,n,s),n.set(e,r),new Yg(i,t,e,n)};class Yg{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}}const Ma=({name:i,code:e,encode:t})=>new Zg(i,e,t);class Zg{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?ar(this.code,t):t.then(s=>ar(this.code,s))}else throw Error("Unknown type, must be binary type")}}const La=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Xg=Ma({name:"sha2-256",code:18,encode:La("SHA-256")}),ef=Ma({name:"sha2-512",code:19,encode:La("SHA-512")});var tf=Object.freeze({__proto__:null,sha256:Xg,sha512:ef});const Ba=0,sf="identity",za=qa,rf=i=>ar(Ba,za(i)),nf={code:Ba,name:sf,encode:za,digest:rf};var of=Object.freeze({__proto__:null,identity:nf});new TextEncoder,new TextDecoder;const Hn={...Zd,...eg,...ig,...rg,...ag,...mg,...vg,..._g,...Ag,...jg};({...tf,...of});function af(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Ha(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Vn=Ha("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Ts=Ha("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=af(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),cf={utf8:Vn,"utf-8":Vn,hex:Hn.base16,latin1:Ts,ascii:Ts,binary:Ts,...Hn};function hf(i,e="utf8"){const t=cf[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 lf=Object.defineProperty,uf=(i,e,t)=>e in i?lf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ge=(i,e,t)=>uf(i,typeof e!="symbol"?e+"":e,t);class pf{constructor(e,t){this.core=e,this.logger=t,Ge(this,"keychain",new Map),Ge(this,"name",ud),Ge(this,"version",pd),Ge(this,"initialized",!1),Ge(this,"storagePrefix",Ze),Ge(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),Ge(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),Ge(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),Ge(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}),Ge(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ks(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Gs(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 df=Object.defineProperty,gf=(i,e,t)=>e in i?df(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ye=(i,e,t)=>gf(i,typeof e!="symbol"?e+"":e,t);class ff{constructor(e,t,s){this.core=e,this.logger=t,ye(this,"name",hd),ye(this,"keychain"),ye(this,"randomSessionIdentifier",sr()),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=u.Po(r);return u.Qe(n.publicKey)}),ye(this,"generateKeyPair",()=>{this.isInitialized();const r=Fu();return this.setPrivateKey(r.publicKey,r.privateKey)}),ye(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=u.Po(n),a=this.randomSessionIdentifier,c=ld;return await u.Qo(a,r,c,o)}),ye(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Uu(a,n);return this.setSymKey(c,o)}),ye(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||es(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=Oa(o),c=u.safeJsonStringify(n);if(_n(a))return Bu(c,o==null?void 0:o.encoding);if(In(a)){const d=a.senderPublicKey,g=a.receiverPublicKey;r=await this.generateSharedKey(d,g)}const h=this.getSymKey(r),{type:l,senderPublicKey:p}=a;return Mu({type:l,symKey:h,message:c,senderPublicKey:p,encoding:o==null?void 0:o.encoding})}),ye(this,"decode",async(r,n,o)=>{this.isInitialized();const a=Hu(n,o);if(_n(a)){const c=zu(n,o==null?void 0:o.encoding);return u.safeJsonParse(c)}if(In(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=Lu({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return u.safeJsonParse(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=Be)=>{const o=Ni({encoded:r,encoding:n});return Rt(o.type)}),ye(this,"getPayloadSenderPublicKey",(r,n=Be)=>{const o=Ni({encoded:r,encoding:n});return o.senderPublicKey?u.toString(o.senderPublicKey,_e):void 0}),this.core=e,this.logger=u.E(t,this.name),this.keychain=s||new pf(this.core,this.logger)}get context(){return u.y(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Dn)}catch{e=sr(),await this.keychain.set(Dn,e)}return hf(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 yf=Object.defineProperty,mf=Object.defineProperties,wf=Object.getOwnPropertyDescriptors,Kn=Object.getOwnPropertySymbols,bf=Object.prototype.hasOwnProperty,vf=Object.prototype.propertyIsEnumerable,cr=(i,e,t)=>e in i?yf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ef=(i,e)=>{for(var t in e||(e={}))bf.call(e,t)&&cr(i,t,e[t]);if(Kn)for(var t of Kn(e))vf.call(e,t)&&cr(i,t,e[t]);return i},If=(i,e)=>mf(i,wf(e)),Oe=(i,e,t)=>cr(i,typeof e!="symbol"?e+"":e,t);class _f extends Wp{constructor(e,t){super(e,t),this.logger=e,this.core=t,Oe(this,"messages",new Map),Oe(this,"messagesWithoutClientAck",new Map),Oe(this,"name",dd),Oe(this,"version",gd),Oe(this,"initialized",!1),Oe(this,"storagePrefix",Ze),Oe(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}}}),Oe(this,"set",async(s,r,n)=>{this.isInitialized();const o=Qe(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===ts.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,If(Ef({},c),{[o]:r}))}return await this.persist(),o}),Oe(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),Oe(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}),Oe(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=Qe(r);return typeof n[o]<"u"}),Oe(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=Qe(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),Oe(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=u.E(e,this.name),this.core=t}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Ks(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ks(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Gs(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Gs(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 Pf=Object.defineProperty,$f=Object.defineProperties,Sf=Object.getOwnPropertyDescriptors,Gn=Object.getOwnPropertySymbols,Of=Object.prototype.hasOwnProperty,Af=Object.prototype.propertyIsEnumerable,hr=(i,e,t)=>e in i?Pf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Gi=(i,e)=>{for(var t in e||(e={}))Of.call(e,t)&&hr(i,t,e[t]);if(Gn)for(var t of Gn(e))Af.call(e,t)&&hr(i,t,e[t]);return i},js=(i,e)=>$f(i,Sf(e)),Me=(i,e,t)=>hr(i,typeof e!="symbol"?e+"":e,t);class xf extends Jp{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Me(this,"events",new He.eventsExports.EventEmitter),Me(this,"name",fd),Me(this,"queue",new Map),Me(this,"publishTimeout",u.cjs.toMiliseconds(u.cjs.ONE_MINUTE)),Me(this,"initialPublishTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),Me(this,"needsTransportRestart",!1),Me(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)||Fn,c=os(n),h=(n==null?void 0:n.prompt)||!1,l=(n==null?void 0:n.tag)||0,p=(n==null?void 0:n.id)||u.getBigIntRpcId().toString(),d={topic:s,message:r,opts:{ttl:a,relay:c,prompt:h,tag:l,id:p,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},g=`Failed to publish payload, please try again. id:${p} tag:${l}`;try{const f=new Promise(async w=>{const y=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(de.publish,y),w(d))};this.relayer.events.on(de.publish,y);const b=dt(new Promise((m,v)=>{this.rpcPublish({topic:s,message:r,ttl:a,prompt:h,tag:l,id:p,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(m).catch(P=>{this.logger.warn(P,P==null?void 0:P.message),v(P)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${l}`);try{await b,this.events.removeListener(de.publish,y)}catch(m){this.queue.set(p,js(Gi({},d),{attempt:1})),this.logger.warn(m,m==null?void 0:m.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:s,message:r,opts:n}}),await dt(f,this.publishTimeout,g)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(p)}}),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.relayer=e,this.logger=u.E(t,this.name),this.registerEventListeners()}get context(){return u.y(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=Fn,prompt:h,tag:l,id:p,attestation:d,tvf:g}=e,f={method:Ii(os().protocol).publish,params:Gi({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:d},g),id:p};we((t=f.params)==null?void 0:t.prompt)&&((s=f.params)==null||delete s.prompt),we((r=f.params)==null?void 0:r.tag)&&((n=f.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const w=await this.relayer.request(f);return this.relayer.events.emit(de.publish,e),this.logger.debug("Successfully Published Payload"),w}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,js(Gi({},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(js(Gi({},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(u.r.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 Rf=Object.defineProperty,Cf=(i,e,t)=>e in i?Rf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,kt=(i,e,t)=>Cf(i,typeof e!="symbol"?e+"":e,t);class Nf{constructor(){kt(this,"map",new Map),kt(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),kt(this,"get",e=>this.map.get(e)||[]),kt(this,"exists",(e,t)=>this.get(e).includes(t)),kt(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)}),kt(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Tf=Object.defineProperty,jf=Object.defineProperties,qf=Object.getOwnPropertyDescriptors,Wn=Object.getOwnPropertySymbols,kf=Object.prototype.hasOwnProperty,Df=Object.prototype.propertyIsEnumerable,lr=(i,e,t)=>e in i?Tf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bi=(i,e)=>{for(var t in e||(e={}))kf.call(e,t)&&lr(i,t,e[t]);if(Wn)for(var t of Wn(e))Df.call(e,t)&&lr(i,t,e[t]);return i},qs=(i,e)=>jf(i,qf(e)),Y=(i,e,t)=>lr(i,typeof e!="symbol"?e+"":e,t);class Ff extends Zp{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Y(this,"subscriptions",new Map),Y(this,"topicMap",new Nf),Y(this,"events",new He.eventsExports.EventEmitter),Y(this,"name",Id),Y(this,"version",_d),Y(this,"pending",new Map),Y(this,"cached",[]),Y(this,"initialized",!1),Y(this,"storagePrefix",Ze),Y(this,"subscribeTimeout",u.cjs.toMiliseconds(u.cjs.ONE_MINUTE)),Y(this,"initialSubscribeTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),Y(this,"clientId"),Y(this,"batchSubscribeTopicsLimit",500),Y(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Y(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=os(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}}),Y(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)}),Y(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),Y(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),Y(this,"on",(s,r)=>{this.events.on(s,r)}),Y(this,"once",(s,r)=>{this.events.once(s,r)}),Y(this,"off",(s,r)=>{this.events.off(s,r)}),Y(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),Y(this,"start",async()=>{await this.onConnect()}),Y(this,"stop",async()=>{await this.onDisconnect()}),Y(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Y(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)}),Y(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(u.r.pulse,async()=>{await this.checkPending()}),this.events.on(xe.created,async s=>{const r=xe.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(xe.deleted,async s=>{const r=xe.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=u.E(t,this.name),this.clientId=""}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const r=os(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Q("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)===te.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Ii(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)===te.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},u.cjs.toMiliseconds(u.cjs.ONE_SECOND)),a;const c=new Promise(async l=>{const p=d=>{d.topic===e&&(this.events.removeListener(xe.created,p),l(d.id))};this.events.on(xe.created,p);try{const d=await dt(new Promise((g,f)=>{this.relayer.request(n).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),f(w)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(xe.created,p),l(d)}catch{}}),h=await dt(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(de.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Ii(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await dt(new Promise(r=>{this.relayer.request(s).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Ii(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let r;try{r=await await dt(new Promise((n,o)=>{this.relayer.request(s).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:Ii(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,qs(bi({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,bi({},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,bi({},t)),this.topicMap.set(t.topic,e),this.events.emit(xe.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(xe.deleted,qs(bi({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(xe.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(xe.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=>qs(bi({},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 $h(u.cjs.toMiliseconds(u.cjs.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 Qe(e+await this.getClientId())}}var Uf=Object.defineProperty,Jn=Object.getOwnPropertySymbols,Mf=Object.prototype.hasOwnProperty,Lf=Object.prototype.propertyIsEnumerable,ur=(i,e,t)=>e in i?Uf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qn=(i,e)=>{for(var t in e||(e={}))Mf.call(e,t)&&ur(i,t,e[t]);if(Jn)for(var t of Jn(e))Lf.call(e,t)&&ur(i,t,e[t]);return i},K=(i,e,t)=>ur(i,typeof e!="symbol"?e+"":e,t);class Bf extends Qp{constructor(e){super(e),K(this,"protocol","wc"),K(this,"version",2),K(this,"core"),K(this,"logger"),K(this,"events",new He.eventsExports.EventEmitter),K(this,"provider"),K(this,"messages"),K(this,"subscriber"),K(this,"publisher"),K(this,"name",md),K(this,"transportExplicitlyClosed",!1),K(this,"initialized",!1),K(this,"connectionAttemptInProgress",!1),K(this,"relayUrl"),K(this,"projectId"),K(this,"packageName"),K(this,"bundleId"),K(this,"hasExperiencedNetworkDisruption",!1),K(this,"pingTimeout"),K(this,"heartBeatTimeout",u.cjs.toMiliseconds(u.cjs.THIRTY_SECONDS+u.cjs.FIVE_SECONDS)),K(this,"reconnectTimeout"),K(this,"connectPromise"),K(this,"reconnectInProgress",!1),K(this,"requestsInFlight",[]),K(this,"connectTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),K(this,"request",async t=>{var s,r;this.logger.debug("Publishing Request Payload");const n=t.id||u.getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(s=t.params)==null?void 0:s.topic},"relayer.request - publishing...");const o=`${n}:${((r=t.params)==null?void 0:r.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),K(this,"resetPingTimeout",()=>{rs()&&(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))}),K(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),K(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(de.connect)}),K(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),K(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()}),K(this,"registerProviderListeners",()=>{this.provider.on(je.payload,this.onPayloadHandler),this.provider.on(je.connect,this.onConnectHandler),this.provider.on(je.disconnect,this.onDisconnectHandler),this.provider.on(je.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?u.E(e.logger,this.name):u.Ot(u.k({level:e.logger||yd})),this.messages=new _f(this.logger,e.core),this.subscriber=new Ff(this,this.logger),this.publisher=new xf(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Ta,this.projectId=e.projectId,hh()?this.packageName=Vr():lh()&&(this.bundleId=Vr()),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 u.y(this.logger)}get connected(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===1||!1}get connecting(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:te.relay},ts.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(xe.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(xe.created,h)}),new Promise(async(l,p)=>{a=await this.subscriber.subscribe(e,Qn({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&p(d)})||a,l()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await dt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,s)=>{await this.connect(e).then(t).catch(s).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await jn())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=ce(u.cjs.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,ts.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(je.disconnect,n),await dt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off(je.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(je.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(je.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,u.cjs.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,s,r,n;if(rs())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 u.o(new u.f(fh({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}),u.isJsonRpcRequest(e)){if(!e.method.endsWith(wd))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:te.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Qn({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else u.isJsonRpcResponse(e)&&this.events.emit(de.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ts.inbound),this.events.emit(de.message,e))}async acknowledgePayload(e){const t=u.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(je.payload,this.onPayloadHandler),this.provider.off(je.connect,this.onConnectHandler),this.provider.off(je.disconnect,this.onDisconnectHandler),this.provider.off(je.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await jn();Dp(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(u.r.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Mp())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},u.cjs.toMiliseconds(bd)))))}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 zf(){}function Yn(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 Zn(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Xn(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Hf="[object RegExp]",Vf="[object String]",Kf="[object Number]",Gf="[object Boolean]",eo="[object Arguments]",Wf="[object Symbol]",Jf="[object Date]",Qf="[object Map]",Yf="[object Set]",Zf="[object Array]",Xf="[object Function]",ey="[object ArrayBuffer]",ks="[object Object]",ty="[object Error]",iy="[object DataView]",sy="[object Uint8Array]",ry="[object Uint8ClampedArray]",ny="[object Uint16Array]",oy="[object Uint32Array]",ay="[object BigUint64Array]",cy="[object Int8Array]",hy="[object Int16Array]",ly="[object Int32Array]",uy="[object BigInt64Array]",py="[object Float32Array]",dy="[object Float64Array]";function gy(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function fy(i,e,t){return _i(i,e,void 0,void 0,void 0,void 0,t)}function _i(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 Si(i,e,n,o)}return Si(i,e,n,o)}function Si(i,e,t,s){if(Object.is(i,e))return!0;let r=Xn(i),n=Xn(e);if(r===eo&&(r=ks),n===eo&&(n=ks),r!==n)return!1;switch(r){case Vf:return i.toString()===e.toString();case Kf:{const c=i.valueOf(),h=e.valueOf();return gy(c,h)}case Gf:case Jf:case Wf:return Object.is(i.valueOf(),e.valueOf());case Hf:return i.source===e.source&&i.flags===e.flags;case Xf: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 Qf:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!_i(h,e.get(c),c,i,e,t,s))return!1;return!0}case Yf:{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 p=c[l],d=h.findIndex(g=>_i(p,g,void 0,i,e,t,s));if(d===-1)return!1;h.splice(d,1)}return!0}case Zf:case sy:case ry:case ny:case oy:case ay:case cy:case hy:case ly:case uy:case py:case dy:{if(typeof q.dist.Buffer<"u"&&q.dist.Buffer.isBuffer(i)!==q.dist.Buffer.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!_i(i[c],e[c],c,i,e,t,s))return!1;return!0}case ey:return i.byteLength!==e.byteLength?!1:Si(new Uint8Array(i),new Uint8Array(e),t,s);case iy:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:Si(new Uint8Array(i),new Uint8Array(e),t,s);case ty:return i.name===e.name&&i.message===e.message;case ks:{if(!(Si(i.constructor,e.constructor,t,s)||Yn(i)&&Yn(e)))return!1;const c=[...Object.keys(i),...Zn(i)],h=[...Object.keys(e),...Zn(e)];if(c.length!==h.length)return!1;for(let l=0;l<c.length;l++){const p=c[l],d=i[p];if(!Object.hasOwn(e,p))return!1;const g=e[p];if(!_i(d,g,p,i,e,t,s))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function yy(i,e){return fy(i,e,zf)}var my=Object.defineProperty,to=Object.getOwnPropertySymbols,wy=Object.prototype.hasOwnProperty,by=Object.prototype.propertyIsEnumerable,pr=(i,e,t)=>e in i?my(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,io=(i,e)=>{for(var t in e||(e={}))wy.call(e,t)&&pr(i,t,e[t]);if(to)for(var t of to(e))by.call(e,t)&&pr(i,t,e[t]);return i},Pe=(i,e,t)=>pr(i,typeof e!="symbol"?e+"":e,t);class Ct extends Yp{constructor(e,t,s,r=Ze,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,Pe(this,"map",new Map),Pe(this,"version",vd),Pe(this,"cached",[]),Pe(this,"initialized",!1),Pe(this,"getKey"),Pe(this,"storagePrefix",Ze),Pe(this,"recentlyDeleted",[]),Pe(this,"recentlyDeletedLimit",200),Pe(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):gp(o)?this.map.set(o.id,o):fp(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Pe(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())}),Pe(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Pe(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>yy(a[c],o[c]))):this.values)),Pe(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=io(io({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Pe(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=u.E(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=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 vy=Object.defineProperty,Ey=(i,e,t)=>e in i?vy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,z=(i,e,t)=>Ey(i,typeof e!="symbol"?e+"":e,t);class Iy{constructor(e,t){this.core=e,this.logger=t,z(this,"name",Pd),z(this,"version",$d),z(this,"events",new He.Nt),z(this,"pairings"),z(this,"initialized",!1),z(this,"storagePrefix",Ze),z(this,"ignoredPayloadTypes",[ct]),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=sr(),n=await this.core.crypto.setSymKey(r),o=ce(u.cjs.FIVE_MINUTES),a={protocol:Na},c={topic:n,expiry:o,relay:a,active:!1,methods:s==null?void 0:s.methods},h=$n({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(_t.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:[Je.pairing_started]}});this.isValidPair(s,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=Pn(s.uri);r.props.properties.topic=n,r.addTrace(Je.pairing_uri_validation_success),r.addTrace(Je.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(Je.existing_pairing),l.active)throw r.setError(rt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(Je.pairing_not_expired)}const p=c||ce(u.cjs.FIVE_MINUTES),d={topic:n,relay:a,expiry:p,active:!1,methods:h};this.core.expirer.set(n,p),await this.pairings.set(n,d),r.addTrace(Je.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(_t.create,d),r.addTrace(Je.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(Je.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(rt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(g){throw r.setError(rt.subscribe_pairing_topic_failure),g}return r.addTrace(Je.subscribe_pairing_topic_success),d}),z(this,"activate",async({topic:s})=>{this.isInitialized();const r=ce(u.cjs.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}=vt();this.events.once(J("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",Q("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 $n({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=u.formatJsonRpcRequest(r,n),a=await this.core.crypto.encode(s,o),c=mi[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=u.formatJsonRpcResult(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=mi[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=u.formatJsonRpcError(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=mi[c]?mi[c].res:mi.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,Q("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=>ut(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(_t.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(()=>{u.isJsonRpcResult(r)?this.events.emit(J("pairing_ping",n),{}):u.isJsonRpcError(r)&&this.events.emit(J("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(_t.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=Q("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(Q("WC_METHOD_UNSUPPORTED",s))}),z(this,"isValidPair",(s,r)=>{var n;if(!$e(s)){const{message:a}=C("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(rt.malformed_pairing_uri),new Error(a)}if(!dp(s.uri)){const{message:a}=C("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(rt.malformed_pairing_uri),new Error(a)}const o=Pn(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(rt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=C("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(rt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&u.cjs.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(rt.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(!$e(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(!$e(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(!ne(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(ut(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=u.E(t,this.name),this.pairings=new Ct(this.core,this.logger,this.name,this.storagePrefix)}get context(){return u.y(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!==te.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);u.isJsonRpcRequest(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):u.isJsonRpcResponse(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,s)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(ke.expired,async e=>{const{topic:t}=Wo(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(_t.expire,{topic:t}))})}}var _y=Object.defineProperty,Py=(i,e,t)=>e in i?_y(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,me=(i,e,t)=>Py(i,typeof e!="symbol"?e+"":e,t);class $y extends Gp{constructor(e,t){super(e,t),this.core=e,this.logger=t,me(this,"records",new Map),me(this,"events",new He.eventsExports.EventEmitter),me(this,"name",Sd),me(this,"version",Od),me(this,"cached",[]),me(this,"initialized",!1),me(this,"storagePrefix",Ze),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:ce(u.cjs.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Fe.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=u.isJsonRpcError(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(Fe.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(Fe.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=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:u.formatJsonRpcRequest(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:s}=C("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Fe.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(Fe.created,e=>{const t=Fe.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Fe.updated,e=>{const t=Fe.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Fe.deleted,e=>{const t=Fe.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(u.r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{u.cjs.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Fe.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 Sy=Object.defineProperty,Oy=(i,e,t)=>e in i?Sy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ee=(i,e,t)=>Oy(i,typeof e!="symbol"?e+"":e,t);class Ay extends Xp{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ee(this,"expirations",new Map),Ee(this,"events",new He.eventsExports.EventEmitter),Ee(this,"name",Ad),Ee(this,"version",xd),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",Ze),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(ke.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(ke.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=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return yh(e);if(typeof e=="number")return mh(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(ke.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;u.cjs.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(ke.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(u.r.pulse,()=>this.checkExpirations()),this.events.on(ke.created,e=>{const t=ke.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(ke.expired,e=>{const t=ke.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(ke.deleted,e=>{const t=ke.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 xy=Object.defineProperty,Ry=(i,e,t)=>e in i?xy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,re=(i,e,t)=>Ry(i,typeof e!="symbol"?e+"":e,t);class Cy extends ed{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,re(this,"name",Rd),re(this,"abortController"),re(this,"isDevEnv"),re(this,"verifyUrlV3",Nd),re(this,"storagePrefix",Ze),re(this,"version",Ca),re(this,"publicKey"),re(this,"fetchPromise"),re(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&u.cjs.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),re(this,"register",async r=>{if(!hi()||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=u.getDocument_1(),l=this.startAbortTimer(u.cjs.ONE_SECOND*5),p=await new Promise((d,g)=>{const f=()=>{window.removeEventListener("message",y),h.body.removeChild(w),g("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const w=h.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",f,{signal:this.abortController.signal});const y=b=>{if(b.data&&typeof b.data=="string")try{const m=JSON.parse(b.data);if(m.type==="verify_attestation"){if(u.sn(m.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(w),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",y),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};h.body.appendChild(w),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",p),p}catch(h){this.logger.warn(h)}return""}),re(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(u.sn(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),re(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(u.cjs.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}),re(this,"getVerifyUrl",r=>{let n=r||$i;return Td.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${$i}`),n=$i),n}),re(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(u.cjs.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)}}),re(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),re(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),re(this,"isValidJwtAttestation",async 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")}}),re(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),re(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),re(this,"validateAttestation",(r,n)=>{const o=Ku(r,n.publicKey),a={hasExpired:u.cjs.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=u.E(t,this.name),this.abortController=new AbortController,this.isDevEnv=Ir(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return u.y(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),u.cjs.toMiliseconds(e))}}var Ny=Object.defineProperty,Ty=(i,e,t)=>e in i?Ny(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,so=(i,e,t)=>Ty(i,typeof e!="symbol"?e+"":e,t);class jy extends td{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,so(this,"context",jd),so(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${qd}/${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=u.E(t,this.context)}}var qy=Object.defineProperty,ro=Object.getOwnPropertySymbols,ky=Object.prototype.hasOwnProperty,Dy=Object.prototype.propertyIsEnumerable,dr=(i,e,t)=>e in i?qy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vi=(i,e)=>{for(var t in e||(e={}))ky.call(e,t)&&dr(i,t,e[t]);if(ro)for(var t of ro(e))Dy.call(e,t)&&dr(i,t,e[t]);return i},le=(i,e,t)=>dr(i,typeof e!="symbol"?e+"":e,t);class Fy extends id{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,le(this,"context",Dd),le(this,"storagePrefix",Ze),le(this,"storageVersion",kd),le(this,"events",new Map),le(this,"shouldPersist",!1),le(this,"init",async()=>{if(!Ir())try{const r={eventId:Gr(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ko(this.core.relayer.protocol,this.core.relayer.version,nr)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),le(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,h=Gr(),l=this.core.projectId||"",p=Date.now(),d=vi({eventId:h,timestamp:p,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,d),this.shouldPersist=!0),d}),le(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 vi(vi({},a),this.setMethods(a.eventId))}),le(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),le(this,"setEventListeners",()=>{this.core.heartbeat.on(u.r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{u.cjs.fromMiliseconds(Date.now())-u.cjs.fromMiliseconds(r.timestamp)>Fd&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),le(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),le(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)}),le(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)}),le(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),le(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,vi(vi({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),le(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)}}),le(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Ud}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${nr}${n}`,{method:"POST",body:JSON.stringify(r)})}),le(this,"getAppDomain",()=>Vo().url),this.logger=u.E(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var Uy=Object.defineProperty,no=Object.getOwnPropertySymbols,My=Object.prototype.hasOwnProperty,Ly=Object.prototype.propertyIsEnumerable,gr=(i,e,t)=>e in i?Uy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oo=(i,e)=>{for(var t in e||(e={}))My.call(e,t)&&gr(i,t,e[t]);if(no)for(var t of no(e))Ly.call(e,t)&&gr(i,t,e[t]);return i},ee=(i,e,t)=>gr(i,typeof e!="symbol"?e+"":e,t);let By=class Va extends zp{constructor(e){var t;super(e),ee(this,"protocol",Ra),ee(this,"version",Ca),ee(this,"name",rr),ee(this,"relayUrl"),ee(this,"projectId"),ee(this,"customStoragePrefix"),ee(this,"events",new He.eventsExports.EventEmitter),ee(this,"logger"),ee(this,"heartbeat"),ee(this,"relayer"),ee(this,"crypto"),ee(this,"storage"),ee(this,"history"),ee(this,"expirer"),ee(this,"pairing"),ee(this,"verify"),ee(this,"echoClient"),ee(this,"linkModeSupportedApps"),ee(this,"eventClient"),ee(this,"initialized",!1),ee(this,"logChunkController"),ee(this,"on",(a,c)=>this.events.on(a,c)),ee(this,"once",(a,c)=>this.events.once(a,c)),ee(this,"off",(a,c)=>this.events.off(a,c)),ee(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ee(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:te.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)||Ta,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=u.k({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:ad.logger,name:rr}),{logger:n,chunkLoggerController:o}=u.A({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=u.E(n,this.name),this.heartbeat=new u.i,this.crypto=new ff(this,this.logger,e==null?void 0:e.keychain),this.history=new $y(this,this.logger),this.expirer=new Ay(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new u.h(oo(oo({},cd),e==null?void 0:e.storageOptions)),this.relayer=new Bf({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Iy(this,this.logger),this.verify=new Cy(this,this.logger,this.storage),this.echoClient=new jy(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Fy(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Va(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(Ed,s),t}get context(){return u.y(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Un,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(Un)||[],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 q.dist.process<"u"&&q.dist.process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const zy=By,Ka="wc",Ga=2,Wa="client",Rr=`${Ka}@${Ga}:${Wa}:`,Ds={name:Wa,logger:"error"},ao="WALLETCONNECT_DEEPLINK_CHOICE",Hy="proposal",co="Proposal expired",Vy="session",Dt=u.cjs.SEVEN_DAYS,Ky="engine",ue={wc_sessionPropose:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1104},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1106},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1112},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1114},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:u.cjs.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:u.cjs.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1119}}},Fs={min:u.cjs.FIVE_MINUTES,max:u.cjs.SEVEN_DAYS},We={idle:"IDLE",active:"ACTIVE"},ho={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Gy="request",Wy=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Jy="wc",Qy="auth",Yy="authKeys",Zy="pairingTopics",Xy="requests",ws=`${Jy}@${1.5}:${Qy}:`,is=`${ws}:PUB_KEY`;var em=Object.defineProperty,tm=Object.defineProperties,im=Object.getOwnPropertyDescriptors,lo=Object.getOwnPropertySymbols,sm=Object.prototype.hasOwnProperty,rm=Object.prototype.propertyIsEnumerable,fr=(i,e,t)=>e in i?em(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Z=(i,e)=>{for(var t in e||(e={}))sm.call(e,t)&&fr(i,t,e[t]);if(lo)for(var t of lo(e))rm.call(e,t)&&fr(i,t,e[t]);return i},Ie=(i,e)=>tm(i,im(e)),I=(i,e,t)=>fr(i,typeof e!="symbol"?e+"":e,t);class nm extends od{constructor(e){super(e),I(this,"name",Ky),I(this,"events",new He.Nt),I(this,"initialized",!1),I(this,"requestQueue",{state:We.idle,queue:[]}),I(this,"sessionRequestQueue",{state:We.idle,queue:[]}),I(this,"requestQueueDelay",u.cjs.ONE_SECOND),I(this,"expectedPairingMethodMap",new Map),I(this,"recentlyDeletedMap",new Map),I(this,"recentlyDeletedLimit",200),I(this,"relayMessageCache",[]),I(this,"pendingSessions",new Map),I(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(ue)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},u.cjs.toMiliseconds(this.requestQueueDelay)))}),I(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=Ie(Z({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=cp(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h}=s;let l=r,p,d=!1;try{if(l){const $=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."),d=$.active}}catch($){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),$}if(!l||!d){const{topic:$,uri:O}=await this.client.core.pairing.create();l=$,p=O}if(!l){const{message:$}=C("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error($)}const g=await this.client.core.crypto.generateKeyPair(),f=ue.wc_sessionPropose.req.ttl||u.cjs.FIVE_MINUTES,w=ce(f),y=Ie(Z(Z({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:Na}],proposer:{publicKey:g,metadata:this.client.metadata},expiryTimestamp:w,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:u.payloadId()}),b=J("session_connect",y.id),{reject:m,resolve:v,done:P}=vt(f,co),R=({id:$})=>{$===y.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(y.id),this.events.emit(b,{error:{message:co,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(b,({error:$,session:O})=>{this.client.events.off("proposal_expire",R),$?m($):O&&v(O)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:y,throwOnFailedPublish:!0,clientRpcId:y.id}),await this.setProposal(y.id,y),{uri:p,approval:P}}),I(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}}),I(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:[Ue.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(E){throw o.setError(wt.no_internet_connection),E}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(E){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(wt.proposal_not_found),E}try{await this.isValidApprove(t)}catch(E){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(wt.session_approve_namespace_validation_failure),E}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:p,sessionConfig:d}=t,g=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:w,requiredNamespaces:y,optionalNamespaces:b}=g;let m=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:f});m||(m=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Ue.session_approve_started,properties:{topic:f,trace:[Ue.session_approve_started,Ue.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),P=w.publicKey,R=await this.client.core.crypto.generateSharedKey(v,P),$=Z(Z(Z({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:v,metadata:this.client.metadata},expiry:ce(Dt)},l&&{sessionProperties:l}),p&&{scopedProperties:p}),d&&{sessionConfig:d}),O=te.relay;m.addTrace(Ue.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:O})}catch(E){throw m.setError(wt.subscribe_session_topic_failure),E}m.addTrace(Ue.subscribe_session_topic_success);const N=Ie(Z({},$),{topic:R,requiredNamespaces:y,optionalNamespaces:b,pairingTopic:f,acknowledged:!1,self:$.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:v,transportType:te.relay});await this.client.session.set(R,N),m.addTrace(Ue.store_session);try{m.addTrace(Ue.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:$,throwOnFailedPublish:!0}).catch(E=>{throw m==null||m.setError(wt.session_settle_publish_failure),E}),m.addTrace(Ue.session_settle_publish_success),m.addTrace(Ue.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:v},throwOnFailedPublish:!0}).catch(E=>{throw m==null||m.setError(wt.session_approve_publish_failure),E}),m.addTrace(Ue.session_approve_publish_success)}catch(E){throw this.client.logger.error(E),this.client.session.delete(R,Q("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),E}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:w.metadata}),await this.client.proposal.delete(a,Q("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(R,ce(Dt)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}}),I(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:ue.wc_sessionPropose.reject}),await this.client.proposal.delete(s,Q("USER_DISCONNECTED")))}),I(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(p){throw this.client.logger.error("update() -> isValidUpdate() failed"),p}const{topic:s,namespaces:r}=t,{done:n,resolve:o,reject:a}=vt(),c=u.payloadId(),h=u.getBigIntRpcId().toString(),l=this.client.session.get(s).namespaces;return this.events.once(J("session_update",c),({error:p})=>{p?a(p):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(p=>{this.client.logger.error(p),this.client.session.update(s,{namespaces:l}),a(p)}),{acknowledged:n}}),I(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=u.payloadId(),{done:n,resolve:o,reject:a}=vt();return this.events.once(J("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,ce(Dt)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),I(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:s,request:r,topic:n,expiry:o=ue.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===te.relay&&await this.confirmOnlineStateOrThrow();const c=u.payloadId(),h=u.getBigIntRpcId().toString(),{done:l,resolve:p,reject:d}=vt(o,"Request expired. Please try again.");this.events.once(J("session_request",c),({error:b,result:m})=>{b?d(b):p(m)});const g="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:{request:Ie(Z({},r),{expiryTimestamp:ce(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const w={request:Ie(Z({},r),{expiryTimestamp:ce(o)}),chainId:s},y=this.shouldSetTVF(g,w);return await Promise.all([new Promise(async b=>{await this.sendRequest(Z({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:w,expiry:o,throwOnFailedPublish:!0},y&&{tvf:this.getTVFParams(c,w)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),b()}),new Promise(async b=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const v=await Eh(this.client.core.storage,ao);await wh({id:c,topic:n,wcDeepLink:v})}b()}),l()]).then(b=>b[2])}),I(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===te.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);u.isJsonRpcResult(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):u.isJsonRpcError(r)&&await this.sendError({id:n,topic:s,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),I(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=u.payloadId(),n=u.getBigIntRpcId().toString(),{done:o,resolve:a,reject:c}=vt();this.events.once(J("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}))}),I(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:s,event:r,chainId:n}=t,o=u.getBigIntRpcId().toString(),a=u.payloadId();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),I(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:Q("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)}}),I(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(s=>up(s,t)))),I(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),I(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?te.link_mode:te.relay;o===te.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:p,type:d,exp:g,nbf:f,methods:w=[],expiry:y}=t,b=[...t.resources||[]],{topic:m,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:v}});const P=await this.client.core.crypto.generateKeyPair(),R=es(P);if(await Promise.all([this.client.auth.authKeys.set(is,{responseTopic:R,publicKey:P}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:m})]),await this.client.core.relayer.subscribe(R,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),w.length>0){const{namespace:S}=Xt(a[0]);let U=dl(S,"request",w);Xi(b)&&(U=fl(U,b.pop())),b.push(U)}const $=y&&y>ue.wc_sessionAuthenticate.req.ttl?y:ue.wc_sessionAuthenticate.req.ttl,O={authPayload:{type:d??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:p,iat:new Date().toISOString(),exp:g,nbf:f,resources:b},requester:{publicKey:P,metadata:this.client.metadata},expiryTimestamp:ce($)},N={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},E={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:P,metadata:this.client.metadata},expiryTimestamp:ce(ue.wc_sessionPropose.req.ttl),id:u.payloadId()},{done:F,resolve:j,reject:D}=vt($,"Request expired"),M=u.payloadId(),_=J("session_connect",E.id),x=J("session_request",M),A=async({error:S,session:U})=>{this.events.off(x,T),S?D(S):U&&j({session:U})},T=async S=>{var U,L,B;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),S.error){const ae=Q("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return S.error.code===ae.code?void 0:(this.events.off(_,A),D(S.error.message))}await this.deleteProposal(E.id),this.events.off(_,A);const{cacaos:X,responder:W}=S.result,se=[],he=[];for(const ae of X){await tn({cacao:ae,projectId:this.client.core.projectId})||(this.client.logger.error(ae,"Signature verification failed"),D(Q("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:mt}=ae,Xe=Xi(mt.resources),Ve=[Ws(mt.iss)],et=ns(mt.iss);if(Xe){const tt=sn(Xe),Li=rn(Xe);se.push(...tt),Ve.push(...Li)}for(const tt of Ve)he.push(`${tt}:${et}`)}const ve=await this.client.core.crypto.generateSharedKey(P,W.publicKey);let oe;se.length>0&&(oe={topic:ve,acknowledged:!0,self:{publicKey:P,metadata:this.client.metadata},peer:W,controller:W.publicKey,expiry:ce(Dt),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:xn([...new Set(se)],[...new Set(he)]),transportType:o},await this.client.core.relayer.subscribe(ve,{transportType:o}),await this.client.session.set(ve,oe),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:W.metadata}),oe=this.client.session.get(ve)),(U=this.client.metadata.redirect)!=null&&U.linkMode&&(L=W.metadata.redirect)!=null&&L.linkMode&&(B=W.metadata.redirect)!=null&&B.universal&&s&&(this.client.core.addLinkModeSupportedApp(W.metadata.redirect.universal),this.client.session.update(ve,{transportType:te.link_mode})),j({auths:X,session:oe})};this.events.once(_,A),this.events.once(x,T);let k;try{if(n){const S=u.formatJsonRpcRequest("wc_sessionAuthenticate",O,M);this.client.core.history.set(m,S);const U=await this.client.core.crypto.encode("",S,{type:Ui,encoding:pt});k=Ki(s,m,U)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:O,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:M}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:E,expiry:ue.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(S){throw this.events.off(_,A),this.events.off(x,T),S}return await this.setProposal(E.id,E),await this.setAuthRequest(M,{request:Ie(Z({},O),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:k??v,response:F}}),I(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[bt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw n.setError(wi.no_internet_connection),y}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(wi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||te.relay;a===te.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=es(c),p={type:ct,receiverPublicKey:c,senderPublicKey:h},d=[],g=[];for(const y of r){if(!await tn({cacao:y,projectId:this.client.core.projectId})){n.setError(wi.invalid_cacao);const R=Q("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:R,encodeOpts:p}),new Error(R.message)}n.addTrace(bt.cacaos_verified);const{p:b}=y,m=Xi(b.resources),v=[Ws(b.iss)],P=ns(b.iss);if(m){const R=sn(m),$=rn(m);d.push(...R),v.push(...$)}for(const R of v)g.push(`${R}:${P}`)}const f=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(bt.create_authenticated_session_topic);let w;if((d==null?void 0:d.length)>0){w={topic:f,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ce(Dt),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:xn([...new Set(d)],[...new Set(g)]),transportType:a},n.addTrace(bt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(y){throw n.setError(wi.subscribe_authenticated_session_topic_failure),y}n.addTrace(bt.subscribe_authenticated_session_topic_success),await this.client.session.set(f,w),n.addTrace(bt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(bt.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:s,result:{cacaos:r,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:p,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw n.setError(wi.authenticated_session_approve_publish_failure),y}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:w}}),I(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===te.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=es(o),h={type:ct,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:s,topic:c,error:r,encodeOpts:h,rpcOpts:ue.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,Q("USER_DISCONNECTED"))}),I(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return sa(s,r)}),I(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)}),I(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)}}),I(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,Q("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(ao).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,Q("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=We.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),I(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(wt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Q("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),I(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=We.idle,this.client.events.emit("session_request_expire",{id:t}))}),I(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)])}),I(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}))}),I(this,"setProposal",async(t,s)=>{this.client.core.expirer.set(t,ce(ue.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),I(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=te.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})}),I(this,"setPendingSessionRequest",async t=>{const{id:s,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ce(ue.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})}),I(this,"sendRequest",async t=>{const{topic:s,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:p}=t,d=u.formatJsonRpcRequest(r,n,c);let g;const f=!!l;try{const b=f?pt:Be;g=await this.client.core.crypto.encode(s,d,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),b}let w;if(Wy.includes(r)){const b=Qe(JSON.stringify(d)),m=Qe(g);w=await this.client.core.verify.register({id:m,decryptedId:b})}const y=ue[r].req;if(y.attestation=w,o&&(y.ttl=o),a&&(y.id=a),this.client.core.history.set(s,d),f){const b=Ki(l,s,g);await q.dist.global.Linking.openURL(b,this.client.name)}else{const b=ue[r].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=Ie(Z({},p),{correlationId:d.id}),h?(b.internal=Ie(Z({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,g,b)):this.client.core.relayer.publish(s,g,b).catch(m=>this.client.logger.error(m))}return d.id}),I(this,"sendResult",async t=>{const{id:s,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=u.formatJsonRpcResult(s,n);let l;const p=c&&typeof(q.dist.global==null?void 0:q.dist.global.Linking)<"u";try{const f=p?pt:Be;l=await this.client.core.crypto.encode(r,h,Ie(Z({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),f}let d,g;try{d=await this.client.core.history.get(r,s);const f=d.request;try{this.shouldSetTVF(f.method,f.params)&&(g=this.getTVFParams(s,f.params,n))}catch(w){this.client.logger.warn("sendResult() -> getTVFParams() failed",w)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),f}if(p){const f=Ki(c,r,l);await q.dist.global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,w=ue[f].res;w.tvf=Ie(Z({},g),{correlationId:s}),o?(w.internal=Ie(Z({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,w)):this.client.core.relayer.publish(r,l,w).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(h)}),I(this,"sendError",async t=>{const{id:s,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=u.formatJsonRpcError(s,n);let l;const p=c&&typeof(q.dist.global==null?void 0:q.dist.global.Linking)<"u";try{const g=p?pt:Be;l=await this.client.core.crypto.encode(r,h,Ie(Z({},o||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),g}let d;try{d=await this.client.core.history.get(r,s)}catch(g){throw this.client.logger.error(`sendError() -> history.get(${r}, ${s}) failed`),g}if(p){const g=Ki(c,r,l);await q.dist.global.Linking.openURL(g,this.client.name)}else{const g=d.request.method,f=a||ue[g].res;this.client.core.relayer.publish(r,l,f)}await this.client.core.history.resolve(h)}),I(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;ut(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=>{ut(r.expiryTimestamp)&&s.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...s.map(r=>this.deleteProposal(r))])}),I(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),I(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),I(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===We.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=We.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=We.idle}),I(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}`)}}),I(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}`)}}),I(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)}),I(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)}),I(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(rt.proposal_listener_not_found)),this.isValidConnect(Z({},r.params));const l=a.expiryTimestamp||ce(ue.wc_sessionPropose.req.ttl),p=Z({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,p);const d=await this.getVerifyContext({attestationId:n,hash:Qe(JSON.stringify(r)),encryptedId:o,metadata:p.proposer.metadata});h==null||h.addTrace(Je.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:p,verifyContext:d})}catch(h){await this.sendError({id:c,topic:s,error:h,rpcOpts:ue.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),I(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(u.isJsonRpcResult(s)){const{result:o}=s;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(c,h);this.pendingSessions.set(n,{sessionTopic:l,pairingTopic:t,proposalId:n,publicKey:c});const p=await this.client.core.relayer.subscribe(l,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:p}),await this.client.core.pairing.activate({topic:t})}else if(u.isJsonRpcError(s)){await this.client.proposal.delete(n,Q("USER_DISCONNECTED"));const o=J("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})}}),I(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:p,sessionConfig:d}=s.params,g=[...this.pendingSessions.values()].find(y=>y.sessionTopic===t);if(!g)return this.client.logger.error(`Pending session not found for topic ${t}`);const f=this.client.proposal.get(g.proposalId),w=Ie(Z(Z(Z({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:g.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:g.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),p&&{scopedProperties:p}),d&&{sessionConfig:d}),{transportType:te.relay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:g.pairingTopic,metadata:w.peer.metadata}),this.client.events.emit("session_connect",{session:w}),this.events.emit(J("session_connect",g.proposalId),{session:w}),this.pendingSessions.delete(g.proposalId),this.deleteProposal(g.proposalId,!1),this.cleanupDuplicatePairings(w),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)}}),I(this,"onSessionSettleResponse",async(t,s)=>{const{id:r}=s;u.isJsonRpcResult(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(J("session_approve",r),{})):u.isJsonRpcError(s)&&(await this.client.session.delete(t,Q("USER_DISCONNECTED")),this.events.emit(J("session_approve",r),{error:s.error}))}),I(this,"onSessionUpdateRequest",async(t,s)=>{const{params:r,id:n}=s;try{const o=`${t}_session_update`,a=yi.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:Q("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Z({topic:t},r));try{yi.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 yi.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)}}),I(this,"isRequestOutOfSync",(t,s)=>s.toString().slice(0,-3)<t.toString().slice(0,-3)),I(this,"onSessionUpdateResponse",(t,s)=>{const{id:r}=s,n=J("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(s)?this.events.emit(J("session_update",r),{}):u.isJsonRpcError(s)&&this.events.emit(J("session_update",r),{error:s.error})}),I(this,"onSessionExtendRequest",async(t,s)=>{const{id:r}=s;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ce(Dt)),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)}}),I(this,"onSessionExtendResponse",(t,s)=>{const{id:r}=s,n=J("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(s)?this.events.emit(J("session_extend",r),{}):u.isJsonRpcError(s)&&this.events.emit(J("session_extend",r),{error:s.error})}),I(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)}}),I(this,"onSessionPingResponse",(t,s)=>{const{id:r}=s,n=J("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);u.isJsonRpcResult(s)?this.events.emit(J("session_ping",r),{}):u.isJsonRpcError(s)&&this.events.emit(J("session_ping",r),{error:s.error})},500)}),I(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:Q("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),I(this,"onSessionRequest",async t=>{var s,r,n;const{topic:o,payload:a,attestation:c,encryptedId:h,transportType:l}=t,{id:p,params:d}=a;try{await this.isValidRequest(Z({topic:o},d));const g=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:Qe(JSON.stringify(u.formatJsonRpcRequest("wc_sessionRequest",d,p))),encryptedId:h,metadata:g.peer.metadata,transportType:l}),w={id:p,topic:o,params:d,verifyContext:f};await this.setPendingSessionRequest(w),l===te.link_mode&&(s=g.peer.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp((r=g.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(g){await this.sendError({id:p,topic:o,error:g}),this.client.logger.error(g)}}),I(this,"onSessionRequestResponse",(t,s)=>{const{id:r}=s,n=J("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(s)?this.events.emit(J("session_request",r),{result:s.result}):u.isJsonRpcError(s)&&this.events.emit(J("session_request",r),{error:s.error})}),I(this,"onSessionEventRequest",async(t,s)=>{const{id:r,params:n}=s;try{const o=`${t}_session_event_${n.event.name}`,a=yi.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Z({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),yi.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),I(this,"onSessionAuthenticateResponse",(t,s)=>{const{id:r}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:s}),u.isJsonRpcResult(s)?this.events.emit(J("session_request",r),{result:s.result}):u.isJsonRpcError(s)&&this.events.emit(J("session_request",r),{error:s.error})}),I(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:p}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Qe(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),g={requester:h,pairingTopic:r,id:n.id,authPayload:l,verifyContext:d,expiryTimestamp:p};await this.setAuthRequest(n.id,{request:g,pairingTopic:r,transportType:c}),c===te.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:d})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,p=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),g={type:ct,receiverPublicKey:l,senderPublicKey:p};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:g,rpcOpts:ue.wc_sessionAuthenticate.autoReject,appLink:d})}}),I(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),I(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=We.idle,this.processSessionRequestQueue()},u.cjs.toMiliseconds(this.requestQueueDelay))}),I(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=J("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(J("session_request",n.request.id),{error:s})})}),I(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===We.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=We.active,this.emitSessionRequest(t)}catch(s){this.client.logger.error(s)}}),I(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),I(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:u.formatJsonRpcRequest("wc_sessionPropose",Ie(Z({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id)})}),I(this,"isValidConnect",async t=>{if(!$e(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),!_p(c)){const{message:h}=C("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!we(r)&&ft(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)&&ft(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)}`)}}),I(this,"validateNamespaces",(t,s)=>{const r=Ip(t,"connect()",s);if(r)throw new Error(r.message)}),I(this,"isValidApprove",async t=>{if(!$e(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=Cs(r,"approve()");if(h)throw new Error(h.message);const l=Nn(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!ne(n,!0)){const{message:p}=C("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(p)}if(we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const p=new Set(Object.keys(r));if(!Object.keys(a).every(d=>p.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(p).join(", ")}`)}}),I(this,"isValidReject",async t=>{if(!$e(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),!$p(r)){const{message:n}=C("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),I(this,"isValidSessionSettleRequest",t=>{if(!$e(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(!xa(s)){const{message:h}=C("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=yp(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Cs(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ut(o)){const{message:h}=C("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),I(this,"isValidUpdate",async t=>{if(!$e(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=Cs(r,"update()");if(o)throw new Error(o.message);const a=Nn(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),I(this,"isValidExtend",async t=>{if(!$e(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)}),I(this,"isValidRequest",async t=>{if(!$e(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(!Cn(a,n)){const{message:c}=C("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!Sp(r)){const{message:c}=C("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!xp(a,n,r.method)){const{message:c}=C("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Tp(o,Fs)){const{message:c}=C("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Fs.min} and ${Fs.max}`);throw new Error(c)}}),I(this,"isValidRespond",async t=>{var s;if(!$e(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(!Op(n)){const{message:o}=C("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),I(this,"isValidPing",async t=>{if(!$e(t)){const{message:r}=C("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),I(this,"isValidEmit",async t=>{if(!$e(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(!Cn(o,n)){const{message:a}=C("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Ap(r)){const{message:a}=C("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Rp(o,n,r.name)){const{message:a}=C("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),I(this,"isValidDisconnect",async t=>{if(!$e(t)){const{message:r}=C("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),I(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(!ne(r,!1))throw new Error("uri is required parameter");if(!ne(n,!1))throw new Error("domain is required parameter");if(!ne(o,!1))throw new Error("nonce is required parameter");if([...new Set(s.map(c=>Xt(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Xt(s[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),I(this,"getVerifyContext",async t=>{const{attestationId:s,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||$i,validation:"UNKNOWN",origin:o.url||""}};try{if(a===te.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}),I(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)}})}),I(this,"getPendingAuthRequest",t=>{const s=this.client.auth.requests.get(t);return typeof s=="object"?s:void 0}),I(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)}}}),I(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)}}),I(this,"isLinkModeEnabled",(t,s)=>{var r,n,o,a,c,h,l,p,d;return!t||s!==te.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&&((p=t==null?void 0:t.redirect)==null?void 0:p.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(q.dist.global==null?void 0:q.dist.global.Linking)<"u"}),I(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}),I(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const s=Kr(t,"topic")||"",r=decodeURIComponent(Kr(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:te.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),I(this,"registerLinkModeListeners",async()=>{var t;if(Ir()||yt()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const s=q.dist.global==null?void 0:q.dist.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)}}}),I(this,"shouldSetTVF",(t,s)=>{if(!s||t!=="wc_sessionRequest")return!1;const{request:r}=s;return Object.keys(ho).includes(r.method)}),I(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return Ie(Z({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{}}),I(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}),I(this,"extractTxHashesFromResult",(t,s)=>{try{const r=ho[t];if(typeof s=="string")return[s];const n=s[r.key];if(ze(n))return t==="solana_signAllTransactions"?n.map(o=>Xh(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(is)?this.client.auth.authKeys.get(is):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===te.link_mode?pt:Be});u.isJsonRpcRequest(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:Qe(s)})):u.isJsonRpcResponse(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,s)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ke.expired,async e=>{const{topic:t,id:s}=Wo(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(_t.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(_t.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ne(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(ut(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=C("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ne(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(ut(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(ne(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(!Pp(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(ut(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=C("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class om extends Ct{constructor(e,t){super(e,t,Hy,Rr),this.core=e,this.logger=t}}let am=class extends Ct{constructor(e,t){super(e,t,Vy,Rr),this.core=e,this.logger=t}};class cm extends Ct{constructor(e,t){super(e,t,Gy,Rr,s=>s.id),this.core=e,this.logger=t}}class hm extends Ct{constructor(e,t){super(e,t,Yy,ws,()=>is),this.core=e,this.logger=t}}class lm extends Ct{constructor(e,t){super(e,t,Zy,ws),this.core=e,this.logger=t}}class um extends Ct{constructor(e,t){super(e,t,Xy,ws,s=>s.id),this.core=e,this.logger=t}}var pm=Object.defineProperty,dm=(i,e,t)=>e in i?pm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Us=(i,e,t)=>dm(i,typeof e!="symbol"?e+"":e,t);class gm{constructor(e,t){this.core=e,this.logger=t,Us(this,"authKeys"),Us(this,"pairingTopics"),Us(this,"requests"),this.authKeys=new hm(this.core,this.logger),this.pairingTopics=new lm(this.core,this.logger),this.requests=new um(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var fm=Object.defineProperty,ym=(i,e,t)=>e in i?fm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,H=(i,e,t)=>ym(i,typeof e!="symbol"?e+"":e,t);let mm=class Ja extends nd{constructor(e){super(e),H(this,"protocol",Ka),H(this,"version",Ga),H(this,"name",Ds.name),H(this,"metadata"),H(this,"core"),H(this,"logger"),H(this,"events",new He.eventsExports.EventEmitter),H(this,"engine"),H(this,"session"),H(this,"proposal"),H(this,"pendingRequest"),H(this,"auth"),H(this,"signConfig"),H(this,"on",(s,r)=>this.events.on(s,r)),H(this,"once",(s,r)=>this.events.once(s,r)),H(this,"off",(s,r)=>this.events.off(s,r)),H(this,"removeListener",(s,r)=>this.events.removeListener(s,r)),H(this,"removeAllListeners",s=>this.events.removeAllListeners(s)),H(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"pair",async s=>{try{return await this.engine.pair(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"approve",async s=>{try{return await this.engine.approve(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"reject",async s=>{try{return await this.engine.reject(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"update",async s=>{try{return await this.engine.update(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"extend",async s=>{try{return await this.engine.extend(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"request",async s=>{try{return await this.engine.request(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"respond",async s=>{try{return await this.engine.respond(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"ping",async s=>{try{return await this.engine.ping(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"emit",async s=>{try{return await this.engine.emit(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"find",s=>{try{return this.engine.find(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}}),H(this,"authenticate",async(s,r)=>{try{return await this.engine.authenticate(s,r)}catch(n){throw this.logger.error(n.message),n}}),H(this,"formatAuthMessage",s=>{try{return this.engine.formatAuthMessage(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"approveSessionAuthenticate",async s=>{try{return await this.engine.approveSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),H(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)||Ds.name,this.metadata=ph(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:u.Ot(u.k({level:(e==null?void 0:e.logger)||Ds.logger}));this.core=(e==null?void 0:e.core)||new zy(e),this.logger=u.E(t,this.name),this.session=new am(this.core,this.logger),this.proposal=new om(this.core,this.logger),this.pendingRequest=new cm(this.core,this.logger),this.engine=new nm(this),this.auth=new gm(this.core,this.logger)}static async init(e){const t=new Ja(e);return await t.initialize(),t}get context(){return u.y(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},u.cjs.toMiliseconds(u.cjs.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const uo="error",wm="wss://relay.walletconnect.org",bm="wc",vm="universal_provider",Wi=`${bm}@2:${vm}:`,Qa="https://rpc.walletconnect.org/v1/",Jt="generic",Em=`${Qa}bundler`,De={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Im(){}function Cr(i){return i==null||typeof i!="object"&&typeof i!="function"}function Nr(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function _m(i){if(Cr(i))return i;if(Array.isArray(i)||Nr(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 po(i){return typeof i=="object"&&i!==null}function Ya(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Za(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Pm="[object RegExp]",Xa="[object String]",ec="[object Number]",tc="[object Boolean]",ic="[object Arguments]",$m="[object Symbol]",Sm="[object Date]",Om="[object Map]",Am="[object Set]",xm="[object Array]",Rm="[object ArrayBuffer]",Cm="[object Object]",Nm="[object DataView]",Tm="[object Uint8Array]",jm="[object Uint8ClampedArray]",qm="[object Uint16Array]",km="[object Uint32Array]",Dm="[object Int8Array]",Fm="[object Int16Array]",Um="[object Int32Array]",Mm="[object Float32Array]",Lm="[object Float64Array]";function Bm(i,e){return Zt(i,void 0,i,new Map,e)}function Zt(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(Cr(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]=Zt(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,Zt(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(Zt(a,void 0,t,s,r));return o}if(typeof q.dist.Buffer<"u"&&q.dist.Buffer.isBuffer(i))return i.subarray();if(Nr(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=Zt(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),Pt(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),Pt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),Pt(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,Pt(o,i,t,s,r),o}if(typeof i=="object"&&zm(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),Pt(o,i,t,s,r),o}return i}function Pt(i,e,t=i,s,r){const n=[...Object.keys(e),...Ya(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=Zt(e[a],a,t,s,r))}}function zm(i){switch(Za(i)){case ic:case xm:case Rm:case Nm:case tc:case Sm:case Mm:case Lm:case Dm:case Fm:case Um:case Om:case ec:case Cm:case Pm:case Am:case Xa:case $m:case Tm:case jm:case qm:case km:return!0;default:return!1}}function Hm(i,e){return Bm(i,(t,s,r,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case ec:case Xa:case tc:{const o=new i.constructor(i==null?void 0:i.valueOf());return Pt(o,i),o}case ic:{const o={};return Pt(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function go(i){return Hm(i)}function fo(i){return i!==null&&typeof i=="object"&&Za(i)==="[object Arguments]"}function Vm(i){return Nr(i)}function Km(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 Gm(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=yr(r,o,s,new Map)}return r}function yr(i,e,t,s){if(Cr(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(s.has(e))return _m(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),...Ya(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(fo(a)&&(a={...a}),fo(c)&&(c={...c}),typeof q.dist.Buffer<"u"&&q.dist.Buffer.isBuffer(a)&&(a=go(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],p=Reflect.ownKeys(c);for(let d=0;d<p.length;d++){const g=p[d];l[g]=c[g]}c=l}else c=[];const h=t(c,a,o,i,e,s);h!=null?i[o]=h:Array.isArray(a)||po(c)&&po(a)?i[o]=yr(c,a,t,s):c==null&&Km(a)?i[o]=yr({},a,t,s):c==null&&Vm(a)?i[o]=go(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Wm(i,...e){return Gm(i,...e,Im)}var Jm=Object.defineProperty,Qm=Object.defineProperties,Ym=Object.getOwnPropertyDescriptors,yo=Object.getOwnPropertySymbols,Zm=Object.prototype.hasOwnProperty,Xm=Object.prototype.propertyIsEnumerable,mo=(i,e,t)=>e in i?Jm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ji=(i,e)=>{for(var t in e||(e={}))Zm.call(e,t)&&mo(i,t,e[t]);if(yo)for(var t of yo(e))Xm.call(e,t)&&mo(i,t,e[t]);return i},ew=(i,e)=>Qm(i,Ym(e));function Te(i,e,t){var s;const r=Xt(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${Qa}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Nt(i){return i.includes(":")?i.split(":")[1]:i}function sc(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function tw(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 Qi(i={},e={}){const t=wo(i),s=wo(e);return Wm(t,s)}function wo(i){var e,t,s,r,n;const o={};if(!ft(i))return o;for(const[a,c]of Object.entries(i)){const h=ys(a)?[a]:c.chains,l=c.methods||[],p=c.events||[],d=c.rpcMap||{},g=Yt(a);o[g]=ew(Ji(Ji({},o[g]),c),{chains:Ye(h,(e=o[g])==null?void 0:e.chains),methods:Ye(l,(t=o[g])==null?void 0:t.methods),events:Ye(p,(s=o[g])==null?void 0:s.events)}),(ft(d)||ft(((r=o[g])==null?void 0:r.rpcMap)||{}))&&(o[g].rpcMap=Ji(Ji({},d),(n=o[g])==null?void 0:n.rpcMap))}return o}function bo(i){return i.includes(":")?i.split(":")[2]:i}function vo(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=ys(t)?[t]:s.chains?s.chains:sc(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Ms(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 rc={},G=i=>rc[i],Ls=(i,e)=>{rc[i]=e};var iw=Object.defineProperty,sw=(i,e,t)=>e in i?iw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ft=(i,e,t)=>sw(i,typeof e!="symbol"?e+"":e,t);class rw{constructor(e){Ft(this,"name","polkadot"),Ft(this,"client"),Ft(this,"httpProviders"),Ft(this,"events"),Ft(this,"namespace"),Ft(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(De.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=Nt(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||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var nw=Object.defineProperty,ow=Object.defineProperties,aw=Object.getOwnPropertyDescriptors,Eo=Object.getOwnPropertySymbols,cw=Object.prototype.hasOwnProperty,hw=Object.prototype.propertyIsEnumerable,mr=(i,e,t)=>e in i?nw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Io=(i,e)=>{for(var t in e||(e={}))cw.call(e,t)&&mr(i,t,e[t]);if(Eo)for(var t of Eo(e))hw.call(e,t)&&mr(i,t,e[t]);return i},_o=(i,e)=>ow(i,aw(e)),Ut=(i,e,t)=>mr(i,typeof e!="symbol"?e+"":e,t);class lw{constructor(e){Ut(this,"name","eip155"),Ut(this,"client"),Ut(this,"chainId"),Ut(this,"namespace"),Ut(this,"httpProviders"),Ut(this,"events"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(De.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||Te(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("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(Nt(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),p=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(p!=null&&p[h])return p==null?void 0:p[h];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:_o(Io({},l.sessionProperties||{}),{capabilities:_o(Io({},p||{}),{[h]:d})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return d}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(u.formatJsonRpcRequest("eth_getUserOperationReceipt",[(s=t.request.params)==null?void 0:s[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${Em}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var uw=Object.defineProperty,pw=(i,e,t)=>e in i?uw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Mt=(i,e,t)=>pw(i,typeof e!="symbol"?e+"":e,t);class dw{constructor(e){Mt(this,"name","solana"),Mt(this,"client"),Mt(this,"httpProviders"),Mt(this,"events"),Mt(this,"namespace"),Mt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(De.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=Nt(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||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var gw=Object.defineProperty,fw=(i,e,t)=>e in i?gw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Lt=(i,e,t)=>fw(i,typeof e!="symbol"?e+"":e,t);class yw{constructor(e){Lt(this,"name","cosmos"),Lt(this,"client"),Lt(this,"httpProviders"),Lt(this,"events"),Lt(this,"namespace"),Lt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(De.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=Nt(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||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var mw=Object.defineProperty,ww=(i,e,t)=>e in i?mw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Bt=(i,e,t)=>ww(i,typeof e!="symbol"?e+"":e,t);class bw{constructor(e){Bt(this,"name","algorand"),Bt(this,"client"),Bt(this,"httpProviders"),Bt(this,"events"),Bt(this,"namespace"),Bt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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||Te(`${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(De.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||Te(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new u.o(new u.f$1(s,G("disableProviderPing")))}}var vw=Object.defineProperty,Ew=(i,e,t)=>e in i?vw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,zt=(i,e,t)=>Ew(i,typeof e!="symbol"?e+"":e,t);class Iw{constructor(e){zt(this,"name","cip34"),zt(this,"client"),zt(this,"httpProviders"),zt(this,"events"),zt(this,"namespace"),zt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(De.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=Nt(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 u.o(new u.f$1(s,G("disableProviderPing")))}}var _w=Object.defineProperty,Pw=(i,e,t)=>e in i?_w(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ht=(i,e,t)=>Pw(i,typeof e!="symbol"?e+"":e,t);class $w{constructor(e){Ht(this,"name","elrond"),Ht(this,"client"),Ht(this,"httpProviders"),Ht(this,"events"),Ht(this,"namespace"),Ht(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(De.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=Nt(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||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var Sw=Object.defineProperty,Ow=(i,e,t)=>e in i?Sw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Vt=(i,e,t)=>Ow(i,typeof e!="symbol"?e+"":e,t);class Aw{constructor(e){Vt(this,"name","multiversx"),Vt(this,"client"),Vt(this,"httpProviders"),Vt(this,"events"),Vt(this,"namespace"),Vt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(De.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=Nt(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||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var xw=Object.defineProperty,Rw=(i,e,t)=>e in i?xw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Kt=(i,e,t)=>Rw(i,typeof e!="symbol"?e+"":e,t);class Cw{constructor(e){Kt(this,"name","near"),Kt(this,"client"),Kt(this,"httpProviders"),Kt(this,"events"),Kt(this,"namespace"),Kt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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||Te(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(De.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||Te(e,this.namespace);return typeof s>"u"?void 0:new u.o(new u.f$1(s,G("disableProviderPing")))}}var Nw=Object.defineProperty,Tw=(i,e,t)=>e in i?Nw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Gt=(i,e,t)=>Tw(i,typeof e!="symbol"?e+"":e,t);class jw{constructor(e){Gt(this,"name","tezos"),Gt(this,"client"),Gt(this,"httpProviders"),Gt(this,"events"),Gt(this,"namespace"),Gt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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||Te(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(De.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||Te(e,this.namespace);return typeof s>"u"?void 0:new u.o(new u.f$1(s))}}var qw=Object.defineProperty,kw=(i,e,t)=>e in i?qw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wt=(i,e,t)=>kw(i,typeof e!="symbol"?e+"":e,t);class Dw{constructor(e){Wt(this,"name",Jt),Wt(this,"client"),Wt(this,"httpProviders"),Wt(this,"events"),Wt(this,"namespace"),Wt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(De.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=Xt(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||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var Fw=Object.defineProperty,Uw=Object.defineProperties,Mw=Object.getOwnPropertyDescriptors,Po=Object.getOwnPropertySymbols,Lw=Object.prototype.hasOwnProperty,Bw=Object.prototype.propertyIsEnumerable,wr=(i,e,t)=>e in i?Fw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Yi=(i,e)=>{for(var t in e||(e={}))Lw.call(e,t)&&wr(i,t,e[t]);if(Po)for(var t of Po(e))Bw.call(e,t)&&wr(i,t,e[t]);return i},Bs=(i,e)=>Uw(i,Mw(e)),qe=(i,e,t)=>wr(i,typeof e!="symbol"?e+"":e,t);let zw=class nc{constructor(e){qe(this,"client"),qe(this,"namespaces"),qe(this,"optionalNamespaces"),qe(this,"sessionProperties"),qe(this,"scopedProperties"),qe(this,"events",new He.Nt),qe(this,"rpcProviders",{}),qe(this,"session"),qe(this,"providerOpts"),qe(this,"logger"),qe(this,"uri"),qe(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:u.Ot(u.k({level:(e==null?void 0:e.logger)||uo})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new nc(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:Yi({},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,u.formatJsonRpcResult(n,o))).catch(o=>t(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Q("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=vo(this.session.namespaces);this.namespaces=Qi(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=vo(r.namespaces);return this.namespaces=Qi(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===Jt?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(ze(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 mm.init({core:this.providerOpts.core,logger:this.providerOpts.logger||uo,relayUrl:this.providerOpts.relayUrl||wm,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=>Yt(t)))];Ls("client",this.client),Ls("events",this.events),Ls("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=tw(t,this.session),r=sc(s),n=Qi(this.namespaces,this.optionalNamespaces),o=Bs(Yi({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new lw({namespace:o});break;case"algorand":this.rpcProviders[t]=new bw({namespace:o});break;case"solana":this.rpcProviders[t]=new dw({namespace:o});break;case"cosmos":this.rpcProviders[t]=new yw({namespace:o});break;case"polkadot":this.rpcProviders[t]=new rw({namespace:o});break;case"cip34":this.rpcProviders[t]=new Iw({namespace:o});break;case"elrond":this.rpcProviders[t]=new $w({namespace:o});break;case"multiversx":this.rpcProviders[t]=new Aw({namespace:o});break;case"near":this.rpcProviders[t]=new Cw({namespace:o});break;case"tezos":this.rpcProviders[t]=new jw({namespace:o});break;default:this.rpcProviders[Jt]?this.rpcProviders[Jt].updateNamespace(o):this.rpcProviders[Jt]=new Dw({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&&ze(o)&&this.events.emit("accountsChanged",o.map(bo))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=Yt(o),h=Ms(o)!==Ms(a)?`${c}:${Ms(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=Bs(Yi({},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",Bs(Yi({},Q("USER_DISCONNECTED")),{data:e.topic})))}),this.on(De.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Jt]}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=Qi(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=>Yt(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=Yt(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(bo);if(!ze(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(`${Wi}/${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(`${Wi}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${Wi}/${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(Wi)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const Hw=zw,Vw="wc",Kw="ethereum_provider",Gw=`${Vw}@2:${Kw}:`,Ww="https://rpc.walletconnect.org/v1/",cs=["eth_sendTransaction","personal_sign"],oc=["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"],hs=["chainChanged","accountsChanged"],ac=["chainChanged","accountsChanged","message","disconnect","connect"],Jw=async()=>{const{createAppKit:i}=await Promise.resolve().then(()=>require("./core-v0G9f7LX.js")).then(e=>e.core);return i};var Qw=Object.defineProperty,Yw=Object.defineProperties,Zw=Object.getOwnPropertyDescriptors,$o=Object.getOwnPropertySymbols,Xw=Object.prototype.hasOwnProperty,eb=Object.prototype.propertyIsEnumerable,br=(i,e,t)=>e in i?Qw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Et=(i,e)=>{for(var t in e||(e={}))Xw.call(e,t)&&br(i,t,e[t]);if($o)for(var t of $o(e))eb.call(e,t)&&br(i,t,e[t]);return i},Ei=(i,e)=>Yw(i,Zw(e)),Ae=(i,e,t)=>br(i,typeof e!="symbol"?e+"":e,t);function ls(i){return Number(i[0].split(":")[1])}function Zi(i){return`0x${i.toString(16)}`}function tb(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!ze(e))throw new Error("Invalid chains");const c={chains:e,methods:s||cs,events:n||hs,rpcMap:Et({},e.length?{[ls(e)]:a[ls(e)]}:{})},h=n==null?void 0:n.filter(g=>!hs.includes(g)),l=s==null?void 0:s.filter(g=>!cs.includes(g));if(!t&&!o&&!r&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const p=(h==null?void 0:h.length)&&(l==null?void 0:l.length)||!t,d={chains:[...new Set(p?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(r!=null&&r.length?r:oc))],events:[...new Set(c.events.concat(o!=null&&o.length?o:ac))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?d:void 0}}class bs{constructor(){Ae(this,"events",new He.eventsExports.EventEmitter),Ae(this,"namespace","eip155"),Ae(this,"accounts",[]),Ae(this,"signer"),Ae(this,"chainId",1),Ae(this,"modal"),Ae(this,"rpc"),Ae(this,"STORAGE_KEY",Gw),Ae(this,"on",(e,t)=>(this.events.on(e,t),this)),Ae(this,"once",(e,t)=>(this.events.once(e,t),this)),Ae(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),Ae(this,"off",(e,t)=>(this.events.off(e,t),this)),Ae(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new bs;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}=tb(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(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const p=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Ei(Et({namespaces:Et({},s&&{[this.namespace]:s})},r&&{optionalNamespaces:{[this.namespace]:r}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:p})).then(d=>{a(d)}).catch(d=>{var g;(g=this.modal)==null||g.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=Lr(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Zi(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(Ei(Et({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var p;(p=this.modal)==null||p.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=r.session;if(n){const o=Lr(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Zi(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",Zi(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",Ei(Et({},Q("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",Zi(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)||cs:[],c=r.length?(e==null?void 0:e.events)||hs:[],h=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],p=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:r==null?void 0:r.map(g=>this.formatChainId(g)),optionalChains:n.map(g=>this.formatChainId(g)),methods:a,events:c,optionalMethods:h,optionalEvents:l,rpcMap:p,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,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?ls(this.rpc.chains):ls(this.rpc.optionalChains),this.signer=await Hw.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 Jw(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return pb}),n=r(Ei(Et({},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(Ei(Et({},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&&ze(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&&ze(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])||`${Ww}?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 ib=bs;var sb=Object.defineProperty,rb=Object.defineProperties,nb=Object.getOwnPropertyDescriptors,So=Object.getOwnPropertySymbols,ob=Object.prototype.hasOwnProperty,ab=Object.prototype.propertyIsEnumerable,Oo=(i,e,t)=>e in i?sb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,cc=(i,e)=>{for(var t in e||(e={}))ob.call(e,t)&&Oo(i,t,e[t]);if(So)for(var t of So(e))ab.call(e,t)&&Oo(i,t,e[t]);return i},cb=(i,e)=>rb(i,nb(e));function hb(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 lb=i=>{const[e,t]=i.split(":");return hc({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function ub(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(lb).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(p=>{var d;return p.id===((d=i.defaultChain)==null?void 0:d.id)}),l={projectId:i.projectId,networks:c,themeMode:i.themeMode,themeVariables:hb(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:cb(cc({},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 p=[...(i.mobileWallets||[]).map(f=>({id:f.id,name:f.name,links:f.links})),...(i.desktopWallets||[]).map(f=>({id:f.id,name:f.name,links:{native:f.links.native,universal:f.links.universal}}))],d=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],g=p.filter(f=>!d.includes(f.id));g.length&&(l.customWallets=g)}return l}function hc(i){return cc({formatters:void 0,fees:void 0,serializers:void 0},i)}var pb=Object.freeze({__proto__:null,convertWCMToAppKitOptions:ub,defineChain:hc});const db=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:ib,OPTIONAL_EVENTS:ac,OPTIONAL_METHODS:oc,REQUIRED_EVENTS:hs,REQUIRED_METHODS:cs,default:bs},Symbol.toStringTag,{value:"Module"}));exports.Hash=ko;exports.abytes=Ti;exports.aexists=Vs;exports.ahash=Pc;exports.aoutput=qo;exports.bs58=zo;exports.concatBytes=kc;exports.createView=Nc;exports.index_es=db;exports.keccak_256=Lo;exports.randomBytes=Dc;exports.rotr=Tc;exports.toBytes=vr;exports.wrapConstructor=Do;