@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,889 +0,0 @@
1
- "use strict";const U=require("./address-BGujeWtN.js"),Lt=require("./index-DKksdvND.js"),h=require("./index.es-C6YhioMN.js"),Bn=require("./index.es-D3Xxxr8I.js"),T=require("./lit-element-Df-39D6h.js"),Is=require("./http-D_Zdp_wT.js");require("./browser-ponyfill-CE6vRkjp.js");const H={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof U.dist.process<"u"&&typeof U.dist.process.env<"u"?U.dist.process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"},Va={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return(t==null?void 0:t.filter(s=>s.chainNamespace===e))||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){var i;if(!e)return;const s=t.find(n=>n.caipNetworkId===e);if(s)return s.name;const[r]=e.split(":");return((i=H.CHAIN_NAME_MAP)==null?void 0:i[r])||void 0}},Nl={bigNumber(t){return t?new T.Big(t):new T.Big(0)},multiply(t,e){if(t===void 0||e===void 0)return new T.Big(0);const s=new T.Big(t),r=new T.Big(e);return s.times(r)},formatNumberToLocalString(t,e=2){return t===void 0?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(t){return t===void 0?0:parseFloat(t.replace(/,/gu,""))}},Al=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],Sl=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],_l=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],Pl={getERC20Abi:t=>H.USDT_CONTRACT_ADDRESSES.includes(t)?_l:Al,getSwapAbi:()=>Sl},Yt={validateCaipAddress(t){var e;if(((e=t.split(":"))==null?void 0:e.length)!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[s,r,i]=e;if(!s||!r||!i)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:r,address:i}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,r]=e;if(!s||!r)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:r}}},se={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections"};function xi(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const ee={setItem(t,e){Ar()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(Ar())return localStorage.getItem(t)||void 0},removeItem(t){Ar()&&localStorage.removeItem(t)},clear(){Ar()&&localStorage.clear()}};function Ar(){return typeof window<"u"&&typeof localStorage<"u"}function ns(t,e){return e==="light"?{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}typeof U.dist.process<"u"&&typeof U.dist.process.env<"u"&&U.dist.process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN;const Ga=[{label:"Coinbase",name:"coinbase",feeRange:"1-2%",url:"",supportedChains:["eip155"]},{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Tl="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",be={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,ONE_SEC_MS:1e3,BALANCE_SUPPORTED_CHAINS:["eip155","solana"],NAMES_SUPPORTED_CHAIN_NAMESPACES:["eip155"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:["eip155","solana"],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["coinbase","meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1},DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal"}},q={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=q.getActiveNamespace(),e=q.getActiveCaipNetworkId(),s=e?e.split(":")[1]:void 0,r=s?isNaN(Number(s))?s:Number(s):void 0;return{namespace:t,caipNetworkId:e,chainId:r}},setWalletConnectDeepLink({name:t,href:e}){try{ee.setItem(se.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=ee.getItem(se.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{ee.removeItem(se.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{ee.setItem(se.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{ee.setItem(se.ACTIVE_CAIP_NETWORK_ID,t),q.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return ee.getItem(se.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{ee.removeItem(se.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=xi(t);ee.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=q.getRecentWallets();e.find(r=>r.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),ee.setItem(se.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=ee.getItem(se.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(t,e){try{const s=xi(t);ee.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return ee.getItem(se.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=xi(t);return ee.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",t)}},setConnectedSocialProvider(t){try{ee.setItem(se.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return ee.getItem(se.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{ee.removeItem(se.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return ee.getItem(se.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var s;const t=ee.getItem(se.ACTIVE_CAIP_NETWORK_ID);return(s=t==null?void 0:t.split(":"))==null?void 0:s[1]},setConnectionStatus(t){try{ee.setItem(se.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return ee.getItem(se.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=ee.getItem(se.CONNECTED_NAMESPACES);return t!=null&&t.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));ee.setItem(se.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=q.getConnectedNamespaces();e.includes(t)||(e.push(t),q.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=q.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),q.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return ee.getItem(se.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{ee.setItem(se.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{ee.removeItem(se.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=ee.getItem(se.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=q.getBalanceCache();ee.setItem(se.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=q.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;q.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=q.getBalanceCache();e[t.caipAddress]=t,ee.setItem(se.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=ee.getItem(se.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=q.getBalanceCache();ee.setItem(se.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const s=q.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),q.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=q.getNativeBalanceCache();e[t.caipAddress]=t,ee.setItem(se.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=ee.getItem(se.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const s=q.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;q.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=q.getEnsCache();e[t.address]=t,ee.setItem(se.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=q.getEnsCache();ee.setItem(se.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=ee.getItem(se.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=q.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;q.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=q.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},ee.setItem(se.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=q.getIdentityCache();ee.setItem(se.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{ee.removeItem(se.PORTFOLIO_CACHE),ee.removeItem(se.NATIVE_BALANCE_CACHE),ee.removeItem(se.ENS_CACHE),ee.removeItem(se.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{ee.setItem(se.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=ee.getItem(se.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s={...q.getConnections(),[e]:t};ee.setItem(se.CONNECTIONS,JSON.stringify(s))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=ee.getItem(se.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}}},Z={isMobile(){var t;return this.isClient()?!!(typeof(window==null?void 0:window.matchMedia)=="function"&&((t=window==null?void 0:window.matchMedia("(pointer:coarse)"))!=null&&t.matches)||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t==null?void 0:t.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return Z.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window==null?void 0:window.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=be.TEN_SEC_MS:!0},isAllowedRetry(t,e=be.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return(window==null?void 0:window.self)!==(window==null?void 0:window.top)}catch{return!1}},isSafeApp(){var t,e;if(Z.isClient()&&window.self!==window.top)try{const s=(e=(t=window==null?void 0:window.location)==null?void 0:t.ancestorOrigins)==null?void 0:e[0],r="https://app.safe.global";if(s){const i=new URL(s),n=new URL(r);return i.hostname===n.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+be.FOUR_MINUTES_MS},getNetworkId(t){return t==null?void 0:t.split(":")[1]},getPlainAddress(t){return t==null?void 0:t.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let s;return(...r)=>{function i(){t(...r)}s&&clearTimeout(s),s=setTimeout(i,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,s=null){if(Z.isHttpUrl(t))return this.formatUniversalUrl(t,e);let r=t,i=s;r.includes("://")||(r=t.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),i&&!(i!=null&&i.endsWith("/"))&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const n=encodeURIComponent(e);return{redirect:`${r}wc?uri=${n}`,redirectUniversalLink:i?`${i}wc?uri=${n}`:void 0,href:r}},formatUniversalUrl(t,e){if(!Z.isHttpUrl(t))return this.formatNativeUrl(t,e);let s=t;s.endsWith("/")||(s=`${s}/`);const r=encodeURIComponent(e);return{redirect:`${s}wc?uri=${r}`,href:s}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?q.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,s){window==null||window.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},returnOpenHref(t,e,s){return window==null?void 0:window.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){var s,r,i;if(typeof window>"u")return!1;const t=(r=(s=window.matchMedia)==null?void 0:s.call(window,"(display-mode: standalone)"))==null?void 0:r.matches,e=(i=window==null?void 0:window.navigator)==null?void 0:i.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((s,r)=>{const i=new Image;i.onload=s,i.onerror=r,i.crossOrigin="anonymous",i.src=t});return Promise.race([e,Z.wait(2e3)])},formatBalance(t,e){let s="0.000";if(typeof t=="string"){const r=Number(t);if(r){const i=Math.floor(r*1e3)/1e3;i&&(s=i.toString())}}return`${s}${e?` ${e}`:""}`},formatBalance2(t,e){var r;let s;if(t==="0")s="0";else if(typeof t=="string"){const i=Number(t);i&&(s=(r=i.toString().match(/^-?\d+(?:\.\d{0,3})?/u))==null?void 0:r[0])}return{value:s??"0",rest:s==="0"?"000":"",symbol:e}},getApiUrl(){return H.W3M_API_URL},getBlockchainApiUrl(){return H.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return H.PULSE_API_URL},getUUID(){return crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){var e,s;return typeof t=="string"?t:typeof((s=(e=t==null?void 0:t.issues)==null?void 0:e[0])==null?void 0:s.message)=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const s={};return e&&t&&(t.forEach((r,i)=>{s[r]=i}),e.sort((r,i)=>{const n=s[r.id],o=s[i.id];return n!==void 0&&o!==void 0?n-o:n!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const s of t)e+=s.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[s,r]=e.split(".");return{dollars:s,pennies:r}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const s=new Set;return t.filter(r=>{const i=r[e];return s.has(i)?!1:(s.add(i),!0)})},generateSdkVersion(t,e,s){const i=t.length===0?be.ADAPTER_TYPES.UNIVERSAL:t.map(n=>n.adapterType).join(",");return`${e}-${i}-${s}`},createAccount(t,e,s,r,i){return{namespace:t,address:e,type:s,publicKey:r,path:i}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),s=e[0];return e.filter(Boolean).length===3&&s in H.CHAIN_NAME_MAP},isMac(){const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window==null?void 0:window.location.href)}`,s="state=";if(new URL(t).host==="auth.magic.link"){const i="provider_authorization_url=",n=t.substring(t.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(n),s,e);return t.replace(n,encodeURIComponent(o))}return this.injectIntoUrl(t,s,e)},injectIntoUrl(t,e,s){const r=t.indexOf(e);if(r===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const i=t.indexOf("&",r),n=e.length,o=i!==-1?i:t.length,a=t.substring(0,r+n),c=t.substring(r+n,o),l=t.substring(i),u=c+s;return a+u+l}};async function wr(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class zr{constructor({baseUrl:e,clientId:s}){this.baseUrl=e,this.clientId=s}async get({headers:e,signal:s,cache:r,...i}){const n=this.createUrl(i);return(await wr(n,{method:"GET",headers:e,signal:s,cache:r})).json()}async getBlob({headers:e,signal:s,...r}){const i=this.createUrl(r);return(await wr(i,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await wr(n,{method:"POST",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}async put({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await wr(n,{method:"PUT",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}async delete({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await wr(n,{method:"DELETE",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}createUrl({path:e,params:s}){const r=new URL(e,this.baseUrl);return s&&Object.entries(s).forEach(([i,n])=>{n&&r.searchParams.append(i,n)}),this.clientId&&r.searchParams.append("clientId",this.clientId),r}}const Ol={getFeatureValue(t,e){const s=e==null?void 0:e[t];return s===void 0?be.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(Z.isTelegram()){if(Z.isIos())return t.filter(e=>e!=="google");if(Z.isMac())return t.filter(e=>e!=="x");if(Z.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t}},V=T.proxy({features:be.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:be.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),A={state:V,subscribeKey(t,e){return T.subscribeKey(V,t,e)},setOptions(t){Object.assign(V,t)},setRemoteFeatures(t){var s;if(!t)return;const e={...V.remoteFeatures,...t};V.remoteFeatures=e,(s=V.remoteFeatures)!=null&&s.socials&&(V.remoteFeatures.socials=Ol.filterSocialsByPlatform(V.remoteFeatures.socials))},setFeatures(t){if(!t)return;V.features||(V.features=be.DEFAULT_FEATURES);const e={...V.features,...t};V.features=e},setProjectId(t){V.projectId=t},setCustomRpcUrls(t){V.customRpcUrls=t},setAllWallets(t){V.allWallets=t},setIncludeWalletIds(t){V.includeWalletIds=t},setExcludeWalletIds(t){V.excludeWalletIds=t},setFeaturedWalletIds(t){V.featuredWalletIds=t},setTokens(t){V.tokens=t},setTermsConditionsUrl(t){V.termsConditionsUrl=t},setPrivacyPolicyUrl(t){V.privacyPolicyUrl=t},setCustomWallets(t){V.customWallets=t},setIsSiweEnabled(t){V.isSiweEnabled=t},setIsUniversalProvider(t){V.isUniversalProvider=t},setSdkVersion(t){V.sdkVersion=t},setMetadata(t){V.metadata=t},setDisableAppend(t){V.disableAppend=t},setEIP6963Enabled(t){V.enableEIP6963=t},setDebug(t){V.debug=t},setEnableWalletConnect(t){V.enableWalletConnect=t},setEnableWalletGuide(t){V.enableWalletGuide=t},setEnableAuthLogger(t){V.enableAuthLogger=t},setEnableWallets(t){V.enableWallets=t},setPreferUniversalLinks(t){V.experimental_preferUniversalLinks=t},setHasMultipleAddresses(t){V.hasMultipleAddresses=t},setSIWX(t){V.siwx=t},setConnectMethodsOrder(t){V.features={...V.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){V.features={...V.features,walletFeaturesOrder:t}},setSocialsOrder(t){V.remoteFeatures={...V.remoteFeatures,socials:t}},setCollapseWallets(t){V.features={...V.features,collapseWallets:t}},setEnableEmbedded(t){V.enableEmbedded=t},setAllowUnsupportedChain(t){V.allowUnsupportedChain=t},setManualWCControl(t){V.manualWCControl=t},setEnableNetworkSwitch(t){V.enableNetworkSwitch=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(V.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){V.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return V.universalProviderConfigOverride},getSnapshot(){return T.snapshot(V)}},kl=Object.freeze({enabled:!0,events:[]}),xl=new zr({baseUrl:Z.getAnalyticsUrl(),clientId:null}),Rl=5,$l=60*1e3,Xt=T.proxy({...kl}),Ul={state:Xt,subscribeKey(t,e){return T.subscribeKey(Xt,t,e)},async sendError(t,e){if(!Xt.enabled)return;const s=Date.now();if(Xt.events.filter(n=>{const o=new Date(n.properties.timestamp||"").getTime();return s-o<$l}).length>=Rl)return;const i={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};Xt.events.push(i);try{if(typeof window>"u")return;const{projectId:n,sdkType:o,sdkVersion:a}=A.state;await xl.post({path:"/e",params:{projectId:n,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:Z.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){Xt.enabled=!0},disable(){Xt.enabled=!1},clearEvents(){Xt.events=[]}};class rr extends Error{constructor(e,s,r){super(e),this.name="AppKitError",this.category=s,this.originalError=r,Object.setPrototypeOf(this,rr.prototype);let i=!1;if(r instanceof Error&&typeof r.stack=="string"&&r.stack){const n=r.stack,o=n.indexOf(`
2
- `);if(o>-1){const a=n.substring(o+1);this.stack=`${this.name}: ${this.message}
3
- ${a}`,i=!0}}i||(Error.captureStackTrace?Error.captureStackTrace(this,rr):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function eo(t,e){const s=t instanceof rr?t:new rr(t instanceof Error?t.message:String(t),e,t);throw Ul.sendError(s,s.category),s}function at(t,e="INTERNAL_SDK_ERROR"){const s={};return Object.keys(t).forEach(r=>{const i=t[r];if(typeof i=="function"){let n=i;i.constructor.name==="AsyncFunction"?n=async(...o)=>{try{return await i(...o)}catch(a){return eo(a,e)}}:n=(...o)=>{try{return i(...o)}catch(a){return eo(a,e)}},s[r]=n}else s[r]=i}),s}const Rt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},Dl={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,r=encodeURIComponent(s);if(t===Rt.PHANTOM.id&&!("phantom"in window)){const i=s.startsWith("https")?"https":"http",n=s.split("/")[2],o=encodeURIComponent(`${i}://${n}`);window.location.href=`${Rt.PHANTOM.url}/ul/browse/${r}?ref=${o}`}t===Rt.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Rt.SOLFLARE.url}/ul/v1/browse/${r}?ref=${r}`),e===H.CHAIN.SOLANA&&t===Rt.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Rt.COINBASE.url}/dapp?cb_url=${r}`)}},ct=T.proxy({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Ll={state:ct,subscribeNetworkImages(t){return T.subscribe(ct.networkImages,()=>t(ct.networkImages))},subscribeKey(t,e){return T.subscribeKey(ct,t,e)},subscribe(t){return T.subscribe(ct,()=>t(ct))},setWalletImage(t,e){ct.walletImages[t]=e},setNetworkImage(t,e){ct.networkImages[t]=e},setChainImage(t,e){ct.chainImages[t]=e},setConnectorImage(t,e){ct.connectorImages={...ct.connectorImages,[t]:e}},setTokenImage(t,e){ct.tokenImages[t]=e},setCurrencyImage(t,e){ct.currencyImages[t]=e}},vt=at(Ll),Fl={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:""},Ri=T.proxy({networkImagePromises:{}}),Mn={async fetchWalletImage(t){if(t)return await K._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(Ri.networkImagePromises[t]||(Ri.networkImagePromises[t]=K._fetchNetworkImage(t)),await Ri.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return vt.state.walletImages[t]},getWalletImage(t){if(t!=null&&t.image_url)return t==null?void 0:t.image_url;if(t!=null&&t.image_id)return vt.state.walletImages[t.image_id]},getNetworkImage(t){var e,s,r;if((e=t==null?void 0:t.assets)!=null&&e.imageUrl)return(s=t==null?void 0:t.assets)==null?void 0:s.imageUrl;if((r=t==null?void 0:t.assets)!=null&&r.imageId)return vt.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return vt.state.networkImages[t]},getConnectorImage(t){if(t!=null&&t.imageUrl)return t.imageUrl;if(t!=null&&t.imageId)return vt.state.connectorImages[t.imageId]},getChainImage(t){return vt.state.networkImages[Fl[t]]}},Zt=T.proxy({message:"",variant:"info",open:!1}),Bl={state:Zt,subscribeKey(t,e){return T.subscribeKey(Zt,t,e)},open(t,e){const{debug:s}=A.state,{shortMessage:r,longMessage:i}=t;s&&(Zt.message=r,Zt.variant=e,Zt.open=!0),i&&console.error(typeof i=="function"?i():i)},close(){Zt.open=!1,Zt.message="",Zt.variant="info"}},rs=at(Bl),Ml=Z.getAnalyticsUrl(),jl=new zr({baseUrl:Ml,clientId:null}),ql=["MODAL_CREATED"],jt=T.proxy({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),_e={state:jt,subscribe(t){return T.subscribe(jt,()=>t(jt))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=A.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(t){try{const e=W.state.address;if(ql.includes(t.data.event)||typeof window>"u")return;await jl.post({path:"/e",params:_e.getSdkProperties(),body:{eventId:Z.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e}}}),jt.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===H.HTTP_STATUS_CODES.FORBIDDEN&&!jt.reportedErrors.FORBIDDEN&&(rs.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${Ar()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),jt.reportedErrors.FORBIDDEN=!0)}},sendEvent(t){var e;jt.timestamp=Date.now(),jt.data=t,(e=A.state.features)!=null&&e.analytics&&_e._sendAnalyticsEvent(jt)}},Wl=Z.getApiUrl(),Qe=new zr({baseUrl:Wl,clientId:null}),zl=40,to=4,Hl=20,re=T.proxy({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),K={state:re,subscribeKey(t,e){return T.subscribeKey(re,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=A.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return A.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${Qe.baseUrl}/getWalletImage/${t}`,s=await Qe.getBlob({path:e,params:K._getSdkProperties()});vt.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${Qe.baseUrl}/public/getAssetImage/${t}`,s=await Qe.getBlob({path:e,params:K._getSdkProperties()});vt.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${Qe.baseUrl}/public/getAssetImage/${t}`,s=await Qe.getBlob({path:e,params:K._getSdkProperties()});vt.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${Qe.baseUrl}/public/getCurrencyImage/${t}`,s=await Qe.getBlob({path:e,params:K._getSdkProperties()});vt.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${Qe.baseUrl}/public/getTokenImage/${t}`,s=await Qe.getBlob({path:e,params:K._getSdkProperties()});vt.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){return Z.isMobile()?t==null?void 0:t.filter(s=>s.mobile_link||s.id===Rt.COINBASE.id?!0:p.state.activeChain==="solana"&&(s.id===Rt.SOLFLARE.id||s.id===Rt.PHANTOM.id)):t},async fetchProjectConfig(){return(await Qe.get({path:"/appkit/v1/config",params:K._getSdkProperties()})).features},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await Qe.get({path:"/projects/v1/origins",params:K._getSdkProperties()});return t}catch{return[]}},async fetchNetworkImages(){const t=p.getAllRequestedCaipNetworks(),e=t==null?void 0:t.map(({assets:s})=>s==null?void 0:s.imageId).filter(Boolean).filter(s=>!Mn.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>K._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=B.state,e=t.map(({imageId:s})=>s).filter(Boolean);await Promise.allSettled(e.map(s=>K._fetchConnectorImage(s)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>K._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>K._fetchTokenImage(e)))},async fetchWallets(t){var n;const e=t.exclude??[];K._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Rt).map(o=>o.id));const r=await Qe.get({path:"/getWallets",params:{...K._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:(n=t.include)==null?void 0:n.join(","),exclude:e.join(",")}});return{data:K._filterWalletsByPlatform(r==null?void 0:r.data)||[],count:r==null?void 0:r.count}},async fetchFeaturedWallets(){const{featuredWalletIds:t}=A.state;if(t!=null&&t.length){const e={...K._getSdkProperties(),page:1,entries:(t==null?void 0:t.length)??to,include:t},{data:s}=await K.fetchWallets(e),r=[...s].sort((n,o)=>t.indexOf(n.id)-t.indexOf(o.id)),i=r.map(n=>n.image_id).filter(Boolean);await Promise.allSettled(i.map(n=>K._fetchWalletImage(n))),re.featured=r,re.allFeatured=r}},async fetchRecommendedWallets(){try{re.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:s}=A.state,r=[...e??[],...s??[]].filter(Boolean),i=p.getRequestedCaipNetworkIds().join(","),n={page:1,entries:to,include:t,exclude:r,chains:i},{data:o,count:a}=await K.fetchWallets(n),c=q.getRecentWallets(),l=o.map(d=>d.image_id).filter(Boolean),u=c.map(d=>d.image_id).filter(Boolean);await Promise.allSettled([...l,...u].map(d=>K._fetchWalletImage(d))),re.recommended=o,re.allRecommended=o,re.count=a??0}catch{}finally{re.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:s,featuredWalletIds:r}=A.state,i=p.getRequestedCaipNetworkIds().join(","),n=[...re.recommended.map(({id:u})=>u),...s??[],...r??[]].filter(Boolean),o={page:t,entries:zl,include:e,exclude:n,chains:i},{data:a,count:c}=await K.fetchWallets(o),l=a.slice(0,Hl).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(l.map(u=>K._fetchWalletImage(u))),re.wallets=Z.uniqueBy([...re.wallets,...K._filterOutExtensions(a)],"id").filter(u=>{var d;return(d=u.chains)==null?void 0:d.some(g=>i.includes(g))}),re.count=c>re.count?c:re.count,re.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:s}=await K.fetchWallets(e);s&&s.forEach(r=>{re.excludedWallets.push({rdns:r.rdns,name:r.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:s,excludeWalletIds:r}=A.state,i=p.getRequestedCaipNetworkIds().join(",");re.search=[];const n={page:1,entries:100,search:t==null?void 0:t.trim(),badge_type:e,include:s,exclude:r,chains:i},{data:o}=await K.fetchWallets(n);_e.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:t??""}});const a=o.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>K._fetchWalletImage(c)),Z.wait(300)]),re.search=K._filterOutExtensions(o)},initPromise(t,e){const s=re.promises[t];return s||(re.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:r=!0}={}){const i=[t&&K.initPromise("connectorImages",K.fetchConnectorImages),e&&K.initPromise("featuredWallets",K.fetchFeaturedWallets),s&&K.initPromise("recommendedWallets",K.fetchRecommendedWallets),r&&K.initPromise("networkImages",K.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){var t;(t=A.state.features)!=null&&t.analytics&&K.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await Qe.get({path:"/getAnalyticsConfig",params:K._getSdkProperties()});A.setFeatures({analytics:t})}catch{A.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!(t!=null&&t.length)){re.featured=re.allFeatured,re.recommended=re.allRecommended;return}const e=p.getRequestedCaipNetworkIds().join(",");re.featured=re.allFeatured.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))}),re.recommended=re.allRecommended.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))}),re.filteredWallets=re.wallets.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))})},clearFilterByNamespaces(){re.filteredWallets=[]},setFilterByNamespace(t){if(!t){re.featured=re.allFeatured,re.recommended=re.allRecommended;return}const e=p.getRequestedCaipNetworkIds().join(",");re.featured=re.allFeatured.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))}),re.recommended=re.allRecommended.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))}),re.filteredWallets=re.wallets.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))})}},we=T.proxy({view:"Connect",history:["Connect"],transactionStack:[]}),Kl={state:we,subscribeKey(t,e){return T.subscribeKey(we,t,e)},pushTransactionStack(t){we.transactionStack.push(t)},popTransactionStack(t){const e=we.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:r,onCancel:i}=e;switch(t){case"success":s==null||s();break;case"error":r==null||r(),ne.goBack();break;case"cancel":i==null||i(),ne.goBack();break}},push(t,e){t!==we.view&&(we.view=t,we.history.push(t),we.data=e)},reset(t,e){we.view=t,we.history=[t],we.data=e},replace(t,e){we.history.at(-1)===t||(we.view=t,we.history[we.history.length-1]=t,we.data=e)},goBack(){var r;const t=p.state.activeCaipAddress,e=ne.state.view==="ConnectingFarcaster",s=!t&&e;if(we.history.length>1){we.history.pop();const[i]=we.history.slice(-1);i&&(t&&i==="Connect"?we.view="Account":we.view=i)}else Le.close();(r=we.data)!=null&&r.wallet&&(we.data.wallet=void 0),setTimeout(()=>{var i,n,o;if(s){W.setFarcasterUrl(void 0,p.state.activeChain);const a=B.getAuthConnector();(i=a==null?void 0:a.provider)==null||i.reload();const c=T.snapshot(A.state);(o=(n=a==null?void 0:a.provider)==null?void 0:n.syncDappData)==null||o.call(n,{metadata:c.metadata,sdkVersion:c.sdkVersion,projectId:c.projectId,sdkType:c.sdkType})}},100)},goBackToIndex(t){if(we.history.length>1){we.history=we.history.slice(0,t+1);const[e]=we.history.slice(-1);e&&(we.view=e)}},goBackOrCloseModal(){ne.state.history.length>1?ne.goBack():Le.close()}},ne=at(Kl),qt=T.proxy({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),an={state:qt,subscribe(t){return T.subscribe(qt,()=>t(qt))},setThemeMode(t){qt.themeMode=t;try{const e=B.getAuthConnector();if(e){const s=an.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:ns(s,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){qt.themeVariables={...qt.themeVariables,...t};try{const e=B.getAuthConnector();if(e){const s=an.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:ns(qt.themeVariables,qt.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return T.snapshot(qt)}},nt=at(an),Ja={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},le=T.proxy({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...Ja},filterByNamespaceMap:{eip155:!0,solana:!0,polkadot:!0,bip122:!0,cosmos:!0}}),Vl={state:le,subscribe(t){return T.subscribe(le,()=>{t(le)})},subscribeKey(t,e){return T.subscribeKey(le,t,e)},initialize(t){t.forEach(e=>{const s=q.getConnectedConnectorId(e);s&&B.setConnectorId(s,e)})},setActiveConnector(t){t&&(le.activeConnector=T.ref(t))},setConnectors(t){t.filter(i=>!le.allConnectors.some(n=>n.id===i.id&&B.getConnectorName(n.name)===B.getConnectorName(i.name)&&n.chain===i.chain)).forEach(i=>{i.type!=="MULTI_CHAIN"&&le.allConnectors.push(T.ref(i))});const s=B.getEnabledNamespaces(),r=B.getEnabledConnectors(s);le.connectors=B.mergeMultiChainConnectors(r)},filterByNamespaces(t){Object.keys(le.filterByNamespaceMap).forEach(e=>{le.filterByNamespaceMap[e]=!1}),t.forEach(e=>{le.filterByNamespaceMap[e]=!0}),B.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){le.filterByNamespaceMap[t]=e,B.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=B.getEnabledNamespaces(),e=B.getEnabledConnectors(t),s=B.areAllNamespacesEnabled();le.connectors=B.mergeMultiChainConnectors(e),s?K.clearFilterByNamespaces():K.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(le.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return le.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(le.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=B.generateConnectorMapByName(t),s=[];return e.forEach(r=>{const i=r[0],n=(i==null?void 0:i.id)===H.CONNECTOR_ID.AUTH;r.length>1&&i?s.push({name:i.name,imageUrl:i.imageUrl,imageId:i.imageId,connectors:[...r],type:n?"AUTH":"MULTI_CHAIN",chain:"eip155",id:(i==null?void 0:i.id)||""}):i&&s.push(i)}),s},generateConnectorMapByName(t){const e=new Map;return t.forEach(s=>{const{name:r}=s,i=B.getConnectorName(r);if(!i)return;const n=e.get(i)||[];n.find(a=>a.chain===s.chain)||n.push(s),e.set(i,n)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(s=>{e.find(r=>r.chain===s.chain)||e.push(s)}),e},addConnector(t){var e,s,r;if(t.id===H.CONNECTOR_ID.AUTH){const i=t,n=T.snapshot(A.state),o=nt.getSnapshot().themeMode,a=nt.getSnapshot().themeVariables;(s=(e=i==null?void 0:i.provider)==null?void 0:e.syncDappData)==null||s.call(e,{metadata:n.metadata,sdkVersion:n.sdkVersion,projectId:n.projectId,sdkType:n.sdkType}),(r=i==null?void 0:i.provider)==null||r.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:ns(a,o)}),B.setConnectors([t])}else B.setConnectors([t])},getAuthConnector(t){var r;const e=t||p.state.activeChain,s=le.connectors.find(i=>i.id===H.CONNECTOR_ID.AUTH);if(s)return(r=s==null?void 0:s.connectors)!=null&&r.length?s.connectors.find(n=>n.chain===e):s},getAnnouncedConnectorRdns(){return le.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>{var e;return(e=t.info)==null?void 0:e.rdns})},getConnectorById(t){return le.allConnectors.find(e=>e.id===t)},getConnector(t,e){return le.allConnectors.filter(r=>r.chain===p.state.activeChain).find(r=>{var i;return r.explorerId===t||((i=r.info)==null?void 0:i.rdns)===e})},syncIfAuthConnector(t){var n,o;if(t.id!=="ID_AUTH")return;const e=t,s=T.snapshot(A.state),r=nt.getSnapshot().themeMode,i=nt.getSnapshot().themeVariables;(o=(n=e==null?void 0:e.provider)==null?void 0:n.syncDappData)==null||o.call(n,{metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:r,themeVariables:i,w3mThemeVariables:ns(i,r)})},getConnectorsByNamespace(t){const e=le.allConnectors.filter(s=>s.chain===t);return B.mergeMultiChainConnectors(e)},selectWalletConnector(t){const e=B.getConnector(t.id,t.rdns),s=p.state.activeChain;Dl.handleMobileDeeplinkRedirect((e==null?void 0:e.explorerId)||t.id,s),e?ne.push("ConnectingExternal",{connector:e}):ne.push("ConnectingWalletConnect",{wallet:t})},getConnectors(t){return t?B.getConnectorsByNamespace(t):B.mergeMultiChainConnectors(le.allConnectors)},setFilterByNamespace(t){le.filterByNamespace=t,le.connectors=B.getConnectors(t),K.setFilterByNamespace(t)},setConnectorId(t,e){t&&(le.activeConnectorIds={...le.activeConnectorIds,[e]:t},q.setConnectedConnectorId(e,t))},removeConnectorId(t){le.activeConnectorIds={...le.activeConnectorIds,[t]:void 0},q.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return le.activeConnectorIds[t]},isConnected(t){return t?!!le.activeConnectorIds[t]:Object.values(le.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){le.activeConnectorIds={...Ja}}},B=at(Vl),Gl="https://secure.walletconnect.org/sdk";typeof U.dist.process<"u"&&typeof U.dist.process.env<"u"&&U.dist.process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL;typeof U.dist.process<"u"&&typeof U.dist.process.env<"u"&&U.dist.process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL;typeof U.dist.process<"u"&&typeof U.dist.process.env<"u"&&U.dist.process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const Or={ACCOUNT_TYPES:{SMART_ACCOUNT:"smartAccount"}},ys=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),Ue=T.proxy({...ys}),Jl={state:Ue,subscribeKey(t,e){return T.subscribeKey(Ue,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=Z.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){Ue.message=ys.message,Ue.variant=ys.variant,Ue.svg=ys.svg,Ue.open=ys.open,Ue.autoClose=ys.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:r=ys.autoClose}){Ue.open?(Ue.open=!1,setTimeout(()=>{Ue.message=t,Ue.variant=s,Ue.svg=e,Ue.open=!0,Ue.autoClose=r},150)):(Ue.message=t,Ue.variant=s,Ue.svg=e,Ue.open=!0,Ue.autoClose=r)}},Et=Jl,Ne=T.proxy({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Yl={state:Ne,subscribe(t){return T.subscribe(Ne,()=>t(Ne))},setLastNetworkInView(t){Ne.lastNetworkInView=t},async fetchTransactions(t,e){var s,r;if(!t)throw new Error("Transactions can't be fetched without an accountAddress");Ne.loading=!0;try{const i=await X.fetchTransactions({account:t,cursor:Ne.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:(s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId}),n=Sr.filterSpamTransactions(i.data),o=Sr.filterByConnectedChain(n),a=[...Ne.transactions,...o];Ne.loading=!1,e==="coinbase"?Ne.coinbaseTransactions=Sr.groupTransactionsByYearAndMonth(Ne.coinbaseTransactions,i.data):(Ne.transactions=a,Ne.transactionsByYear=Sr.groupTransactionsByYearAndMonth(Ne.transactionsByYear,o)),Ne.empty=a.length===0,Ne.next=i.next?i.next:void 0}catch{const n=p.state.activeChain;_e.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:A.state.projectId,cursor:Ne.next,isSmartAccount:((r=W.state.preferredAccountTypes)==null?void 0:r[n])===Or.ACCOUNT_TYPES.SMART_ACCOUNT}}),Et.showError("Failed to fetch transactions"),Ne.loading=!1,Ne.empty=!0,Ne.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const s=t;return e.forEach(r=>{const i=new Date(r.metadata.minedAt).getFullYear(),n=new Date(r.metadata.minedAt).getMonth(),o=s[i]??{},c=(o[n]??[]).filter(l=>l.id!==r.id);s[i]={...o,[n]:[...c,r].sort((l,u)=>new Date(u.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),s},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(r=>{var i;return((i=r.nft_info)==null?void 0:i.flags.is_spam)===!0}))},filterByConnectedChain(t){var r;const e=(r=p.state.activeCaipNetwork)==null?void 0:r.caipNetworkId;return t.filter(i=>i.metadata.chain===e)},clearCursor(){Ne.next=void 0},resetTransactions(){Ne.transactions=[],Ne.transactionsByYear={},Ne.lastNetworkInView=void 0,Ne.loading=!1,Ne.empty=!1,Ne.next=void 0}},Sr=at(Yl,"API_ERROR"),ve=T.proxy({connections:new Map,wcError:!1,buffering:!1,status:"disconnected"});let fs;const Xl={state:ve,subscribeKey(t,e){return T.subscribeKey(ve,t,e)},_getClient(){return ve._client},setClient(t){ve._client=T.ref(t)},async connectWalletConnect(){var t,e,s,r;if(Z.isTelegram()||Z.isSafari()&&Z.isIos()){if(fs){await fs,fs=void 0;return}if(!Z.isPairingExpired(ve==null?void 0:ve.wcPairingExpiry)){const i=ve.wcUri;ve.wcUri=i;return}fs=(e=(t=J._getClient())==null?void 0:t.connectWalletConnect)==null?void 0:e.call(t).catch(()=>{}),J.state.status="connecting",await fs,fs=void 0,ve.wcPairingExpiry=void 0,J.state.status="connected"}else await((r=(s=J._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:r.call(s))},async connectExternal(t,e,s=!0){var r,i;await((i=(r=J._getClient())==null?void 0:r.connectExternal)==null?void 0:i.call(r,t)),s&&p.setActiveNamespace(e)},async reconnectExternal(t){var s,r;await((r=(s=J._getClient())==null?void 0:s.reconnectExternal)==null?void 0:r.call(s,t));const e=t.chain||p.state.activeChain;e&&B.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){var r;Le.setLoading(!0,p.state.activeChain);const s=B.getAuthConnector();s&&(W.setPreferredAccountType(t,e),await s.provider.setPreferredAccount(t),q.setPreferredAccountTypes(W.state.preferredAccountTypes??{[e]:t}),await J.reconnectExternal(s),Le.setLoading(!1,p.state.activeChain),_e.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:((r=p.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||""}}))},async signMessage(t){var e;return(e=J._getClient())==null?void 0:e.signMessage(t)},parseUnits(t,e){var s;return(s=J._getClient())==null?void 0:s.parseUnits(t,e)},formatUnits(t,e){var s;return(s=J._getClient())==null?void 0:s.formatUnits(t,e)},async sendTransaction(t){var e;return(e=J._getClient())==null?void 0:e.sendTransaction(t)},async getCapabilities(t){var e;return(e=J._getClient())==null?void 0:e.getCapabilities(t)},async grantPermissions(t){var e;return(e=J._getClient())==null?void 0:e.grantPermissions(t)},async walletGetAssets(t){var e;return((e=J._getClient())==null?void 0:e.walletGetAssets(t))??{}},async estimateGas(t){var e;return(e=J._getClient())==null?void 0:e.estimateGas(t)},async writeContract(t){var e;return(e=J._getClient())==null?void 0:e.writeContract(t)},async getEnsAddress(t){var e;return(e=J._getClient())==null?void 0:e.getEnsAddress(t)},async getEnsAvatar(t){var e;return(e=J._getClient())==null?void 0:e.getEnsAvatar(t)},checkInstalled(t){var e,s;return((s=(e=J._getClient())==null?void 0:e.checkInstalled)==null?void 0:s.call(e,t))||!1},resetWcConnection(){ve.wcUri=void 0,ve.wcPairingExpiry=void 0,ve.wcLinking=void 0,ve.recentWallet=void 0,ve.status="disconnected",Sr.resetTransactions(),q.deleteWalletConnectDeepLink()},resetUri(){ve.wcUri=void 0,ve.wcPairingExpiry=void 0,fs=void 0},finalizeWcConnection(){var s,r;const{wcLinking:t,recentWallet:e}=J.state;t&&q.setWalletConnectDeepLink(t),e&&q.setAppKitRecent(e),_e.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:t?"mobile":"qrcode",name:((r=(s=ne.state.data)==null?void 0:s.wallet)==null?void 0:r.name)||"Unknown"}})},setWcBasic(t){ve.wcBasic=t},setUri(t){ve.wcUri=t,ve.wcPairingExpiry=Z.getPairingExpiry()},setWcLinking(t){ve.wcLinking=t},setWcError(t){ve.wcError=t,ve.buffering=!1},setRecentWallet(t){ve.recentWallet=t},setBuffering(t){ve.buffering=t},setStatus(t){ve.status=t},async disconnect(t){var e;try{await((e=J._getClient())==null?void 0:e.disconnect(t))}catch(s){throw new rr("Failed to disconnect","INTERNAL_SDK_ERROR",s)}},setConnections(t,e){ve.connections.set(e,t)},switchAccount({connection:t,address:e,namespace:s}){if(B.state.activeConnectorIds[s]===t.connectorId){const n=p.state.activeCaipNetwork;if(n){const o=`${s}:${n.id}:${e}`;W.setCaipAddress(o,s)}else console.warn(`No current network found for namespace "${s}"`)}else{const n=B.getConnector(t.connectorId);n?J.connectExternal(n,s):console.warn(`No connector found for namespace "${s}"`)}}},J=at(Xl),xs=T.proxy({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),as={state:xs,subscribe(t){return T.subscribe(xs,()=>t(xs))},subscribeOpen(t){return T.subscribeKey(xs,"open",t)},set(t){Object.assign(xs,{...xs,...t})}},$i={createBalance(t,e){const s={name:t.metadata.name||"",symbol:t.metadata.symbol||"",decimals:t.metadata.decimals||0,value:t.metadata.value||0,price:t.metadata.price||0,iconUrl:t.metadata.iconUrl||""};return{name:s.name,symbol:s.symbol,chainId:e,address:t.address==="native"?void 0:this.convertAddressToCAIP10Address(t.address,e),value:s.value,price:s.price,quantity:{decimals:s.decimals.toString(),numeric:this.convertHexToBalance({hex:t.balance,decimals:s.decimals})},iconUrl:s.iconUrl}},convertHexToBalance({hex:t,decimals:e}){return Is.formatUnits(BigInt(t),e)},convertAddressToCAIP10Address(t,e){return`${e}:${t}`},createCAIP2ChainId(t,e){return`${e}:${parseInt(t,16)}`},getChainIdHexFromCAIP2ChainId(t){const e=t.split(":");if(e.length<2||!e[1])return"0x0";const s=e[1],r=parseInt(s,10);return isNaN(r)?"0x0":`0x${r.toString(16)}`},isWalletGetAssetsResponse(t){return typeof t!="object"||t===null?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(s=>this.isValidAsset(s)))},isValidAsset(t){return typeof t=="object"&&t!==null&&typeof t.address=="string"&&typeof t.balance=="string"&&(t.type==="ERC20"||t.type==="NATIVE")&&typeof t.metadata=="object"&&t.metadata!==null&&typeof t.metadata.name=="string"&&typeof t.metadata.symbol=="string"&&typeof t.metadata.decimals=="number"&&typeof t.metadata.price=="number"&&typeof t.metadata.iconUrl=="string"}},so={async getMyTokensWithBalance(t){const e=W.state.address,s=p.state.activeCaipNetwork;if(!e||!s)return[];if(s.chainNamespace==="eip155"){const i=await this.getEIP155Balances(e,s);if(i)return this.filterLowQualityTokens(i)}const r=await X.getBalance(e,s.caipNetworkId,t);return this.filterLowQualityTokens(r.balances)},async getEIP155Balances(t,e){var s,r;try{const i=$i.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),n=await J.getCapabilities(t);if(!((r=(s=n==null?void 0:n[i])==null?void 0:s.assetDiscovery)!=null&&r.supported))return null;const o=await J.walletGetAssets({account:t,chainFilter:[i]});return $i.isWalletGetAssetsResponse(o)?(o[i]||[]).map(c=>$i.createBalance(c,e.caipNetworkId)):null}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},mapBalancesToSwapTokens(t){return(t==null?void 0:t.map(e=>({...e,address:e!=null&&e.address?e.address:p.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]}},me=T.proxy({tokenBalances:[],loading:!1}),Zl={state:me,subscribe(t){return T.subscribe(me,()=>t(me))},subscribeKey(t,e){return T.subscribeKey(me,t,e)},setToken(t){t&&(me.token=T.ref(t))},setTokenAmount(t){me.sendTokenAmount=t},setReceiverAddress(t){me.receiverAddress=t},setReceiverProfileImageUrl(t){me.receiverProfileImageUrl=t},setReceiverProfileName(t){me.receiverProfileName=t},setNetworkBalanceInUsd(t){me.networkBalanceInUSD=t},setLoading(t){me.loading=t},async sendToken(){var t;try{switch(pe.setLoading(!0),(t=p.state.activeCaipNetwork)==null?void 0:t.chainNamespace){case"eip155":await pe.sendEvmToken();return;case"solana":await pe.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}finally{pe.setLoading(!1)}},async sendEvmToken(){var s,r,i,n;const t=p.state.activeChain,e=(s=W.state.preferredAccountTypes)==null?void 0:s[t];if(!pe.state.sendTokenAmount||!pe.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!pe.state.token)throw new Error("A token is required");(r=pe.state.token)!=null&&r.address?(_e.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Or.ACCOUNT_TYPES.SMART_ACCOUNT,token:pe.state.token.address,amount:pe.state.sendTokenAmount,network:((i=p.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||""}}),await pe.sendERC20Token({receiverAddress:pe.state.receiverAddress,tokenAddress:pe.state.token.address,sendTokenAmount:pe.state.sendTokenAmount,decimals:pe.state.token.quantity.decimals})):(_e.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Or.ACCOUNT_TYPES.SMART_ACCOUNT,token:pe.state.token.symbol||"",amount:pe.state.sendTokenAmount,network:((n=p.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}}),await pe.sendNativeToken({receiverAddress:pe.state.receiverAddress,sendTokenAmount:pe.state.sendTokenAmount,decimals:pe.state.token.quantity.decimals}))},async fetchTokenBalance(t){var n,o;me.loading=!0;const e=(n=p.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,s=(o=p.state.activeCaipNetwork)==null?void 0:o.chainNamespace,r=p.state.activeCaipAddress,i=r?Z.getPlainAddress(r):void 0;if(me.lastRetry&&!Z.isAllowedRetry(me.lastRetry,30*be.ONE_SEC_MS))return me.loading=!1,[];try{if(i&&e&&s){const a=await so.getMyTokensWithBalance();return me.tokenBalances=a,me.lastRetry=void 0,a}}catch(a){me.lastRetry=Date.now(),t==null||t(a),Et.showError("Token Balance Unavailable")}finally{me.loading=!1}return[]},fetchNetworkBalance(){if(me.tokenBalances.length===0)return;const t=so.mapBalancesToSwapTokens(me.tokenBalances);if(!t)return;const e=t.find(s=>s.address===p.getActiveNetworkTokenAddress());e&&(me.networkBalanceInUSD=e?Nl.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){var n,o,a,c;ne.pushTransactionStack({});const e=t.receiverAddress,s=W.state.address,r=J.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));await J.sendTransaction({chainNamespace:"eip155",to:e,address:s,data:"0x",value:r??BigInt(0)}),_e.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:((n=W.state.preferredAccountTypes)==null?void 0:n.eip155)===Or.ACCOUNT_TYPES.SMART_ACCOUNT,token:((o=pe.state.token)==null?void 0:o.symbol)||"",amount:t.sendTokenAmount,network:((a=p.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)||""}}),(c=J._getClient())==null||c.updateBalance("eip155"),pe.resetSend()},async sendERC20Token(t){ne.pushTransactionStack({onSuccess(){ne.replace("Account")}});const e=J.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));if(W.state.address&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const s=Z.getPlainAddress(t.tokenAddress);await J.writeContract({fromAddress:W.state.address,tokenAddress:s,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:Pl.getERC20Abi(s),chainNamespace:"eip155"}),pe.resetSend()}},async sendSolanaToken(){var t;if(!pe.state.sendTokenAmount||!pe.state.receiverAddress)throw new Error("An amount and receiver address are required");ne.pushTransactionStack({onSuccess(){ne.replace("Account")}}),await J.sendTransaction({chainNamespace:"solana",to:pe.state.receiverAddress,value:pe.state.sendTokenAmount}),(t=J._getClient())==null||t.updateBalance("solana"),pe.resetSend()},resetSend(){me.token=void 0,me.sendTokenAmount=void 0,me.receiverAddress=void 0,me.receiverProfileImageUrl=void 0,me.receiverProfileName=void 0,me.loading=!1,me.tokenBalances=[]}},pe=at(Zl),Ui={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},ei={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},L=T.proxy({chains:T.proxyMap(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),Ql={state:L,subscribe(t){return T.subscribe(L,()=>{t(L)})},subscribeKey(t,e){return T.subscribeKey(L,t,e)},subscribeChainProp(t,e,s){let r;return T.subscribe(L.chains,()=>{var n;const i=s||L.activeChain;if(i){const o=(n=L.chains.get(i))==null?void 0:n[t];r!==o&&(r=o,e(o))}})},initialize(t,e,s){const{chainId:r,namespace:i}=q.getActiveNetworkProps(),n=e==null?void 0:e.find(u=>u.id.toString()===(r==null?void 0:r.toString())),a=t.find(u=>(u==null?void 0:u.namespace)===i)||(t==null?void 0:t[0]),c=t.map(u=>u.namespace).filter(u=>u!==void 0),l=A.state.enableEmbedded?new Set([...c]):new Set([...(e==null?void 0:e.map(u=>u.chainNamespace))??[]]);((t==null?void 0:t.length)===0||!a)&&(L.noAdapters=!0),L.noAdapters||(L.activeChain=a==null?void 0:a.namespace,L.activeCaipNetwork=n,p.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:n}),L.activeChain&&as.set({activeChain:a==null?void 0:a.namespace})),l.forEach(u=>{const d=e==null?void 0:e.filter(g=>g.chainNamespace===u);p.state.chains.set(u,{namespace:u,networkState:T.proxy({...ei,caipNetwork:d==null?void 0:d[0]}),accountState:T.proxy(Ui),caipNetworks:d??[],...s}),p.setRequestedCaipNetworks(d??[],u)})},removeAdapter(t){var e,s;if(L.activeChain===t){const r=Array.from(L.chains.entries()).find(([i])=>i!==t);if(r){const i=(s=(e=r[1])==null?void 0:e.caipNetworks)==null?void 0:s[0];i&&p.setActiveCaipNetwork(i)}}L.chains.delete(t)},addAdapter(t,{networkControllerClient:e,connectionControllerClient:s},r){L.chains.set(t.namespace,{namespace:t.namespace,networkState:{...ei,caipNetwork:r[0]},accountState:Ui,caipNetworks:r,connectionControllerClient:s,networkControllerClient:e}),p.setRequestedCaipNetworks((r==null?void 0:r.filter(i=>i.chainNamespace===t.namespace))??[],t.namespace)},addNetwork(t){var s;const e=L.chains.get(t.chainNamespace);if(e){const r=[...e.caipNetworks||[]];(s=e.caipNetworks)!=null&&s.find(i=>i.id===t.id)||r.push(t),L.chains.set(t.chainNamespace,{...e,caipNetworks:r}),p.setRequestedCaipNetworks(r,t.chainNamespace),B.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){var r,i,n;const s=L.chains.get(t);if(s){const o=((r=L.activeCaipNetwork)==null?void 0:r.id)===e,a=[...((i=s.caipNetworks)==null?void 0:i.filter(c=>c.id!==e))||[]];o&&((n=s==null?void 0:s.caipNetworks)!=null&&n[0])&&p.setActiveCaipNetwork(s.caipNetworks[0]),L.chains.set(t,{...s,caipNetworks:a}),p.setRequestedCaipNetworks(a||[],t),a.length===0&&B.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=L.chains.get(t);s&&(s.networkState={...s.networkState||ei,...e},L.chains.set(t,s))},setChainAccountData(t,e,s=!0){if(!t)throw new Error("Chain is required to update chain account data");const r=L.chains.get(t);if(r){const i={...r.accountState||Ui,...e};L.chains.set(t,{...r,accountState:i}),(L.chains.size===1||L.activeChain===t)&&(e.caipAddress&&(L.activeCaipAddress=e.caipAddress),W.replaceState(i))}},setChainNetworkData(t,e){if(!t)return;const s=L.chains.get(t);if(s){const r={...s.networkState||ei,...e};L.chains.set(t,{...s,networkState:r})}},setAccountProp(t,e,s,r=!0){p.setChainAccountData(s,{[t]:e},r),t==="status"&&e==="disconnected"&&s&&B.removeConnectorId(s)},setActiveNamespace(t){var r,i;L.activeChain=t;const e=t?L.chains.get(t):void 0,s=(r=e==null?void 0:e.networkState)==null?void 0:r.caipNetwork;s!=null&&s.id&&t&&(L.activeCaipAddress=(i=e==null?void 0:e.accountState)==null?void 0:i.caipAddress,L.activeCaipNetwork=s,p.setChainNetworkData(t,{caipNetwork:s}),q.setActiveCaipNetworkId(s==null?void 0:s.caipNetworkId),as.set({activeChain:t,selectedNetworkId:s==null?void 0:s.caipNetworkId}))},setActiveCaipNetwork(t){var r,i,n;if(!t)return;L.activeChain!==t.chainNamespace&&p.setIsSwitchingNamespace(!0);const e=L.chains.get(t.chainNamespace);L.activeChain=t.chainNamespace,L.activeCaipNetwork=t,p.setChainNetworkData(t.chainNamespace,{caipNetwork:t}),(r=e==null?void 0:e.accountState)!=null&&r.address?L.activeCaipAddress=`${t.chainNamespace}:${t.id}:${(i=e==null?void 0:e.accountState)==null?void 0:i.address}`:L.activeCaipAddress=void 0,p.setAccountProp("caipAddress",L.activeCaipAddress,t.chainNamespace),e&&W.replaceState(e.accountState),pe.resetSend(),as.set({activeChain:L.activeChain,selectedNetworkId:(n=L.activeCaipNetwork)==null?void 0:n.caipNetworkId}),q.setActiveCaipNetworkId(t.caipNetworkId),!p.checkIfSupportedNetwork(t.chainNamespace)&&A.state.enableNetworkSwitch&&!A.state.allowUnsupportedChain&&!J.state.wcBasic&&p.showUnsupportedChainUI()},addCaipNetwork(t){var s;if(!t)return;const e=L.chains.get(t.chainNamespace);e&&((s=e==null?void 0:e.caipNetworks)==null||s.push(t))},async switchActiveNamespace(t){var i;if(!t)return;const e=t!==p.state.activeChain,s=(i=p.getNetworkData(t))==null?void 0:i.caipNetwork,r=p.getCaipNetworkByNamespace(t,s==null?void 0:s.id);e&&r&&await p.switchActiveNetwork(r)},async switchActiveNetwork(t){var i;const e=p.state.chains.get(p.state.activeChain),s=!((i=e==null?void 0:e.caipNetworks)!=null&&i.some(n=>{var o;return n.id===((o=L.activeCaipNetwork)==null?void 0:o.id)})),r=p.getNetworkControllerClient(t.chainNamespace);if(r){try{await r.switchCaipNetwork(t),s&&Le.close()}catch{ne.goBack()}_e.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})}},getNetworkControllerClient(t){const e=t||L.activeChain,s=L.chains.get(e);if(!s)throw new Error("Chain adapter not found");if(!s.networkControllerClient)throw new Error("NetworkController client not set");return s.networkControllerClient},getConnectionControllerClient(t){const e=t||L.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const s=L.chains.get(e);if(!(s!=null&&s.connectionControllerClient))throw new Error("ConnectionController client not set");return s.connectionControllerClient},getAccountProp(t,e){var i;let s=L.activeChain;if(e&&(s=e),!s)return;const r=(i=L.chains.get(s))==null?void 0:i.accountState;if(r)return r[t]},getNetworkProp(t,e){var r;const s=(r=L.chains.get(e))==null?void 0:r.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=L.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:r=[]}=(e==null?void 0:e.networkState)||{};return Z.sortRequestedNetworks(s,r)},getAllRequestedCaipNetworks(){const t=[];return L.chains.forEach(e=>{const s=p.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){p.setAdapterNetworkState(e,{requestedCaipNetworks:t});const r=p.getAllRequestedCaipNetworks().map(n=>n.chainNamespace),i=Array.from(new Set(r));B.filterByNamespaces(i)},getAllApprovedCaipNetworkIds(){const t=[];return L.chains.forEach(e=>{const s=p.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(){return L.activeCaipNetwork},getActiveCaipAddress(){return L.activeCaipAddress},getApprovedCaipNetworkIds(t){var r;const e=L.chains.get(t);return((r=e==null?void 0:e.networkState)==null?void 0:r.approvedCaipNetworkIds)||[]},async setApprovedCaipNetworksData(t){const e=p.getNetworkControllerClient(),s=await(e==null?void 0:e.getApprovedCaipNetworksData());p.setAdapterNetworkState(t,{approvedCaipNetworkIds:s==null?void 0:s.approvedCaipNetworkIds,supportsAllNetworks:s==null?void 0:s.supportsAllNetworks})},checkIfSupportedNetwork(t,e){const s=e||L.activeCaipNetwork,r=p.getRequestedCaipNetworks(t);return r.length?r==null?void 0:r.some(i=>i.id===(s==null?void 0:s.id)):!0},checkIfSupportedChainId(t){if(!L.activeChain)return!0;const e=p.getRequestedCaipNetworks(L.activeChain);return e==null?void 0:e.some(s=>s.id===t)},setSmartAccountEnabledNetworks(t,e){p.setAdapterNetworkState(e,{smartAccountEnabledNetworks:t})},checkIfSmartAccountEnabled(){var r;const t=Va.caipNetworkIdToNumber((r=L.activeCaipNetwork)==null?void 0:r.caipNetworkId),e=L.activeChain;if(!e||!t)return!1;const s=p.getNetworkProp("smartAccountEnabledNetworks",e);return!!(s!=null&&s.includes(Number(t)))},getActiveNetworkTokenAddress(){var r,i;const t=((r=L.activeCaipNetwork)==null?void 0:r.chainNamespace)||"eip155",e=((i=L.activeCaipNetwork)==null?void 0:i.id)||1,s=be.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`},showUnsupportedChainUI(){Le.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=L.activeCaipNetwork;return!!(t!=null&&t.chainNamespace&&be.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){p.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(t){const e=t;if(!e)throw new Error("Chain is required to set account prop");L.activeCaipAddress=void 0,p.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountTypes:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),B.removeConnectorId(e)},setIsSwitchingNamespace(t){L.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){var s,r;const t=[];let e;if(L.chains.forEach(i=>{H.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===i.namespace)&&i.namespace&&t.push(i.namespace)}),t.length>0){const i=t[0];return e=i?(r=(s=L.chains.get(i))==null?void 0:s.caipNetworks)==null?void 0:r[0]:void 0,e}},getAccountData(t){var e;return t?(e=p.state.chains.get(t))==null?void 0:e.accountState:W.state},getNetworkData(t){var s;const e=t||L.activeChain;if(e)return(s=p.state.chains.get(e))==null?void 0:s.networkState},getCaipNetworkByNamespace(t,e){var i,n,o;if(!t)return;const s=p.state.chains.get(t),r=(i=s==null?void 0:s.caipNetworks)==null?void 0:i.find(a=>a.id===e);return r||((n=s==null?void 0:s.networkState)==null?void 0:n.caipNetwork)||((o=s==null?void 0:s.caipNetworks)==null?void 0:o[0])},getRequestedCaipNetworkIds(){const t=B.state.filterByNamespace;return(t?[L.chains.get(t)]:Array.from(L.chains.values())).flatMap(s=>(s==null?void 0:s.caipNetworks)||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?p.getRequestedCaipNetworks(t):p.getAllRequestedCaipNetworks()}},p=at(Ql),eu={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},Ya=Z.getBlockchainApiUrl(),et=T.proxy({clientId:null,api:new zr({baseUrl:Ya,clientId:null}),supportedChains:{http:[],ws:[]}}),X={state:et,async get(t){const{st:e,sv:s}=X.getSdkProperties(),r=A.state.projectId,i={...t.params||{},st:e,sv:s,projectId:r};return et.api.get({...t,params:i})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=A.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{et.supportedChains.http.length||await X.getSupportedNetworks()}catch{return!1}return et.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await X.get({path:"v1/supported-chains"});return et.supportedChains=t,t}catch{return et.supportedChains}},async fetchIdentity({address:t,caipNetworkId:e}){if(!await X.isNetworkSupported(e))return{avatar:"",name:""};const r=q.getIdentityFromCacheForAddress(t);if(r)return r;const i=await X.get({path:`/v1/identity/${t}`,params:{sender:p.state.activeCaipAddress?Z.getPlainAddress(p.state.activeCaipAddress):void 0}});return q.updateIdentityCache({address:t,identity:i,timestamp:Date.now()}),i},async fetchTransactions({account:t,cursor:e,onramp:s,signal:r,cache:i,chainId:n}){var a;return await X.isNetworkSupported((a=p.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?X.get({path:`/v1/account/${t}/history`,params:{cursor:e,onramp:s,chainId:n},signal:r,cache:i}):{data:[],next:void 0}},async fetchSwapQuote({amount:t,userAddress:e,from:s,to:r,gasPrice:i}){var o;return await X.isNetworkSupported((o=p.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?X.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:s,to:r,gasPrice:i}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){var s;return await X.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?X.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){var s;return await X.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?et.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:A.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){var r;return await X.isNetworkSupported((r=p.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?X.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){var i;const{st:e,sv:s}=X.getSdkProperties();if(!await X.isNetworkSupported((i=p.state.activeCaipNetwork)==null?void 0:i.caipNetworkId))throw new Error("Network not supported for Gas Price");return X.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:s}})},async generateSwapCalldata({amount:t,from:e,to:s,userAddress:r,disableEstimate:i}){var o;if(!await X.isNetworkSupported((o=p.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return et.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:be.CONVERT_SLIPPAGE_TOLERANCE},projectId:A.state.projectId,from:e,to:s,userAddress:r,disableEstimate:i}})},async generateApproveCalldata({from:t,to:e,userAddress:s}){var o;const{st:r,sv:i}=X.getSdkProperties();if(!await X.isNetworkSupported((o=p.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return X.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:t,to:e,st:r,sv:i}})},async getBalance(t,e,s){var l;const{st:r,sv:i}=X.getSdkProperties();if(!await X.isNetworkSupported((l=p.state.activeCaipNetwork)==null?void 0:l.caipNetworkId))return Et.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=q.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await X.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:s,st:r,sv:i}});return q.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){var s;return await X.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?X.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){var s;return await X.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?X.get({path:`/v1/profile/reverse/${t}`,params:{sender:W.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(t){var s;return await X.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?X.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:r}){var n;return await X.isNetworkSupported((n=p.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?et.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:s,signature:r},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:s,purchaseAmount:r,paymentAmount:i}){var a;return await X.isNetworkSupported((a=p.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await et.api.post({path:"/v1/generators/onrampurl",params:{projectId:A.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:r,presetFiatAmount:i}})).url:""},async getOnrampOptions(){var e;if(!await X.isNetworkSupported((e=p.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await X.get({path:"/v1/onramp/options"})}catch{return eu}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:r}){var i;try{return await X.isNetworkSupported((i=p.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?await et.api.post({path:"/v1/onramp/quote",params:{projectId:A.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:s,network:r}}):null}catch{return{coinbaseFee:{amount:s,currency:e.id},networkFee:{amount:s,currency:e.id},paymentSubtotal:{amount:s,currency:e.id},paymentTotal:{amount:s,currency:e.id},purchaseAmount:{amount:s,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){var s;return await X.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?X.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){var i;return await X.isNetworkSupported((i=p.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?et.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:A.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){et.clientId=t,et.api=new zr({baseUrl:Ya,clientId:t})}},ft=T.proxy({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),tu={state:ft,replaceState(t){t&&Object.assign(ft,T.ref(t))},subscribe(t){return p.subscribeChainProp("accountState",e=>{if(e)return t(e)})},subscribeKey(t,e,s){let r;return p.subscribeChainProp("accountState",i=>{if(i){const n=i[t];r!==n&&(r=n,e(n))}},s)},setStatus(t,e){p.setAccountProp("status",t,e)},getCaipAddress(t){return p.getAccountProp("caipAddress",t)},setCaipAddress(t,e){const s=t?Z.getPlainAddress(t):void 0;e===p.state.activeChain&&(p.state.activeCaipAddress=t),p.setAccountProp("caipAddress",t,e),p.setAccountProp("address",s,e)},setBalance(t,e,s){p.setAccountProp("balance",t,s),p.setAccountProp("balanceSymbol",e,s)},setProfileName(t,e){p.setAccountProp("profileName",t,e)},setProfileImage(t,e){p.setAccountProp("profileImage",t,e)},setUser(t,e){p.setAccountProp("user",t,e)},setAddressExplorerUrl(t,e){p.setAccountProp("addressExplorerUrl",t,e)},setSmartAccountDeployed(t,e){p.setAccountProp("smartAccountDeployed",t,e)},setCurrentTab(t){p.setAccountProp("currentTab",t,p.state.activeChain)},setTokenBalance(t,e){t&&p.setAccountProp("tokenBalance",t,e)},setShouldUpdateToAddress(t,e){p.setAccountProp("shouldUpdateToAddress",t,e)},setAllAccounts(t,e){p.setAccountProp("allAccounts",t,e)},addAddressLabel(t,e,s){const r=p.getAccountProp("addressLabels",s)||new Map;r.set(t,e),p.setAccountProp("addressLabels",r,s)},removeAddressLabel(t,e){const s=p.getAccountProp("addressLabels",e)||new Map;s.delete(t),p.setAccountProp("addressLabels",s,e)},setConnectedWalletInfo(t,e){p.setAccountProp("connectedWalletInfo",t,e,!1)},setPreferredAccountType(t,e){p.setAccountProp("preferredAccountTypes",{...ft.preferredAccountTypes,[e]:t},e)},setPreferredAccountTypes(t){ft.preferredAccountTypes=t},setSocialProvider(t,e){t&&p.setAccountProp("socialProvider",t,e)},setSocialWindow(t,e){p.setAccountProp("socialWindow",t?T.ref(t):void 0,e)},setFarcasterUrl(t,e){p.setAccountProp("farcasterUrl",t,e)},async fetchTokenBalance(t){var n,o;ft.balanceLoading=!0;const e=(n=p.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,s=(o=p.state.activeCaipNetwork)==null?void 0:o.chainNamespace,r=p.state.activeCaipAddress,i=r?Z.getPlainAddress(r):void 0;if(ft.lastRetry&&!Z.isAllowedRetry(ft.lastRetry,30*be.ONE_SEC_MS))return ft.balanceLoading=!1,[];try{if(i&&e&&s){const c=(await X.getBalance(i,e)).balances.filter(l=>l.quantity.decimals!=="0");return W.setTokenBalance(c,s),ft.lastRetry=void 0,ft.balanceLoading=!1,c}}catch(a){ft.lastRetry=Date.now(),t==null||t(a),Et.showError("Token Balance Unavailable")}finally{ft.balanceLoading=!1}return[]},resetAccount(t){p.resetAccount(t)}},W=at(tu),su={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){const s=p.state.activeCaipNetwork,r=ne.state.data;if(t.id===(s==null?void 0:s.id))return;const n=W.getCaipAddress(p.state.activeChain),o=t.chainNamespace!==p.state.activeChain,a=W.getCaipAddress(t.chainNamespace),l=B.getConnectorId(p.state.activeChain)===H.CONNECTOR_ID.AUTH,u=H.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(d=>d===t.chainNamespace);e||l&&u?ne.push("SwitchNetwork",{...r,network:t}):n&&o&&!a?ne.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):ne.push("SwitchNetwork",{...r,network:t})}},tt=T.proxy({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),ru={state:tt,subscribe(t){return T.subscribe(tt,()=>t(tt))},subscribeKey(t,e){return T.subscribeKey(tt,t,e)},async open(t){var o,a;const e=W.state.status==="connected",s=t==null?void 0:t.namespace,r=p.state.activeChain,i=s&&s!==r,n=(o=p.getAccountData(t==null?void 0:t.namespace))==null?void 0:o.caipAddress;if(J.state.wcBasic?K.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await K.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),B.setFilterByNamespace(t==null?void 0:t.namespace),Le.setLoading(!0,s),s&&i){const c=((a=p.getNetworkData(s))==null?void 0:a.caipNetwork)||p.getRequestedCaipNetworks(s)[0];c&&su.onSwitchNetwork({network:c,ignoreSwitchConfirmation:!0})}else{const c=p.state.noAdapters;A.state.manualWCControl||c&&!n?Z.isMobile()?ne.reset("AllWallets"):ne.reset("ConnectingWalletConnectBasic"):t!=null&&t.view?ne.reset(t.view,t.data):n?ne.reset("Account"):ne.reset("Connect")}tt.open=!0,as.set({open:!0}),_e.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!n}})},close(){const t=A.state.enableEmbedded,e=!!p.state.activeCaipAddress;tt.open&&_e.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),tt.open=!1,ne.reset("Connect"),Le.clearLoading(),t?e?ne.replace("Account"):ne.push("Connect"):as.set({open:!1}),J.resetUri()},setLoading(t,e){e&&tt.loadingNamespaceMap.set(e,t),tt.loading=t,as.set({loading:t})},clearLoading(){tt.loadingNamespaceMap.clear(),tt.loading=!1},shake(){tt.shake||(tt.shake=!0,setTimeout(()=>{tt.shake=!1},500))}},Le=at(ru),kr={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},cn={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},iu={providers:Ga,selectedProvider:null,error:null,purchaseCurrency:kr,paymentCurrency:cn,purchaseCurrencies:[kr],paymentCurrencies:[],quotesLoading:!1},ce=T.proxy(iu),nu={state:ce,subscribe(t){return T.subscribe(ce,()=>t(ce))},subscribeKey(t,e){return T.subscribeKey(ce,t,e)},setSelectedProvider(t){if(t&&t.name==="meld"){const e=p.state.activeChain===H.CHAIN.SOLANA?"SOL":"USDC",s=W.state.address??"",r=new URL(t.url);r.searchParams.append("publicKey",Tl),r.searchParams.append("destinationCurrencyCode",e),r.searchParams.append("walletAddress",s),r.searchParams.append("externalCustomerId",A.state.projectId),ce.selectedProvider={...t,url:r.toString()}}else ce.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=Ga.filter(r=>e.includes(r.name));ce.providers=s}else ce.providers=[]},setPurchaseCurrency(t){ce.purchaseCurrency=t},setPaymentCurrency(t){ce.paymentCurrency=t},setPurchaseAmount(t){ln.state.purchaseAmount=t},setPaymentAmount(t){ln.state.paymentAmount=t},async getAvailableCurrencies(){const t=await X.getOnrampOptions();ce.purchaseCurrencies=t.purchaseCurrencies,ce.paymentCurrencies=t.paymentCurrencies,ce.paymentCurrency=t.paymentCurrencies[0]||cn,ce.purchaseCurrency=t.purchaseCurrencies[0]||kr,await K.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await K.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){var t,e;ce.quotesLoading=!0;try{const s=await X.getOnrampQuote({purchaseCurrency:ce.purchaseCurrency,paymentCurrency:ce.paymentCurrency,amount:((t=ce.paymentAmount)==null?void 0:t.toString())||"0",network:(e=ce.purchaseCurrency)==null?void 0:e.symbol});return ce.quotesLoading=!1,ce.purchaseAmount=Number(s==null?void 0:s.purchaseAmount.amount),s}catch(s){return ce.error=s.message,ce.quotesLoading=!1,null}finally{ce.quotesLoading=!1}},resetState(){ce.selectedProvider=null,ce.error=null,ce.purchaseCurrency=kr,ce.paymentCurrency=cn,ce.purchaseCurrencies=[kr],ce.paymentCurrencies=[],ce.paymentAmount=void 0,ce.purchaseAmount=void 0,ce.quotesLoading=!1}},ln=at(nu),ro=2147483648,ou={convertEVMChainIdToCoinType(t){if(t>=ro)throw new Error("Invalid chainId");return(ro|t)>>>0}},mt=T.proxy({suggestions:[],loading:!1}),au={state:mt,subscribe(t){return T.subscribe(mt,()=>t(mt))},subscribeKey(t,e){return T.subscribeKey(mt,t,e)},async resolveName(t){var e,s;try{return await X.lookupEnsName(t)}catch(r){const i=r;throw new Error(((s=(e=i==null?void 0:i.reasons)==null?void 0:e[0])==null?void 0:s.description)||"Error resolving name")}},async isNameRegistered(t){try{return await X.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{mt.loading=!0,mt.suggestions=[];const e=await X.getEnsNameSuggestions(t);return mt.suggestions=e.suggestions.map(s=>({...s,name:s.name}))||[],mt.suggestions}catch(e){const s=xr.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{mt.loading=!1}},async getNamesForAddress(t){try{if(!p.state.activeCaipNetwork)return[];const s=q.getEnsFromCacheForAddress(t);if(s)return s;const r=await X.reverseLookupEnsName({address:t});return q.updateEnsCache({address:t,ens:r,timestamp:Date.now()}),r}catch(e){const s=xr.parseEnsApiError(e,"Error fetching names for address");throw new Error(s)}},async registerName(t){const e=p.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const s=W.state.address,r=B.getAuthConnector();if(!s||!r)throw new Error("Address or auth connector not found");mt.loading=!0;try{const i=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});ne.pushTransactionStack({onCancel(){ne.replace("RegisterAccountName")}});const n=await J.signMessage(i);mt.loading=!1;const o=e.id;if(!o)throw new Error("Network not found");const a=ou.convertEVMChainIdToCoinType(Number(o));await X.registerEnsName({coinType:a,address:s,signature:n,message:i}),W.setProfileName(t,e.chainNamespace),ne.replace("RegisterAccountNameSuccess")}catch(i){const n=xr.parseEnsApiError(i,`Error registering name ${t}`);throw ne.replace("RegisterAccountName"),new Error(n)}finally{mt.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){var r,i;const s=t;return((i=(r=s==null?void 0:s.reasons)==null?void 0:r[0])==null?void 0:i.description)||e}},xr=at(au),er={getSIWX(){return A.state.siwx},async initializeIfEnabled(){var n;const t=A.state.siwx,e=p.getActiveCaipAddress();if(!(t&&e))return;const[s,r,i]=e.split(":");if(p.checkIfSupportedNetwork(s))try{if((await t.getSessions(`${s}:${r}`,i)).length)return;await Le.open({view:"SIWXSignMessage"})}catch(o){console.error("SIWXUtil:initializeIfEnabled",o),_e.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await((n=J._getClient())==null?void 0:n.disconnect().catch(console.error)),ne.reset("Connect"),Et.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=A.state.siwx,e=Z.getPlainAddress(p.getActiveCaipAddress()),s=p.getActiveCaipNetwork(),r=J._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");if(!r)throw new Error("No ConnectionController client found");try{const i=await t.createMessage({chainId:s.caipNetworkId,accountAddress:e}),n=i.toString();B.getConnectorId(s.chainNamespace)===H.CONNECTOR_ID.AUTH&&ne.pushTransactionStack({});const a=await r.signMessage(n);await t.addSession({data:i,message:n,signature:a}),Le.close(),_e.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(i){const n=this.getSIWXEventProperties();(!Le.state.open||ne.state.view==="ApproveTransaction")&&await Le.open({view:"SIWXSignMessage"}),n.isSmartAccount?Et.showError("This application might not support Smart Accounts"):Et.showError("Signature declined"),_e.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:n}),console.error("SWIXUtil:requestSignMessage",i)}},async cancelSignMessage(){var t;try{const e=this.getSIWX();((t=e==null?void 0:e.getRequired)==null?void 0:t.call(e))?await J.disconnect():Le.close(),ne.reset("Connect"),_e.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getSessions(){const t=A.state.siwx,e=Z.getPlainAddress(p.getActiveCaipAddress()),s=p.getActiveCaipNetwork();return t&&e&&s?t.getSessions(s.caipNetworkId,e):[]},async isSIWXCloseDisabled(){var e;const t=this.getSIWX();if(t){const s=ne.state.view==="ApproveTransaction",r=ne.state.view==="SIWXSignMessage";if(s||r)return((e=t.getRequired)==null?void 0:e.call(t))&&(await this.getSessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){var a,c,l;const r=er.getSIWX(),i=new Set(e.map(u=>u.split(":")[0]));if(!r||i.size!==1||!i.has("eip155"))return!1;const n=await r.createMessage({chainId:((a=p.getActiveCaipNetwork())==null?void 0:a.caipNetworkId)||"",accountAddress:""}),o=await t.authenticate({nonce:n.nonce,domain:n.domain,uri:n.uri,exp:n.expirationTime,iat:n.issuedAt,nbf:n.notBefore,requestId:n.requestId,version:n.version,resources:n.resources,statement:n.statement,chainId:n.chainId,methods:s,chains:[n.chainId,...e.filter(u=>u!==n.chainId)]});if(Et.showLoading("Authenticating...",{autoClose:!1}),W.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:(c=o.session.peer.metadata.icons)==null?void 0:c[0],type:"WALLET_CONNECT"},Array.from(i)[0]),(l=o==null?void 0:o.auths)!=null&&l.length){const u=o.auths.map(d=>{const g=t.client.formatAuthMessage({request:d.p,iss:d.p.iss});return{data:{...d.p,accountAddress:d.p.iss.split(":").slice(-1).join(""),chainId:d.p.iss.split(":").slice(2,4).join(":"),uri:d.p.aud,version:d.p.version||n.version,expirationTime:d.p.exp,issuedAt:d.p.iat,notBefore:d.p.nbf},message:g,signature:d.s.s,cacao:d}});try{await r.setSessions(u),_e.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:er.getSIWXEventProperties()})}catch(d){throw console.error("SIWX:universalProviderAuth - failed to set sessions",d),_e.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:er.getSIWXEventProperties()}),await t.disconnect().catch(console.error),d}finally{Et.hide()}}return!0},getSIWXEventProperties(){var e,s;const t=p.state.activeChain;return{network:((e=p.state.activeCaipNetwork)==null?void 0:e.caipNetworkId)||"",isSmartAccount:((s=W.state.preferredAccountTypes)==null?void 0:s[t])===Or.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}};var cu=Object.defineProperty,lu=(t,e,s)=>e in t?cu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,io=(t,e,s)=>lu(t,typeof e!="symbol"?e+"":e,s);let uu=class extends h.IEvents{constructor(e){super(),this.opts=e,io(this,"protocol","wc"),io(this,"version",2)}};var du=Object.defineProperty,hu=(t,e,s)=>e in t?du(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pu=(t,e,s)=>hu(t,e+"",s);let gu=class extends h.IEvents{constructor(e,s){super(),this.core=e,this.logger=s,pu(this,"records",new Map)}},fu=class{constructor(e,s){this.logger=e,this.core=s}};class mu extends h.IEvents{constructor(e,s){super(),this.relayer=e,this.logger=s}}let wu=class extends h.IEvents{constructor(e){super()}},yu=class{constructor(e,s,r,i){this.core=e,this.logger=s,this.name=r}},bu=class extends h.IEvents{constructor(e,s){super(),this.relayer=e,this.logger=s}},vu=class extends h.IEvents{constructor(e,s){super(),this.core=e,this.logger=s}},Eu=class{constructor(e,s,r){this.core=e,this.logger=s,this.store=r}},Cu=class{constructor(e,s){this.projectId=e,this.logger=s}},Iu=class{constructor(e,s,r){this.core=e,this.logger=s,this.telemetryEnabled=r}};var Nu=Object.defineProperty,Au=(t,e,s)=>e in t?Nu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,no=(t,e,s)=>Au(t,typeof e!="symbol"?e+"":e,s);let Su=class{constructor(e){this.opts=e,no(this,"protocol","wc"),no(this,"version",2)}},_u=class{constructor(e){this.client=e}};function Fr(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function oo(t){return Fr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Xa="2.23.2";let yr={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${Xa}`};class Ss extends Error{constructor(e,s={}){var a;const r=(()=>{var c;return s.cause instanceof Ss?s.cause.details:(c=s.cause)!=null&&c.message?s.cause.message:s.details})(),i=s.cause instanceof Ss&&s.cause.docsPath||s.docsPath,n=(a=yr.getDocsUrl)==null?void 0:a.call(yr,{...s,docsPath:i}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...yr.version?[`Version: ${yr.version}`]:[]].join(`
4
- `);super(o,s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=i,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=Xa}walk(e){return Za(this,e)}}function Za(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Za(t.cause,e):e?null:t}class Qa extends Ss{constructor({size:e,targetSize:s,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${s}).`,{name:"SizeExceedsPaddingSizeError"})}}function dr(t,{dir:e,size:s=32}={}){return typeof t=="string"?Pu(t,{dir:e,size:s}):Tu(t,{dir:e,size:s})}function Pu(t,{dir:e,size:s=32}={}){if(s===null)return t;const r=t.replace("0x","");if(r.length>s*2)throw new Qa({size:Math.ceil(r.length/2),targetSize:s,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function Tu(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new Qa({size:t.length,targetSize:s,type:"bytes"});const r=new Uint8Array(s);for(let i=0;i<s;i++){const n=e==="right";r[n?i:s-i-1]=t[n?i:t.length-i-1]}return r}class Ou extends Ss{constructor({max:e,min:s,signed:r,size:i,value:n}){super(`Number "${n}" is not in safe ${i?`${i*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${s} to ${e})`:`(above ${s})`}`,{name:"IntegerOutOfRangeError"})}}class ku extends Ss{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function hr(t,{size:e}){if(oo(t)>e)throw new ku({givenSize:oo(t),maxSize:e})}function un(t,e={}){const{signed:s}=e;e.size&&hr(t,{size:e.size});const r=BigInt(t);if(!s)return r;const i=(t.length-2)/2,n=(1n<<BigInt(i)*8n-1n)-1n;return r<=n?r:r-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function xu(t,e={}){return Number(un(t,e))}const Ru=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function dn(t,e={}){return typeof t=="number"||typeof t=="bigint"?tc(t,e):typeof t=="string"?Du(t,e):typeof t=="boolean"?$u(t,e):ec(t,e)}function $u(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(hr(s,{size:e.size}),dr(s,{size:e.size})):s}function ec(t,e={}){let s="";for(let i=0;i<t.length;i++)s+=Ru[t[i]];const r=`0x${s}`;return typeof e.size=="number"?(hr(r,{size:e.size}),dr(r,{dir:"right",size:e.size})):r}function tc(t,e={}){const{signed:s,size:r}=e,i=BigInt(t);let n;r?s?n=(1n<<BigInt(r)*8n-1n)-1n:n=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&s?-n-1n:0;if(n&&i>n||i<o){const c=typeof t=="bigint"?"n":"";throw new Ou({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:s,size:r,value:`${t}${c}`})}const a=`0x${(s&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?dr(a,{size:r}):a}const Uu=new TextEncoder;function Du(t,e={}){const s=Uu.encode(t);return ec(s,e)}const Lu=new TextEncoder;function Fu(t,e={}){return typeof t=="number"||typeof t=="bigint"?Mu(t,e):typeof t=="boolean"?Bu(t,e):Fr(t)?sc(t,e):rc(t,e)}function Bu(t,e={}){const s=new Uint8Array(1);return s[0]=Number(t),typeof e.size=="number"?(hr(s,{size:e.size}),dr(s,{size:e.size})):s}const Wt={zero:48,nine:57,A:65,F:70,a:97,f:102};function ao(t){if(t>=Wt.zero&&t<=Wt.nine)return t-Wt.zero;if(t>=Wt.A&&t<=Wt.F)return t-(Wt.A-10);if(t>=Wt.a&&t<=Wt.f)return t-(Wt.a-10)}function sc(t,e={}){let s=t;e.size&&(hr(s,{size:e.size}),s=dr(s,{dir:"right",size:e.size}));let r=s.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,n=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=ao(r.charCodeAt(a++)),l=ao(r.charCodeAt(a++));if(c===void 0||l===void 0)throw new Ss(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);n[o]=c*16+l}return n}function Mu(t,e){const s=tc(t,e);return sc(s)}function rc(t,e={}){const s=Lu.encode(t);return typeof e.size=="number"?(hr(s,{size:e.size}),dr(s,{dir:"right",size:e.size})):s}function ic(t,e){const s=e||"hex",r=Bn.keccak_256(Fr(t,{strict:!1})?Fu(t):t);return s==="bytes"?r:dn(r)}class ju extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const s=super.get(e);return super.has(e)&&s!==void 0&&(this.delete(e),super.set(e,s)),s}set(e,s){if(super.set(e,s),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const Di=new ju(8192);function qu(t,e){if(Di.has(`${t}.${e}`))return Di.get(`${t}.${e}`);const s=t.substring(2).toLowerCase(),r=ic(rc(s),"bytes"),i=s.split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(r[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const n=`0x${i.join("")}`;return Di.set(`${t}.${e}`,n),n}function Wu(t){const e=ic(`0x${t.substring(4)}`).substring(26);return qu(`0x${e}`)}async function zu({hash:t,signature:e}){const s=Fr(t)?t:dn(t),{secp256k1:r}=await Promise.resolve().then(()=>require("./secp256k1-CjndBUS7.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:d,yParity:g}=e,m=Number(g??d),y=co(m);return new r.Signature(un(l),un(u)).addRecoveryBit(y)}const o=Fr(e)?e:dn(e),a=xu(`0x${o.slice(130)}`),c=co(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(s.substring(2)).toHex(!1)}`}function co(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Hu({hash:t,signature:e}){return Wu(await zu({hash:t,signature:e}))}const Ku=":";function tr(t){const[e,s]=t.split(Ku);return{namespace:e,reference:s}}function nc(t,e){return t.includes(":")?[t]:e.chains||[]}var Vu=Object.defineProperty,Gu=Object.defineProperties,Ju=Object.getOwnPropertyDescriptors,lo=Object.getOwnPropertySymbols,Yu=Object.prototype.hasOwnProperty,Xu=Object.prototype.propertyIsEnumerable,uo=(t,e,s)=>e in t?Vu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ho=(t,e)=>{for(var s in e||(e={}))Yu.call(e,s)&&uo(t,s,e[s]);if(lo)for(var s of lo(e))Xu.call(e,s)&&uo(t,s,e[s]);return t},Zu=(t,e)=>Gu(t,Ju(e));const Qu="ReactNative",pt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},ed="js";function wi(){return typeof U.dist.process<"u"&&typeof U.dist.process.versions<"u"&&typeof U.dist.process.versions.node<"u"}function ps(){return!h.getDocument_1()&&!!h.getNavigator_1()&&navigator.product===Qu}function td(){return ps()&&typeof U.dist.global<"u"&&typeof(U.dist.global==null?void 0:U.dist.global.Platform)<"u"&&(U.dist.global==null?void 0:U.dist.global.Platform.OS)==="android"}function sd(){return ps()&&typeof U.dist.global<"u"&&typeof(U.dist.global==null?void 0:U.dist.global.Platform)<"u"&&(U.dist.global==null?void 0:U.dist.global.Platform.OS)==="ios"}function pr(){return!wi()&&!!h.getNavigator_1()&&!!h.getDocument_1()}function Hr(){return ps()?pt.reactNative:wi()?pt.node:pr()?pt.browser:pt.unknown}function po(){var t;try{return ps()&&typeof U.dist.global<"u"&&typeof(U.dist.global==null?void 0:U.dist.global.Application)<"u"?(t=U.dist.global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function rd(t,e){const s=new URLSearchParams(t);for(const r of Object.keys(e).sort())if(e.hasOwnProperty(r)){const i=e[r];i!==void 0&&s.set(r,i)}return s.toString()}function id(t){var e,s;const r=oc();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),Zu(ho(ho({},r),t),{url:(t==null?void 0:t.url)||r.url,name:(t==null?void 0:t.name)||r.name,description:(t==null?void 0:t.description)||r.description,icons:(s=t==null?void 0:t.icons)!=null&&s.length&&t.icons.length>0?t.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),t||r}}function oc(){return h.getWindowMetadata_1()||{name:"",description:"",url:"",icons:[""]}}function nd(){if(Hr()===pt.reactNative&&typeof U.dist.global<"u"&&typeof(U.dist.global==null?void 0:U.dist.global.Platform)<"u"){const{OS:s,Version:r}=U.dist.global.Platform;return[s,r].join("-")}const t=h.detect();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function od(){var t;const e=Hr();return e===pt.browser?[e,((t=h.getLocation_1())==null?void 0:t.host)||"unknown"].join(":"):e}function ac(t,e,s){const r=nd(),i=od();return[[t,e].join("-"),[ed,s].join("-"),r,i].join("/")}function ad({protocol:t,version:e,relayUrl:s,sdkVersion:r,auth:i,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),u=ac(t,e,r),d={auth:i,ua:u,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},g=rd(l[1]||"",d);return l[0]+"?"+g}function Ns(t,e){return t.filter(s=>e.includes(s)).length===t.length}function hn(t){return Object.fromEntries(t.entries())}function pn(t){return new Map(Object.entries(t))}function bs(t=h.cjs.FIVE_MINUTES,e){const s=h.cjs.toMiliseconds(t||h.cjs.FIVE_MINUTES);let r,i,n,o;return{resolve:a=>{n&&r&&(clearTimeout(n),r(a),o=Promise.resolve(a))},reject:a=>{n&&i&&(clearTimeout(n),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},s),r=a,i=c})}}function os(t,e,s){return new Promise(async(r,i)=>{const n=setTimeout(()=>i(new Error(s)),e);try{const o=await t;r(o)}catch(o){i(o)}clearTimeout(n)})}function cc(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function cd(t){return cc("topic",t)}function ld(t){return cc("id",t)}function lc(t){const[e,s]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof s=="string")r.topic=s;else if(e==="id"&&Number.isInteger(Number(s)))r.id=Number(s);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${s}`);return r}function De(t,e){return h.cjs.fromMiliseconds(Date.now()+h.cjs.toMiliseconds(t))}function ss(t){return Date.now()>=h.cjs.toMiliseconds(t)}function fe(t,e){return`${t}${e?`:${e}`:""}`}function Ut(t=[],e=[]){return[...new Set([...t,...e])]}async function ud({id:t,topic:e,wcDeepLink:s}){var r;try{if(!s)return;const i=typeof s=="string"?JSON.parse(s):s,n=i==null?void 0:i.href;if(typeof n!="string")return;const o=dd(n,t,e),a=Hr();if(a===pt.browser){if(!((r=h.getDocument_1())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}hd(o)}else a===pt.reactNative&&typeof(U.dist.global==null?void 0:U.dist.global.Linking)<"u"&&await U.dist.global.Linking.openURL(o)}catch(i){console.error(i)}}function dd(t,e,s){const r=`requestId=${e}&sessionTopic=${s}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${n}${md(r,!0)}`}else i=`${i}/wc?${r}`;return i}function hd(t){let e="_self";fd()?e="_top":(gd()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function pd(t,e){let s="";try{if(pr()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(r){console.error(r)}return s}function go(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),r=s.indexOf(e);return s[r+2]}function fo(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function jn(){return typeof U.dist.process<"u"&&U.dist.process.env.IS_VITEST==="true"}function gd(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function fd(){try{return window.self!==window.top}catch{return!1}}function md(t,e=!1){const s=U.dist.Buffer.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function uc(t){return U.dist.Buffer.from(t,"base64").toString("utf-8")}function wd(t){return new Promise(e=>setTimeout(e,t))}function Br(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function yd(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Kr(t,...e){if(!yd(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function qn(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Br(t.outputLen),Br(t.blockLen)}function ir(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function dc(t,e){Kr(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const ti=BigInt(2**32-1),mo=BigInt(32);function bd(t,e=!1){return e?{h:Number(t&ti),l:Number(t>>mo&ti)}:{h:Number(t>>mo&ti)|0,l:Number(t&ti)|0}}function vd(t,e=!1){let s=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:n,l:o}=bd(t[i],e);[s[i],r[i]]=[n,o]}return[s,r]}const Ed=(t,e,s)=>t<<s|e>>>32-s,Cd=(t,e,s)=>e<<s|t>>>32-s,Id=(t,e,s)=>e<<s-32|t>>>64-s,Nd=(t,e,s)=>t<<s-32|e>>>64-s,Rs=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Ad(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Li(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Tt(t,e){return t<<32-e|t>>>e}const wo=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Sd(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function yo(t){for(let e=0;e<t.length;e++)t[e]=Sd(t[e])}function _d(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function nr(t){return typeof t=="string"&&(t=_d(t)),Kr(t),t}function Pd(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Kr(i),e+=i.length}const s=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const n=t[r];s.set(n,i),i+=n.length}return s}let Wn=class{clone(){return this._cloneInto()}};function hc(t){const e=r=>t().update(nr(r)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function gr(t=32){if(Rs&&typeof Rs.getRandomValues=="function")return Rs.getRandomValues(new Uint8Array(t));if(Rs&&typeof Rs.randomBytes=="function")return Rs.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const pc=[],gc=[],fc=[],Td=BigInt(0),br=BigInt(1),Od=BigInt(2),kd=BigInt(7),xd=BigInt(256),Rd=BigInt(113);for(let t=0,e=br,s=1,r=0;t<24;t++){[s,r]=[r,(2*s+3*r)%5],pc.push(2*(5*r+s)),gc.push((t+1)*(t+2)/2%64);let i=Td;for(let n=0;n<7;n++)e=(e<<br^(e>>kd)*Rd)%xd,e&Od&&(i^=br<<(br<<BigInt(n))-br);fc.push(i)}const[$d,Ud]=vd(fc,!0),bo=(t,e,s)=>s>32?Id(t,e,s):Ed(t,e,s),vo=(t,e,s)=>s>32?Nd(t,e,s):Cd(t,e,s);function Dd(t,e=24){const s=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],d=bo(l,u,1)^s[a],g=vo(l,u,1)^s[a+1];for(let m=0;m<50;m+=10)t[o+m]^=d,t[o+m+1]^=g}let i=t[2],n=t[3];for(let o=0;o<24;o++){const a=gc[o],c=bo(i,n,a),l=vo(i,n,a),u=pc[o];i=t[u],n=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=$d[r],t[1]^=Ud[r]}s.fill(0)}let Ld=class mc extends Wn{constructor(e,s,r,i=!1,n=24){if(super(),this.blockLen=e,this.suffix=s,this.outputLen=r,this.enableXOF=i,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Br(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Ad(this.state)}keccak(){wo||yo(this.state32),Dd(this.state32,this.rounds),wo||yo(this.state32),this.posOut=0,this.pos=0}update(e){ir(this);const{blockLen:s,state:r}=this;e=nr(e);const i=e.length;for(let n=0;n<i;){const o=Math.min(s-this.pos,i-n);for(let a=0;a<o;a++)r[this.pos++]^=e[n++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:r,blockLen:i}=this;e[r]^=s,s&128&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){ir(this,!1),Kr(e),this.finish();const s=this.state,{blockLen:r}=this;for(let i=0,n=e.length;i<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-i);e.set(s.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Br(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(dc(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:s,suffix:r,outputLen:i,rounds:n,enableXOF:o}=this;return e||(e=new mc(s,r,i,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Fd=(t,e,s)=>hc(()=>new Ld(e,t,s)),Bd=Fd(1,136,256/8),Md="https://rpc.walletconnect.org/v1";function wc(t){const e=`Ethereum Signed Message:
5
- ${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+U.dist.Buffer.from(Bd(s)).toString("hex")}async function jd(t,e,s,r,i,n){switch(s.t){case"eip191":return await qd(t,e,s.s);case"eip1271":return await Wd(t,e,s.s,r,i,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}async function qd(t,e,s){return(await Hu({hash:wc(e),signature:s})).toLowerCase()===t.toLowerCase()}async function Wd(t,e,s,r,i,n){const o=tr(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l="0000000000000000000000000000000000000000000000000000000000000041",u=s.substring(2),d=wc(e).substring(2),g=a+d+c+l+u,m=await fetch(`${n||Md}/?chainId=${r}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:zd(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:g},"latest"]})}),{result:y}=await m.json();return y?y.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function zd(){return Date.now()+Math.floor(Math.random()*1e3)}function Hd(t){const e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);const r=s[0];if(r===0)throw new Error("No signatures found");const i=1+r*64;if(s.length<i)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const n=U.dist.Buffer.from(t,"base64").slice(1,65);return Bn.bs58.encode(n)}var Kd=Object.defineProperty,Vd=Object.defineProperties,Gd=Object.getOwnPropertyDescriptors,Eo=Object.getOwnPropertySymbols,Jd=Object.prototype.hasOwnProperty,Yd=Object.prototype.propertyIsEnumerable,Co=(t,e,s)=>e in t?Kd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Xd=(t,e)=>{for(var s in e||(e={}))Jd.call(e,s)&&Co(t,s,e[s]);if(Eo)for(var s of Eo(e))Yd.call(e,s)&&Co(t,s,e[s]);return t},Zd=(t,e)=>Vd(t,Gd(e));const Qd="did:pkh:",zn=t=>t==null?void 0:t.split(":"),eh=t=>{const e=t&&zn(t);if(e)return t.includes(Qd)?e[3]:e[1]},gn=t=>{const e=t&&zn(t);if(e)return e[2]+":"+e[3]},yi=t=>{const e=t&&zn(t);if(e)return e.pop()};async function Io(t){const{cacao:e,projectId:s}=t,{s:r,p:i}=e,n=yc(i,i.iss),o=yi(i.iss);return await jd(o,n,r,gn(i.iss),s)}const yc=(t,e)=>{const s=`${t.domain} wants you to sign in with your Ethereum account:`,r=yi(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0;const n=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${eh(e)}`,c=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,u=t.exp?`Expiration Time: ${t.exp}`:void 0,d=t.nbf?`Not Before: ${t.nbf}`:void 0,g=t.requestId?`Request ID: ${t.requestId}`:void 0,m=t.resources?`Resources:${t.resources.map(w=>`
6
- - ${w}`).join("")}`:void 0,y=hi(t.resources);if(y){const w=Mr(y);i=lh(i,w)}return[s,r,"",i,"",n,o,a,c,l,u,d,g,m].filter(w=>w!=null).join(`
7
- `)};function th(t){return U.dist.Buffer.from(JSON.stringify(t)).toString("base64")}function sh(t){return JSON.parse(U.dist.Buffer.from(t,"base64").toString("utf-8"))}function _s(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(s=>{const r=t.att[s];if(Array.isArray(r))throw new Error(`Resource must be an object: ${s}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${s}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${s}`);Object.keys(r).forEach(i=>{const n=r[i];if(!Array.isArray(n))throw new Error(`Ability limits ${i} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function rh(t,e,s,r={}){return s==null||s.sort((i,n)=>i.localeCompare(n)),{att:{[t]:ih(e,s,r)}}}function ih(t,e,s={}){e=e==null?void 0:e.sort((i,n)=>i.localeCompare(n));const r=e.map(i=>({[`${t}/${i}`]:[s]}));return Object.assign({},...r)}function bc(t){return _s(t),`urn:recap:${th(t).replace(/=/g,"")}`}function Mr(t){const e=sh(t.replace("urn:recap:",""));return _s(e),e}function nh(t,e,s){const r=rh(t,e,s);return bc(r)}function oh(t){return t&&t.includes("urn:recap:")}function ah(t,e){const s=Mr(t),r=Mr(e),i=ch(s,r);return bc(i)}function ch(t,e){_s(t),_s(e);const s=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,n)=>i.localeCompare(n)),r={att:{}};return s.forEach(i=>{var n,o;Object.keys(((n=t.att)==null?void 0:n[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;r.att[i]=Zd(Xd({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((l=e.att[i])==null?void 0:l[a])})})}),r}function lh(t="",e){_s(e);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(s))return t;const r=[];let i=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));c.sort((d,g)=>d.action.localeCompare(g.action));const l={};c.forEach(d=>{l[d.ability]||(l[d.ability]=[]),l[d.ability].push(d.action)});const u=Object.keys(l).map(d=>(i++,`(${i}) '${d}': '${l[d].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const n=r.join(" "),o=`${s}${n}`;return`${t?t+" ":""}${o}`}function No(t){var e;const s=Mr(t);_s(s);const r=(e=s.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function Ao(t){const e=Mr(t);_s(e);const s=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(i=>{var n;(n=i==null?void 0:i[0])!=null&&n.chains&&s.push(i[0].chains)})}),[...new Set(s.flat())]}function hi(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return oh(e)?e:void 0}function Fi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function vc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ht(t,...e){if(!vc(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function So(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function uh(t,e){ht(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function _o(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const cs=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),dh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),hh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!hh)throw new Error("Non little-endian hardware is not supported");function ph(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function fn(t){if(typeof t=="string")t=ph(t);else if(vc(t))t=mn(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function gh(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function fh(t,e){if(t.length!==e.length)return!1;let s=0;for(let r=0;r<t.length;r++)s|=t[r]^e[r];return s===0}const mh=(t,e)=>{function s(r,...i){if(ht(r),t.nonceLength!==void 0){const l=i[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?ht(l):ht(l,t.nonceLength)}const n=t.tagLength;n&&i[1]!==void 0&&ht(i[1]);const o=e(r,...i),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");ht(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ht(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(ht(l),n&&l.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(s,t),s};function Po(t,e,s=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(s&&!wh(e))throw new Error("invalid output, must be aligned");return e}function To(t,e,s,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,r);const i=BigInt(32),n=BigInt(4294967295),o=Number(s>>i&n),a=Number(s&n);t.setUint32(e+4,o,r),t.setUint32(e+0,a,r)}function wh(t){return t.byteOffset%4===0}function mn(t){return Uint8Array.from(t)}function or(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const Ec=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),yh=Ec("expand 16-byte k"),bh=Ec("expand 32-byte k"),vh=cs(yh),Eh=cs(bh);function ue(t,e){return t<<e|t>>>32-e}function wn(t){return t.byteOffset%4===0}const si=64,Ch=16,Cc=2**32-1,Oo=new Uint32Array;function Ih(t,e,s,r,i,n,o,a){const c=i.length,l=new Uint8Array(si),u=cs(l),d=wn(i)&&wn(n),g=d?cs(i):Oo,m=d?cs(n):Oo;for(let y=0;y<c;o++){if(t(e,s,r,u,o,a),o>=Cc)throw new Error("arx: counter overflow");const w=Math.min(si,c-y);if(d&&w===si){const f=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let v=0,b;v<Ch;v++)b=f+v,m[b]=g[b]^u[v];y+=si;continue}for(let f=0,v;f<w;f++)v=y+f,n[v]=i[v]^l[f];y+=w}}function Nh(t,e){const{allowShortKeys:s,extendNonceFn:r,counterLength:i,counterRight:n,rounds:o}=gh({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Fi(i),Fi(o),_o(n),_o(s),(a,c,l,u,d=0)=>{ht(a),ht(c),ht(l);const g=l.length;if(u===void 0&&(u=new Uint8Array(g)),ht(u),Fi(d),d<0||d>=Cc)throw new Error("arx: counter overflow");if(u.length<g)throw new Error(`arx: output (${u.length}) is shorter than data (${g})`);const m=[];let y=a.length,w,f;if(y===32)m.push(w=mn(a)),f=Eh;else if(y===16&&s)w=new Uint8Array(32),w.set(a),w.set(a,16),f=vh,m.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${y}`);wn(c)||m.push(c=mn(c));const v=cs(w);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(f,v,cs(c.subarray(0,16)),v),c=c.subarray(16)}const b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){const S=new Uint8Array(12);S.set(c,n?0:12-c.length),c=S,m.push(c)}const E=cs(c);return Ih(t,f,v,E,l,u,d,o),or(...m),u}}const ze=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class Ah{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=fn(e),ht(e,32);const s=ze(e,0),r=ze(e,2),i=ze(e,4),n=ze(e,6),o=ze(e,8),a=ze(e,10),c=ze(e,12),l=ze(e,14);this.r[0]=s&8191,this.r[1]=(s>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=ze(e,16+2*u)}process(e,s,r=!1){const i=r?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],g=o[5],m=o[6],y=o[7],w=o[8],f=o[9],v=ze(e,s+0),b=ze(e,s+2),E=ze(e,s+4),S=ze(e,s+6),R=ze(e,s+8),_=ze(e,s+10),O=ze(e,s+12),D=ze(e,s+14);let C=n[0]+(v&8191),G=n[1]+((v>>>13|b<<3)&8191),M=n[2]+((b>>>10|E<<6)&8191),z=n[3]+((E>>>7|S<<9)&8191),Q=n[4]+((S>>>4|R<<12)&8191),N=n[5]+(R>>>1&8191),x=n[6]+((R>>>14|_<<2)&8191),k=n[7]+((_>>>11|O<<5)&8191),F=n[8]+((O>>>8|D<<8)&8191),j=n[9]+(D>>>5|i),P=0,Y=P+C*a+G*(5*f)+M*(5*w)+z*(5*y)+Q*(5*m);P=Y>>>13,Y&=8191,Y+=N*(5*g)+x*(5*d)+k*(5*u)+F*(5*l)+j*(5*c),P+=Y>>>13,Y&=8191;let te=P+C*c+G*a+M*(5*f)+z*(5*w)+Q*(5*y);P=te>>>13,te&=8191,te+=N*(5*m)+x*(5*g)+k*(5*d)+F*(5*u)+j*(5*l),P+=te>>>13,te&=8191;let ie=P+C*l+G*c+M*a+z*(5*f)+Q*(5*w);P=ie>>>13,ie&=8191,ie+=N*(5*y)+x*(5*m)+k*(5*g)+F*(5*d)+j*(5*u),P+=ie>>>13,ie&=8191;let Ie=P+C*u+G*l+M*c+z*a+Q*(5*f);P=Ie>>>13,Ie&=8191,Ie+=N*(5*w)+x*(5*y)+k*(5*m)+F*(5*g)+j*(5*d),P+=Ie>>>13,Ie&=8191;let ge=P+C*d+G*u+M*l+z*c+Q*a;P=ge>>>13,ge&=8191,ge+=N*(5*f)+x*(5*w)+k*(5*y)+F*(5*m)+j*(5*g),P+=ge>>>13,ge&=8191;let Oe=P+C*g+G*d+M*u+z*l+Q*c;P=Oe>>>13,Oe&=8191,Oe+=N*a+x*(5*f)+k*(5*w)+F*(5*y)+j*(5*m),P+=Oe>>>13,Oe&=8191;let Fe=P+C*m+G*g+M*d+z*u+Q*l;P=Fe>>>13,Fe&=8191,Fe+=N*c+x*a+k*(5*f)+F*(5*w)+j*(5*y),P+=Fe>>>13,Fe&=8191;let Je=P+C*y+G*m+M*g+z*d+Q*u;P=Je>>>13,Je&=8191,Je+=N*l+x*c+k*a+F*(5*f)+j*(5*w),P+=Je>>>13,Je&=8191;let Re=P+C*w+G*y+M*m+z*g+Q*d;P=Re>>>13,Re&=8191,Re+=N*u+x*l+k*c+F*a+j*(5*f),P+=Re>>>13,Re&=8191;let $e=P+C*f+G*w+M*y+z*m+Q*g;P=$e>>>13,$e&=8191,$e+=N*d+x*u+k*l+F*c+j*a,P+=$e>>>13,$e&=8191,P=(P<<2)+P|0,P=P+Y|0,Y=P&8191,P=P>>>13,te+=P,n[0]=Y,n[1]=te,n[2]=ie,n[3]=Ie,n[4]=ge,n[5]=Oe,n[6]=Fe,n[7]=Je,n[8]=Re,n[9]=$e}finalize(){const{h:e,pad:s}=this,r=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+i,i=r[a]>>>13,r[a]&=8191;r[9]-=8192;let n=(i^1)-1;for(let a=0;a<10;a++)r[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+s[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+s[a]|0)+(o>>>16)|0,e[a]=o&65535;or(r)}update(e){So(this);const{buffer:s,blockLen:r}=this;e=fn(e);const i=e.length;for(let n=0;n<i;){const o=Math.min(r-this.pos,i-n);if(o===r){for(;r<=i-n;n+=r)this.process(e,n);continue}s.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===r&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){or(this.h,this.r,this.buffer,this.pad)}digestInto(e){So(this),uh(e,this),this.finished=!0;const{buffer:s,h:r}=this;let{pos:i}=this;if(i){for(s[i++]=1;i<16;i++)s[i]=0;this.process(s,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=r[o]>>>0,e[n++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const r=e.slice(0,s);return this.destroy(),r}}function Sh(t){const e=(r,i)=>t(i).update(fn(r)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=r=>t(r),e}const _h=Sh(t=>new Ah(t));function Ph(t,e,s,r,i,n=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],g=e[2],m=e[3],y=e[4],w=e[5],f=e[6],v=e[7],b=i,E=s[0],S=s[1],R=s[2],_=o,O=a,D=c,C=l,G=u,M=d,z=g,Q=m,N=y,x=w,k=f,F=v,j=b,P=E,Y=S,te=R;for(let Ie=0;Ie<n;Ie+=2)_=_+G|0,j=ue(j^_,16),N=N+j|0,G=ue(G^N,12),_=_+G|0,j=ue(j^_,8),N=N+j|0,G=ue(G^N,7),O=O+M|0,P=ue(P^O,16),x=x+P|0,M=ue(M^x,12),O=O+M|0,P=ue(P^O,8),x=x+P|0,M=ue(M^x,7),D=D+z|0,Y=ue(Y^D,16),k=k+Y|0,z=ue(z^k,12),D=D+z|0,Y=ue(Y^D,8),k=k+Y|0,z=ue(z^k,7),C=C+Q|0,te=ue(te^C,16),F=F+te|0,Q=ue(Q^F,12),C=C+Q|0,te=ue(te^C,8),F=F+te|0,Q=ue(Q^F,7),_=_+M|0,te=ue(te^_,16),k=k+te|0,M=ue(M^k,12),_=_+M|0,te=ue(te^_,8),k=k+te|0,M=ue(M^k,7),O=O+z|0,j=ue(j^O,16),F=F+j|0,z=ue(z^F,12),O=O+z|0,j=ue(j^O,8),F=F+j|0,z=ue(z^F,7),D=D+Q|0,P=ue(P^D,16),N=N+P|0,Q=ue(Q^N,12),D=D+Q|0,P=ue(P^D,8),N=N+P|0,Q=ue(Q^N,7),C=C+G|0,Y=ue(Y^C,16),x=x+Y|0,G=ue(G^x,12),C=C+G|0,Y=ue(Y^C,8),x=x+Y|0,G=ue(G^x,7);let ie=0;r[ie++]=o+_|0,r[ie++]=a+O|0,r[ie++]=c+D|0,r[ie++]=l+C|0,r[ie++]=u+G|0,r[ie++]=d+M|0,r[ie++]=g+z|0,r[ie++]=m+Q|0,r[ie++]=y+N|0,r[ie++]=w+x|0,r[ie++]=f+k|0,r[ie++]=v+F|0,r[ie++]=b+j|0,r[ie++]=E+P|0,r[ie++]=S+Y|0,r[ie++]=R+te|0}const Th=Nh(Ph,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Oh=new Uint8Array(16),ko=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(Oh.subarray(s))},kh=new Uint8Array(32);function xo(t,e,s,r,i){const n=t(e,s,kh),o=_h.create(n);i&&ko(o,i),ko(o,r);const a=new Uint8Array(16),c=dh(a);To(c,0,BigInt(i?i.length:0),!0),To(c,8,BigInt(r.length),!0),o.update(a);const l=o.digest();return or(n,a),l}const xh=t=>(e,s,r)=>({encrypt(i,n){const o=i.length;n=Po(o+16,n,!1),n.set(i);const a=n.subarray(0,-16);t(e,s,a,a,1);const c=xo(t,e,s,a,r);return n.set(c,o),or(c),n},decrypt(i,n){n=Po(i.length-16,n,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=xo(t,e,s,o,r);if(!fh(a,c))throw new Error("invalid tag");return n.set(i.subarray(0,-16)),t(e,s,n,n,1),or(c),n}}),Ic=mh({blockSize:64,nonceLength:12,tagLength:16},xh(Th));let Nc=class extends Wn{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,qn(e);const r=nr(s);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,n=new Uint8Array(i);n.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return ir(this),this.iHash.update(e),this}digestInto(e){ir(this),Kr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:r,finished:i,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Ni=(t,e,s)=>new Nc(t,e).update(s).digest();Ni.create=(t,e)=>new Nc(t,e);function Rh(t,e,s){return qn(t),s===void 0&&(s=new Uint8Array(t.outputLen)),Ni(t,nr(s),nr(e))}const Bi=new Uint8Array([0]),Ro=new Uint8Array;function $h(t,e,s,r=32){if(qn(t),Br(r),r>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/t.outputLen);s===void 0&&(s=Ro);const n=new Uint8Array(i*t.outputLen),o=Ni.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<i;l++)Bi[0]=l+1,a.update(l===0?Ro:c).update(s).update(Bi).digestInto(c),n.set(c,t.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Bi.fill(0),n.slice(0,r)}const Uh=(t,e,s,r,i)=>$h(t,Rh(t,e,s),r,i);function Dh(t,e,s,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,r);const i=BigInt(32),n=BigInt(4294967295),o=Number(s>>i&n),a=Number(s&n),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function Lh(t,e,s){return t&e^~t&s}function Fh(t,e,s){return t&e^t&s^e&s}let Bh=class extends Wn{constructor(e,s,r,i){super(),this.blockLen=e,this.outputLen=s,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Li(this.buffer)}update(e){ir(this);const{view:s,buffer:r,blockLen:i}=this;e=nr(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(i-this.pos,n-o);if(a===i){const c=Li(e);for(;i<=n-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ir(this),dc(e,this),this.finished=!0;const{buffer:s,view:r,blockLen:i,isLE:n}=this;let{pos:o}=this;s[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let d=o;d<i;d++)s[d]=0;Dh(r,i-8,BigInt(this.length*8),n),this.process(r,0);const a=Li(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],n)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const r=e.slice(0,s);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:r,length:i,finished:n,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=n,e.destroyed=o,i%s&&e.buffer.set(r),e}};const Mh=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]),Qt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),es=new Uint32Array(64);class jh extends Bh{constructor(){super(64,32,8,!1),this.A=Qt[0]|0,this.B=Qt[1]|0,this.C=Qt[2]|0,this.D=Qt[3]|0,this.E=Qt[4]|0,this.F=Qt[5]|0,this.G=Qt[6]|0,this.H=Qt[7]|0}get(){const{A:e,B:s,C:r,D:i,E:n,F:o,G:a,H:c}=this;return[e,s,r,i,n,o,a,c]}set(e,s,r,i,n,o,a,c){this.A=e|0,this.B=s|0,this.C=r|0,this.D=i|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let d=0;d<16;d++,s+=4)es[d]=e.getUint32(s,!1);for(let d=16;d<64;d++){const g=es[d-15],m=es[d-2],y=Tt(g,7)^Tt(g,18)^g>>>3,w=Tt(m,17)^Tt(m,19)^m>>>10;es[d]=w+es[d-7]+y+es[d-16]|0}let{A:r,B:i,C:n,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const g=Tt(a,6)^Tt(a,11)^Tt(a,25),m=u+g+Lh(a,c,l)+Mh[d]+es[d]|0,y=(Tt(r,2)^Tt(r,13)^Tt(r,22))+Fh(r,i,n)|0;u=l,l=c,c=a,a=o+m|0,o=n,n=i,i=r,r=m+y|0}r=r+this.A|0,i=i+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,i,n,o,a,c,l,u)}roundClean(){es.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Vr=hc(()=>new jh);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ai=BigInt(0),Si=BigInt(1),qh=BigInt(2);function Ps(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Gr(t){if(!Ps(t))throw new Error("Uint8Array expected")}function ar(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Wh=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function cr(t){Gr(t);let e="";for(let s=0;s<t.length;s++)e+=Wh[t[s]];return e}function Xs(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Hn(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ai:BigInt("0x"+t)}const zt={_0:48,_9:57,A:65,F:70,a:97,f:102};function $o(t){if(t>=zt._0&&t<=zt._9)return t-zt._0;if(t>=zt.A&&t<=zt.F)return t-(zt.A-10);if(t>=zt.a&&t<=zt.f)return t-(zt.a-10)}function lr(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(s);for(let i=0,n=0;i<s;i++,n+=2){const o=$o(t.charCodeAt(n)),a=$o(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}r[i]=o*16+a}return r}function As(t){return Hn(cr(t))}function jr(t){return Gr(t),Hn(cr(Uint8Array.from(t).reverse()))}function ur(t,e){return lr(t.toString(16).padStart(e*2,"0"))}function _i(t,e){return ur(t,e).reverse()}function zh(t){return lr(Xs(t))}function dt(t,e,s){let r;if(typeof e=="string")try{r=lr(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(Ps(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof s=="number"&&i!==s)throw new Error(t+" of length "+s+" expected, got "+i);return r}function qr(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Gr(i),e+=i.length}const s=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const n=t[r];s.set(n,i),i+=n.length}return s}function Hh(t,e){if(t.length!==e.length)return!1;let s=0;for(let r=0;r<t.length;r++)s|=t[r]^e[r];return s===0}function Kh(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const Mi=t=>typeof t=="bigint"&&Ai<=t;function Pi(t,e,s){return Mi(t)&&Mi(e)&&Mi(s)&&e<=t&&t<s}function Gt(t,e,s,r){if(!Pi(e,s,r))throw new Error("expected valid "+t+": "+s+" <= n < "+r+", got "+e)}function Ac(t){let e;for(e=0;t>Ai;t>>=Si,e+=1);return e}function Vh(t,e){return t>>BigInt(e)&Si}function Gh(t,e,s){return t|(s?Si:Ai)<<BigInt(e)}const Kn=t=>(qh<<BigInt(t-1))-Si,ji=t=>new Uint8Array(t),Uo=t=>Uint8Array.from(t);function Sc(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");let r=ji(t),i=ji(t),n=0;const o=()=>{r.fill(1),i.fill(0),n=0},a=(...u)=>s(i,r,...u),c=(u=ji())=>{i=a(Uo([0]),u),r=a(),u.length!==0&&(i=a(Uo([1]),u),r=a())},l=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const d=[];for(;u<e;){r=a();const g=r.slice();d.push(g),u+=r.length}return qr(...d)};return(u,d)=>{o(),c(u);let g;for(;!(g=d(l()));)c();return o(),g}}const Jh={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Ps(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function fr(t,e,s={}){const r=(i,n,o)=>{const a=Jh[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+n+", got "+c)};for(const[i,n]of Object.entries(e))r(i,n,!1);for(const[i,n]of Object.entries(s))r(i,n,!0);return t}const Yh=()=>{throw new Error("not implemented")};function yn(t){const e=new WeakMap;return(s,...r)=>{const i=e.get(s);if(i!==void 0)return i;const n=t(s,...r);return e.set(s,n),n}}var Xh=Object.freeze({__proto__:null,isBytes:Ps,abytes:Gr,abool:ar,bytesToHex:cr,numberToHexUnpadded:Xs,hexToNumber:Hn,hexToBytes:lr,bytesToNumberBE:As,bytesToNumberLE:jr,numberToBytesBE:ur,numberToBytesLE:_i,numberToVarBytesBE:zh,ensureBytes:dt,concatBytes:qr,equalBytes:Hh,utf8ToBytes:Kh,inRange:Pi,aInRange:Gt,bitLen:Ac,bitGet:Vh,bitSet:Gh,bitMask:Kn,createHmacDrbg:Sc,validateObject:fr,notImplemented:Yh,memoized:yn});const We=BigInt(0),Te=BigInt(1),vs=BigInt(2),Zh=BigInt(3),bn=BigInt(4),Do=BigInt(5),Lo=BigInt(8);function ot(t,e){const s=t%e;return s>=We?s:e+s}function _c(t,e,s){if(e<We)throw new Error("invalid exponent, negatives unsupported");if(s<=We)throw new Error("invalid modulus");if(s===Te)return We;let r=Te;for(;e>We;)e&Te&&(r=r*t%s),t=t*t%s,e>>=Te;return r}function St(t,e,s){let r=t;for(;e-- >We;)r*=r,r%=s;return r}function vn(t,e){if(t===We)throw new Error("invert: expected non-zero number");if(e<=We)throw new Error("invert: expected positive modulus, got "+e);let s=ot(t,e),r=e,i=We,n=Te;for(;s!==We;){const o=r/s,a=r%s,c=i-n*o;r=s,s=a,i=n,n=c}if(r!==Te)throw new Error("invert: does not exist");return ot(i,e)}function Qh(t){const e=(t-Te)/vs;let s,r,i;for(s=t-Te,r=0;s%vs===We;s/=vs,r++);for(i=vs;i<t&&_c(i,e,t)!==t-Te;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+Te)/bn;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const n=(s+Te)/vs;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,l=o.pow(o.mul(o.ONE,i),s),u=o.pow(a,n),d=o.pow(a,s);for(;!o.eql(d,o.ONE);){if(o.eql(d,o.ZERO))return o.ZERO;let g=1;for(let y=o.sqr(d);g<c&&!o.eql(y,o.ONE);g++)y=o.sqr(y);const m=o.pow(l,Te<<BigInt(c-g-1));l=o.sqr(m),u=o.mul(u,m),d=o.mul(d,l),c=g}return u}}function ep(t){if(t%bn===Zh){const e=(t+Te)/bn;return function(s,r){const i=s.pow(r,e);if(!s.eql(s.sqr(i),r))throw new Error("Cannot find square root");return i}}if(t%Lo===Do){const e=(t-Do)/Lo;return function(s,r){const i=s.mul(r,vs),n=s.pow(i,e),o=s.mul(r,n),a=s.mul(s.mul(o,vs),n),c=s.mul(o,s.sub(a,s.ONE));if(!s.eql(s.sqr(c),r))throw new Error("Cannot find square root");return c}}return Qh(t)}const tp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function sp(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},s=tp.reduce((r,i)=>(r[i]="function",r),e);return fr(t,s)}function rp(t,e,s){if(s<We)throw new Error("invalid exponent, negatives unsupported");if(s===We)return t.ONE;if(s===Te)return e;let r=t.ONE,i=e;for(;s>We;)s&Te&&(r=t.mul(r,i)),i=t.sqr(i),s>>=Te;return r}function ip(t,e){const s=new Array(e.length),r=e.reduce((n,o,a)=>t.is0(o)?n:(s[a]=n,t.mul(n,o)),t.ONE),i=t.inv(r);return e.reduceRight((n,o,a)=>t.is0(o)?n:(s[a]=t.mul(n,s[a]),t.mul(n,o)),i),s}function Pc(t,e){const s=e!==void 0?e:t.toString(2).length,r=Math.ceil(s/8);return{nBitLength:s,nByteLength:r}}function Tc(t,e,s=!1,r={}){if(t<=We)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:n}=Pc(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:s,BITS:i,BYTES:n,MASK:Kn(i),ZERO:We,ONE:Te,create:c=>ot(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return We<=c&&c<t},is0:c=>c===We,isOdd:c=>(c&Te)===Te,neg:c=>ot(-c,t),eql:(c,l)=>c===l,sqr:c=>ot(c*c,t),add:(c,l)=>ot(c+l,t),sub:(c,l)=>ot(c-l,t),mul:(c,l)=>ot(c*l,t),pow:(c,l)=>rp(a,c,l),div:(c,l)=>ot(c*vn(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>vn(c,t),sqrt:r.sqrt||(c=>(o||(o=ep(t)),o(a,c))),invertBatch:c=>ip(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>s?_i(c,n):ur(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return s?jr(c):As(c)}});return Object.freeze(a)}function Oc(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function kc(t){const e=Oc(t);return e+Math.ceil(e/2)}function np(t,e,s=!1){const r=t.length,i=Oc(e),n=kc(e);if(r<16||r<n||r>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+r);const o=s?jr(t):As(t),a=ot(o,e-Te)+Te;return s?_i(a,i):ur(a,i)}const Fo=BigInt(0),ri=BigInt(1);function qi(t,e){const s=e.negate();return t?s:e}function xc(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Wi(t,e){xc(t,e);const s=Math.ceil(e/t)+1,r=2**(t-1);return{windows:s,windowSize:r}}function op(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,r)=>{if(!(s instanceof e))throw new Error("invalid point at index "+r)})}function ap(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,r)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+r)})}const zi=new WeakMap,Rc=new WeakMap;function Hi(t){return Rc.get(t)||1}function cp(t,e){return{constTimeNegate:qi,hasPrecomputes(s){return Hi(s)!==1},unsafeLadder(s,r,i=t.ZERO){let n=s;for(;r>Fo;)r&ri&&(i=i.add(n)),n=n.double(),r>>=ri;return i},precomputeWindow(s,r){const{windows:i,windowSize:n}=Wi(r,e),o=[];let a=s,c=a;for(let l=0;l<i;l++){c=a,o.push(c);for(let u=1;u<n;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(s,r,i){const{windows:n,windowSize:o}=Wi(s,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**s-1),u=2**s,d=BigInt(s);for(let g=0;g<n;g++){const m=g*o;let y=Number(i&l);i>>=d,y>o&&(y-=u,i+=ri);const w=m,f=m+Math.abs(y)-1,v=g%2!==0,b=y<0;y===0?c=c.add(qi(v,r[w])):a=a.add(qi(b,r[f]))}return{p:a,f:c}},wNAFUnsafe(s,r,i,n=t.ZERO){const{windows:o,windowSize:a}=Wi(s,e),c=BigInt(2**s-1),l=2**s,u=BigInt(s);for(let d=0;d<o;d++){const g=d*a;if(i===Fo)break;let m=Number(i&c);if(i>>=u,m>a&&(m-=l,i+=ri),m===0)continue;let y=r[g+Math.abs(m)-1];m<0&&(y=y.negate()),n=n.add(y)}return n},getPrecomputes(s,r,i){let n=zi.get(r);return n||(n=this.precomputeWindow(r,s),s!==1&&zi.set(r,i(n))),n},wNAFCached(s,r,i){const n=Hi(s);return this.wNAF(n,this.getPrecomputes(n,s,i),r)},wNAFCachedUnsafe(s,r,i,n){const o=Hi(s);return o===1?this.unsafeLadder(s,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,s,i),r,n)},setWindowSize(s,r){xc(r,e),Rc.set(s,r),zi.delete(s)}}}function lp(t,e,s,r){if(op(s,t),ap(r,e),s.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,n=Ac(BigInt(s.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),l=Math.floor((e.BITS-1)/o)*o;let u=i;for(let d=l;d>=0;d-=o){c.fill(i);for(let m=0;m<r.length;m++){const y=r[m],w=Number(y>>BigInt(d)&BigInt(a));c[w]=c[w].add(s[m])}let g=i;for(let m=c.length-1,y=i;m>0;m--)y=y.add(c[m]),g=g.add(y);if(u=u.add(g),d!==0)for(let m=0;m<o;m++)u=u.double()}return u}function $c(t){return sp(t.Fp),fr(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Pc(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const $s=BigInt(0),Ki=BigInt(1);function up(t){return fr(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function dp(t){const e=up(t),{P:s}=e,r=b=>ot(b,s),i=e.montgomeryBits,n=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(b=>b),c=e.powPminus2||(b=>_c(b,s-BigInt(2),s));function l(b,E,S){const R=r(b*(E-S));return E=r(E-R),S=r(S+R),[E,S]}const u=(e.a-BigInt(2))/BigInt(4);function d(b,E){Gt("u",b,$s,s),Gt("scalar",E,$s,s);const S=E,R=b;let _=Ki,O=$s,D=b,C=Ki,G=$s,M;for(let Q=BigInt(i-1);Q>=$s;Q--){const N=S>>Q&Ki;G^=N,M=l(G,_,D),_=M[0],D=M[1],M=l(G,O,C),O=M[0],C=M[1],G=N;const x=_+O,k=r(x*x),F=_-O,j=r(F*F),P=k-j,Y=D+C,te=D-C,ie=r(te*x),Ie=r(Y*F),ge=ie+Ie,Oe=ie-Ie;D=r(ge*ge),C=r(R*r(Oe*Oe)),_=r(k*j),O=r(P*(k+r(u*P)))}M=l(G,_,D),_=M[0],D=M[1],M=l(G,O,C),O=M[0],C=M[1];const z=c(O);return r(_*z)}function g(b){return _i(r(b),n)}function m(b){const E=dt("u coordinate",b,n);return o===32&&(E[31]&=127),jr(E)}function y(b){const E=dt("scalar",b),S=E.length;if(S!==n&&S!==o){let R=""+n+" or "+o;throw new Error("invalid scalar, expected "+R+" bytes, got "+S)}return jr(a(E))}function w(b,E){const S=m(E),R=y(b),_=d(S,R);if(_===$s)throw new Error("invalid private or public key received");return g(_)}const f=g(e.Gu);function v(b){return w(b,f)}return{scalarMult:w,scalarMultBase:v,getSharedSecret:(b,E)=>w(b,E),getPublicKey:b=>v(b),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:f}}const En=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const hp=BigInt(1),Bo=BigInt(2),pp=BigInt(3),gp=BigInt(5);BigInt(8);function fp(t){const e=BigInt(10),s=BigInt(20),r=BigInt(40),i=BigInt(80),n=En,o=t*t%n*t%n,a=St(o,Bo,n)*o%n,c=St(a,hp,n)*t%n,l=St(c,gp,n)*c%n,u=St(l,e,n)*l%n,d=St(u,s,n)*u%n,g=St(d,r,n)*d%n,m=St(g,i,n)*g%n,y=St(m,i,n)*g%n,w=St(y,e,n)*l%n;return{pow_p_5_8:St(w,Bo,n)*t%n,b2:o}}function mp(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Cn=dp({P:En,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=En,{pow_p_5_8:s,b2:r}=fp(t);return ot(St(s,pp,e)*r,e)},adjustScalarBytes:mp,randomBytes:gr});function Mo(t){t.lowS!==void 0&&ar("lowS",t.lowS),t.prehash!==void 0&&ar("prehash",t.prehash)}function wp(t){const e=$c(t);fr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:s,Fp:r,a:i}=e;if(s){if(!r.eql(i,r.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof s!="object"||typeof s.beta!="bigint"||typeof s.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:yp,hexToBytes:bp}=Xh;class vp extends Error{constructor(e=""){super(e)}}const Kt={Err:vp,_tlv:{encode:(t,e)=>{const{Err:s}=Kt;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const r=e.length/2,i=Xs(r);if(i.length/2&128)throw new s("tlv.encode: long form length too big");const n=r>127?Xs(i.length/2|128):"";return Xs(t)+n+i+e},decode(t,e){const{Err:s}=Kt;let r=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new s("tlv.decode: wrong tlv");const i=e[r++],n=!!(i&128);let o=0;if(!n)o=i;else{const c=i&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(r+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=Kt;if(t<Vt)throw new e("integer: negative integers are not allowed");let s=Xs(t);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(t){const{Err:e}=Kt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return yp(t)}},toSig(t){const{Err:e,_int:s,_tlv:r}=Kt,i=typeof t=="string"?bp(t):t;Gr(i);const{v:n,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,n),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(t){const{_tlv:e,_int:s}=Kt,r=e.encode(2,s.encode(t.r)),i=e.encode(2,s.encode(t.s)),n=r+i;return e.encode(48,n)}},Vt=BigInt(0),je=BigInt(1);BigInt(2);const jo=BigInt(3);BigInt(4);function Ep(t){const e=wp(t),{Fp:s}=e,r=Tc(e.n,e.nBitLength),i=e.toBytes||((w,f,v)=>{const b=f.toAffine();return qr(Uint8Array.from([4]),s.toBytes(b.x),s.toBytes(b.y))}),n=e.fromBytes||(w=>{const f=w.subarray(1),v=s.fromBytes(f.subarray(0,s.BYTES)),b=s.fromBytes(f.subarray(s.BYTES,2*s.BYTES));return{x:v,y:b}});function o(w){const{a:f,b:v}=e,b=s.sqr(w),E=s.mul(b,w);return s.add(s.add(E,s.mul(w,f)),v)}if(!s.eql(s.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(w){return Pi(w,je,e.n)}function c(w){const{allowedPrivateKeyLengths:f,nByteLength:v,wrapPrivateKey:b,n:E}=e;if(f&&typeof w!="bigint"){if(Ps(w)&&(w=cr(w)),typeof w!="string"||!f.includes(w.length))throw new Error("invalid private key");w=w.padStart(v*2,"0")}let S;try{S=typeof w=="bigint"?w:As(dt("private key",w,v))}catch{throw new Error("invalid private key, expected hex or "+v+" bytes, got "+typeof w)}return b&&(S=ot(S,E)),Gt("private key",S,je,E),S}function l(w){if(!(w instanceof g))throw new Error("ProjectivePoint expected")}const u=yn((w,f)=>{const{px:v,py:b,pz:E}=w;if(s.eql(E,s.ONE))return{x:v,y:b};const S=w.is0();f==null&&(f=S?s.ONE:s.inv(E));const R=s.mul(v,f),_=s.mul(b,f),O=s.mul(E,f);if(S)return{x:s.ZERO,y:s.ZERO};if(!s.eql(O,s.ONE))throw new Error("invZ was invalid");return{x:R,y:_}}),d=yn(w=>{if(w.is0()){if(e.allowInfinityPoint&&!s.is0(w.py))return;throw new Error("bad point: ZERO")}const{x:f,y:v}=w.toAffine();if(!s.isValid(f)||!s.isValid(v))throw new Error("bad point: x or y not FE");const b=s.sqr(v),E=o(f);if(!s.eql(b,E))throw new Error("bad point: equation left != right");if(!w.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(f,v,b){if(this.px=f,this.py=v,this.pz=b,f==null||!s.isValid(f))throw new Error("x required");if(v==null||!s.isValid(v))throw new Error("y required");if(b==null||!s.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(f){const{x:v,y:b}=f||{};if(!f||!s.isValid(v)||!s.isValid(b))throw new Error("invalid affine point");if(f instanceof g)throw new Error("projective point not allowed");const E=S=>s.eql(S,s.ZERO);return E(v)&&E(b)?g.ZERO:new g(v,b,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const v=s.invertBatch(f.map(b=>b.pz));return f.map((b,E)=>b.toAffine(v[E])).map(g.fromAffine)}static fromHex(f){const v=g.fromAffine(n(dt("pointHex",f)));return v.assertValidity(),v}static fromPrivateKey(f){return g.BASE.multiply(c(f))}static msm(f,v){return lp(g,r,f,v)}_setWindowSize(f){y.setWindowSize(this,f)}assertValidity(){d(this)}hasEvenY(){const{y:f}=this.toAffine();if(s.isOdd)return!s.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){l(f);const{px:v,py:b,pz:E}=this,{px:S,py:R,pz:_}=f,O=s.eql(s.mul(v,_),s.mul(S,E)),D=s.eql(s.mul(b,_),s.mul(R,E));return O&&D}negate(){return new g(this.px,s.neg(this.py),this.pz)}double(){const{a:f,b:v}=e,b=s.mul(v,jo),{px:E,py:S,pz:R}=this;let _=s.ZERO,O=s.ZERO,D=s.ZERO,C=s.mul(E,E),G=s.mul(S,S),M=s.mul(R,R),z=s.mul(E,S);return z=s.add(z,z),D=s.mul(E,R),D=s.add(D,D),_=s.mul(f,D),O=s.mul(b,M),O=s.add(_,O),_=s.sub(G,O),O=s.add(G,O),O=s.mul(_,O),_=s.mul(z,_),D=s.mul(b,D),M=s.mul(f,M),z=s.sub(C,M),z=s.mul(f,z),z=s.add(z,D),D=s.add(C,C),C=s.add(D,C),C=s.add(C,M),C=s.mul(C,z),O=s.add(O,C),M=s.mul(S,R),M=s.add(M,M),C=s.mul(M,z),_=s.sub(_,C),D=s.mul(M,G),D=s.add(D,D),D=s.add(D,D),new g(_,O,D)}add(f){l(f);const{px:v,py:b,pz:E}=this,{px:S,py:R,pz:_}=f;let O=s.ZERO,D=s.ZERO,C=s.ZERO;const G=e.a,M=s.mul(e.b,jo);let z=s.mul(v,S),Q=s.mul(b,R),N=s.mul(E,_),x=s.add(v,b),k=s.add(S,R);x=s.mul(x,k),k=s.add(z,Q),x=s.sub(x,k),k=s.add(v,E);let F=s.add(S,_);return k=s.mul(k,F),F=s.add(z,N),k=s.sub(k,F),F=s.add(b,E),O=s.add(R,_),F=s.mul(F,O),O=s.add(Q,N),F=s.sub(F,O),C=s.mul(G,k),O=s.mul(M,N),C=s.add(O,C),O=s.sub(Q,C),C=s.add(Q,C),D=s.mul(O,C),Q=s.add(z,z),Q=s.add(Q,z),N=s.mul(G,N),k=s.mul(M,k),Q=s.add(Q,N),N=s.sub(z,N),N=s.mul(G,N),k=s.add(k,N),z=s.mul(Q,k),D=s.add(D,z),z=s.mul(F,k),O=s.mul(x,O),O=s.sub(O,z),z=s.mul(x,Q),C=s.mul(F,C),C=s.add(C,z),new g(O,D,C)}subtract(f){return this.add(f.negate())}is0(){return this.equals(g.ZERO)}wNAF(f){return y.wNAFCached(this,f,g.normalizeZ)}multiplyUnsafe(f){const{endo:v,n:b}=e;Gt("scalar",f,Vt,b);const E=g.ZERO;if(f===Vt)return E;if(this.is0()||f===je)return this;if(!v||y.hasPrecomputes(this))return y.wNAFCachedUnsafe(this,f,g.normalizeZ);let{k1neg:S,k1:R,k2neg:_,k2:O}=v.splitScalar(f),D=E,C=E,G=this;for(;R>Vt||O>Vt;)R&je&&(D=D.add(G)),O&je&&(C=C.add(G)),G=G.double(),R>>=je,O>>=je;return S&&(D=D.negate()),_&&(C=C.negate()),C=new g(s.mul(C.px,v.beta),C.py,C.pz),D.add(C)}multiply(f){const{endo:v,n:b}=e;Gt("scalar",f,je,b);let E,S;if(v){const{k1neg:R,k1:_,k2neg:O,k2:D}=v.splitScalar(f);let{p:C,f:G}=this.wNAF(_),{p:M,f:z}=this.wNAF(D);C=y.constTimeNegate(R,C),M=y.constTimeNegate(O,M),M=new g(s.mul(M.px,v.beta),M.py,M.pz),E=C.add(M),S=G.add(z)}else{const{p:R,f:_}=this.wNAF(f);E=R,S=_}return g.normalizeZ([E,S])[0]}multiplyAndAddUnsafe(f,v,b){const E=g.BASE,S=(_,O)=>O===Vt||O===je||!_.equals(E)?_.multiplyUnsafe(O):_.multiply(O),R=S(this,v).add(S(f,b));return R.is0()?void 0:R}toAffine(f){return u(this,f)}isTorsionFree(){const{h:f,isTorsionFree:v}=e;if(f===je)return!0;if(v)return v(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:v}=e;return f===je?this:v?v(g,this):this.multiplyUnsafe(e.h)}toRawBytes(f=!0){return ar("isCompressed",f),this.assertValidity(),i(g,this,f)}toHex(f=!0){return ar("isCompressed",f),cr(this.toRawBytes(f))}}g.BASE=new g(e.Gx,e.Gy,s.ONE),g.ZERO=new g(s.ZERO,s.ONE,s.ZERO);const m=e.nBitLength,y=cp(g,e.endo?Math.ceil(m/2):m);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Cp(t){const e=$c(t);return fr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Ip(t){const e=Cp(t),{Fp:s,n:r}=e,i=s.BYTES+1,n=2*s.BYTES+1;function o(N){return ot(N,r)}function a(N){return vn(N,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:d}=Ep({...e,toBytes(N,x,k){const F=x.toAffine(),j=s.toBytes(F.x),P=qr;return ar("isCompressed",k),k?P(Uint8Array.from([x.hasEvenY()?2:3]),j):P(Uint8Array.from([4]),j,s.toBytes(F.y))},fromBytes(N){const x=N.length,k=N[0],F=N.subarray(1);if(x===i&&(k===2||k===3)){const j=As(F);if(!Pi(j,je,s.ORDER))throw new Error("Point is not on curve");const P=u(j);let Y;try{Y=s.sqrt(P)}catch(ie){const Ie=ie instanceof Error?": "+ie.message:"";throw new Error("Point is not on curve"+Ie)}const te=(Y&je)===je;return(k&1)===1!==te&&(Y=s.neg(Y)),{x:j,y:Y}}else if(x===n&&k===4){const j=s.fromBytes(F.subarray(0,s.BYTES)),P=s.fromBytes(F.subarray(s.BYTES,2*s.BYTES));return{x:j,y:P}}else{const j=i,P=n;throw new Error("invalid Point, expected length of "+j+", or uncompressed "+P+", got "+x)}}}),g=N=>cr(ur(N,e.nByteLength));function m(N){const x=r>>je;return N>x}function y(N){return m(N)?o(-N):N}const w=(N,x,k)=>As(N.slice(x,k));class f{constructor(x,k,F){this.r=x,this.s=k,this.recovery=F,this.assertValidity()}static fromCompact(x){const k=e.nByteLength;return x=dt("compactSignature",x,k*2),new f(w(x,0,k),w(x,k,2*k))}static fromDER(x){const{r:k,s:F}=Kt.toSig(dt("DER",x));return new f(k,F)}assertValidity(){Gt("r",this.r,je,r),Gt("s",this.s,je,r)}addRecoveryBit(x){return new f(this.r,this.s,x)}recoverPublicKey(x){const{r:k,s:F,recovery:j}=this,P=_(dt("msgHash",x));if(j==null||![0,1,2,3].includes(j))throw new Error("recovery id invalid");const Y=j===2||j===3?k+e.n:k;if(Y>=s.ORDER)throw new Error("recovery id 2 or 3 invalid");const te=j&1?"03":"02",ie=c.fromHex(te+g(Y)),Ie=a(Y),ge=o(-P*Ie),Oe=o(F*Ie),Fe=c.BASE.multiplyAndAddUnsafe(ie,ge,Oe);if(!Fe)throw new Error("point at infinify");return Fe.assertValidity(),Fe}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return lr(this.toDERHex())}toDERHex(){return Kt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return lr(this.toCompactHex())}toCompactHex(){return g(this.r)+g(this.s)}}const v={isValidPrivateKey(N){try{return l(N),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const N=kc(e.n);return np(e.randomBytes(N),e.n)},precompute(N=8,x=c.BASE){return x._setWindowSize(N),x.multiply(BigInt(3)),x}};function b(N,x=!0){return c.fromPrivateKey(N).toRawBytes(x)}function E(N){const x=Ps(N),k=typeof N=="string",F=(x||k)&&N.length;return x?F===i||F===n:k?F===2*i||F===2*n:N instanceof c}function S(N,x,k=!0){if(E(N))throw new Error("first arg must be private key");if(!E(x))throw new Error("second arg must be public key");return c.fromHex(x).multiply(l(N)).toRawBytes(k)}const R=e.bits2int||function(N){if(N.length>8192)throw new Error("input is too large");const x=As(N),k=N.length*8-e.nBitLength;return k>0?x>>BigInt(k):x},_=e.bits2int_modN||function(N){return o(R(N))},O=Kn(e.nBitLength);function D(N){return Gt("num < 2^"+e.nBitLength,N,Vt,O),ur(N,e.nByteLength)}function C(N,x,k=G){if(["recovered","canonical"].some(Re=>Re in k))throw new Error("sign() legacy options not supported");const{hash:F,randomBytes:j}=e;let{lowS:P,prehash:Y,extraEntropy:te}=k;P==null&&(P=!0),N=dt("msgHash",N),Mo(k),Y&&(N=dt("prehashed msgHash",F(N)));const ie=_(N),Ie=l(x),ge=[D(Ie),D(ie)];if(te!=null&&te!==!1){const Re=te===!0?j(s.BYTES):te;ge.push(dt("extraEntropy",Re))}const Oe=qr(...ge),Fe=ie;function Je(Re){const $e=R(Re);if(!d($e))return;const gs=a($e),Ft=c.BASE.multiply($e).toAffine(),Pt=o(Ft.x);if(Pt===Vt)return;const Bt=o(gs*o(Fe+Pt*Ie));if(Bt===Vt)return;let Mt=(Ft.x===Pt?0:2)|Number(Ft.y&je),Qr=Bt;return P&&m(Bt)&&(Qr=y(Bt),Mt^=1),new f(Pt,Qr,Mt)}return{seed:Oe,k2sig:Je}}const G={lowS:e.lowS,prehash:!1},M={lowS:e.lowS,prehash:!1};function z(N,x,k=G){const{seed:F,k2sig:j}=C(N,x,k),P=e;return Sc(P.hash.outputLen,P.nByteLength,P.hmac)(F,j)}c.BASE._setWindowSize(8);function Q(N,x,k,F=M){var Bt;const j=N;x=dt("msgHash",x),k=dt("publicKey",k);const{lowS:P,prehash:Y,format:te}=F;if(Mo(F),"strict"in F)throw new Error("options.strict was renamed to lowS");if(te!==void 0&&te!=="compact"&&te!=="der")throw new Error("format must be compact or der");const ie=typeof j=="string"||Ps(j),Ie=!ie&&!te&&typeof j=="object"&&j!==null&&typeof j.r=="bigint"&&typeof j.s=="bigint";if(!ie&&!Ie)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let ge,Oe;try{if(Ie&&(ge=new f(j.r,j.s)),ie){try{te!=="compact"&&(ge=f.fromDER(j))}catch(Mt){if(!(Mt instanceof Kt.Err))throw Mt}!ge&&te!=="der"&&(ge=f.fromCompact(j))}Oe=c.fromHex(k)}catch{return!1}if(!ge||P&&ge.hasHighS())return!1;Y&&(x=e.hash(x));const{r:Fe,s:Je}=ge,Re=_(x),$e=a(Je),gs=o(Re*$e),Ft=o(Fe*$e),Pt=(Bt=c.BASE.multiplyAndAddUnsafe(Oe,gs,Ft))==null?void 0:Bt.toAffine();return Pt?o(Pt.x)===Fe:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:S,sign:z,verify:Q,ProjectivePoint:c,Signature:f,utils:v}}function Np(t){return{hash:t,hmac:(e,...s)=>Ni(t,e,Pd(...s)),randomBytes:gr}}function Ap(t,e){const s=r=>Ip({...t,...Np(r)});return{...s(e),create:s}}const Uc=Tc(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Sp=Uc.create(BigInt("-3")),_p=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Pp=Ap({a:Sp,b:_p,Fp:Uc,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Vr),Dc="base10",Ze="base16",_t="base64pad",is="base64url",Jr="utf8",Lc=0,Jt=1,Yr=2,Tp=0,qo=1,Rr=12,Vn=32;function Op(){const t=Cn.utils.randomPrivateKey(),e=Cn.getPublicKey(t);return{privateKey:h.toString(t,Ze),publicKey:h.toString(e,Ze)}}function In(){const t=gr(Vn);return h.toString(t,Ze)}function kp(t,e){const s=Cn.getSharedSecret(h.fromString(t,Ze),h.fromString(e,Ze)),r=Uh(Vr,s,void 0,void 0,Vn);return h.toString(r,Ze)}function pi(t){const e=Vr(h.fromString(t,Ze));return h.toString(e,Ze)}function $t(t){const e=Vr(h.fromString(t,Jr));return h.toString(e,Ze)}function Fc(t){return h.fromString(`${t}`,Dc)}function Ts(t){return Number(h.toString(t,Dc))}function Bc(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Mc(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function xp(t){const e=Fc(typeof t.type<"u"?t.type:Lc);if(Ts(e)===Jt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?h.fromString(t.senderPublicKey,Ze):void 0,r=typeof t.iv<"u"?h.fromString(t.iv,Ze):gr(Rr),i=h.fromString(t.symKey,Ze),n=Ic(i,r).encrypt(h.fromString(t.message,Jr)),o=jc({type:e,sealed:n,iv:r,senderPublicKey:s});return t.encoding===is?Bc(o):o}function Rp(t){const e=h.fromString(t.symKey,Ze),{sealed:s,iv:r}=Wr({encoded:t.encoded,encoding:t.encoding}),i=Ic(e,r).decrypt(s);if(i===null)throw new Error("Failed to decrypt");return h.toString(i,Jr)}function $p(t,e){const s=Fc(Yr),r=gr(Rr),i=h.fromString(t,Jr),n=jc({type:s,sealed:i,iv:r});return e===is?Bc(n):n}function Up(t,e){const{sealed:s}=Wr({encoded:t,encoding:e});return h.toString(s,Jr)}function jc(t){if(Ts(t.type)===Yr)return h.toString(h.concat([t.type,t.sealed]),_t);if(Ts(t.type)===Jt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return h.toString(h.concat([t.type,t.senderPublicKey,t.iv,t.sealed]),_t)}return h.toString(h.concat([t.type,t.iv,t.sealed]),_t)}function Wr(t){const e=(t.encoding||_t)===is?Mc(t.encoded):t.encoded,s=h.fromString(e,_t),r=s.slice(Tp,qo),i=qo;if(Ts(r)===Jt){const c=i+Vn,l=c+Rr,u=s.slice(i,c),d=s.slice(c,l),g=s.slice(l);return{type:r,sealed:g,iv:d,senderPublicKey:u}}if(Ts(r)===Yr){const c=s.slice(i),l=gr(Rr);return{type:r,sealed:c,iv:l}}const n=i+Rr,o=s.slice(i,n),a=s.slice(n);return{type:r,sealed:a,iv:o}}function Dp(t,e){const s=Wr({encoded:t,encoding:e==null?void 0:e.encoding});return qc({type:Ts(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?h.toString(s.senderPublicKey,Ze):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function qc(t){const e=(t==null?void 0:t.type)||Lc;if(e===Jt){if(typeof(t==null?void 0:t.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(t==null?void 0:t.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t==null?void 0:t.senderPublicKey,receiverPublicKey:t==null?void 0:t.receiverPublicKey}}function Wo(t){return t.type===Jt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function zo(t){return t.type===Yr}function Lp(t){const e=U.dist.Buffer.from(t.x,"base64"),s=U.dist.Buffer.from(t.y,"base64");return h.concat([new Uint8Array([4]),e,s])}function Fp(t,e){const[s,r,i]=t.split("."),n=U.dist.Buffer.from(Mc(i),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${s}.${r}`,l=Vr(c),u=Lp(e);if(!Pp.verify(h.concat([o,a]),l,u))throw new Error("Invalid signature");return h.sn(t).payload}const Bp="irn";function bi(t){return(t==null?void 0:t.relay)||{protocol:Bp}}function _r(t){const e=h.C[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function Mp(t,e="-"){const s={},r="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(r)){const n=i.replace(r,""),o=t[i];s[n]=o}}),s}function Ho(t){if(!t.includes("wc:")){const l=uc(t);l!=null&&l.includes("wc:")&&(t=l)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),s=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),i=t.substring(e+1,s).split("@"),n=typeof s<"u"?t.substring(s):"",o=new URLSearchParams(n),a={};o.forEach((l,u)=>{a[u]=l});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:jp(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:Mp(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function jp(t){return t.startsWith("//")?t.substring(2):t}function qp(t,e="-"){const s="relay",r={};return Object.keys(t).forEach(i=>{const n=i,o=s+e+n;t[n]&&(r[o]=t[n])}),r}function Ko(t){const e=new URLSearchParams,s=qp(t.relay);Object.keys(s).sort().forEach(i=>{e.set(i,s[i])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const r=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${r}`}function ii(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var Wp=Object.defineProperty,zp=Object.defineProperties,Hp=Object.getOwnPropertyDescriptors,Vo=Object.getOwnPropertySymbols,Kp=Object.prototype.hasOwnProperty,Vp=Object.prototype.propertyIsEnumerable,Go=(t,e,s)=>e in t?Wp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Gp=(t,e)=>{for(var s in e||(e={}))Kp.call(e,s)&&Go(t,s,e[s]);if(Vo)for(var s of Vo(e))Vp.call(e,s)&&Go(t,s,e[s]);return t},Jp=(t,e)=>zp(t,Hp(e));function mr(t){const e=[];return t.forEach(s=>{const[r,i]=s.split(":");e.push(`${r}:${i}`)}),e}function Yp(t){const e=[];return Object.values(t).forEach(s=>{e.push(...mr(s.accounts))}),e}function Xp(t,e){const s=[];return Object.values(t).forEach(r=>{mr(r.accounts).includes(e)&&s.push(...r.methods)}),s}function Zp(t,e){const s=[];return Object.values(t).forEach(r=>{mr(r.accounts).includes(e)&&s.push(...r.events)}),s}function Ti(t){return t.includes(":")}function Zs(t){return Ti(t)?t.split(":")[0]:t}function Jo(t){var e,s,r;const i={};if(!us(t))return i;for(const[n,o]of Object.entries(t)){const a=Ti(n)?[n]:o.chains,c=o.methods||[],l=o.events||[],u=Zs(n);i[u]=Jp(Gp({},i[u]),{chains:Ut(a,(e=i[u])==null?void 0:e.chains),methods:Ut(c,(s=i[u])==null?void 0:s.methods),events:Ut(l,(r=i[u])==null?void 0:r.events)})}return i}function Qp(t){const e={};return t==null||t.forEach(s=>{var r;const[i,n]=s.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(s),(r=e[i].chains)==null||r.push(`${i}:${n}`)}),e}function Yo(t,e){e=e.map(r=>r.replace("did:pkh:",""));const s=Qp(e);for(const[r,i]of Object.entries(s))i.methods?i.methods=Ut(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return s}function eg(t,e){var s,r,i,n,o,a;const c=Jo(t),l=Jo(e),u={},d=Object.keys(c).concat(Object.keys(l));for(const g of d)u[g]={chains:Ut((s=c[g])==null?void 0:s.chains,(r=l[g])==null?void 0:r.chains),methods:Ut((i=c[g])==null?void 0:i.methods,(n=l[g])==null?void 0:n.methods),events:Ut((o=c[g])==null?void 0:o.events,(a=l[g])==null?void 0:a.events)};return u}const tg={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}},sg={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 $(t,e){const{message:s,code:r}=sg[t];return{message:e?`${s} ${e}`:s,code:r}}function ye(t,e){const{message:s,code:r}=tg[t];return{message:e?`${s} ${e}`:s,code:r}}function ls(t,e){return!!Array.isArray(t)}function us(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Ve(t){return typeof t>"u"}function xe(t,e){return e&&Ve(t)?!0:typeof t=="string"&&!!t.trim().length}function Gn(t,e){return e&&Ve(t)?!0:typeof t=="number"&&!isNaN(t)}function rg(t,e){const{requiredNamespaces:s}=e,r=Object.keys(t.namespaces),i=Object.keys(s);let n=!0;return Ns(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],u=mr(a),d=s[o];(!Ns(nc(o,d),u)||!Ns(d.methods,c)||!Ns(d.events,l))&&(n=!1)}),n):!1}function vi(t){return xe(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function ig(t){if(xe(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&vi(s)}}return!1}function ng(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(xe(t,!1)){if(e(t))return!0;const s=uc(t);return e(s)}}catch{}return!1}function og(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function ag(t){return t==null?void 0:t.topic}function cg(t,e){let s=null;return xe(t==null?void 0:t.publicKey,!1)||(s=$("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function Xo(t){let e=!0;return ls(t)?t.length&&(e=t.every(s=>xe(s,!1))):e=!1,e}function lg(t,e,s){let r=null;return ls(e)&&e.length?e.forEach(i=>{r||vi(i)||(r=ye("UNSUPPORTED_CHAINS",`${s}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):vi(t)||(r=ye("UNSUPPORTED_CHAINS",`${s}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function ug(t,e,s){let r=null;return Object.entries(t).forEach(([i,n])=>{if(r)return;const o=lg(i,nc(i,n),`${e} ${s}`);o&&(r=o)}),r}function dg(t,e){let s=null;return ls(t)?t.forEach(r=>{s||ig(r)||(s=ye("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):s=ye("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function hg(t,e){let s=null;return Object.values(t).forEach(r=>{if(s)return;const i=dg(r==null?void 0:r.accounts,`${e} namespace`);i&&(s=i)}),s}function pg(t,e){let s=null;return Xo(t==null?void 0:t.methods)?Xo(t==null?void 0:t.events)||(s=ye("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=ye("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function Wc(t,e){let s=null;return Object.values(t).forEach(r=>{if(s)return;const i=pg(r,`${e}, namespace`);i&&(s=i)}),s}function gg(t,e,s){let r=null;if(t&&us(t)){const i=Wc(t,e);i&&(r=i);const n=ug(t,e,s);n&&(r=n)}else r=$("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return r}function Vi(t,e){let s=null;if(t&&us(t)){const r=Wc(t,e);r&&(s=r);const i=hg(t,e);i&&(s=i)}else s=$("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function zc(t){return xe(t.protocol,!0)}function fg(t,e){let s=!1;return t?t&&ls(t)&&t.length&&t.forEach(r=>{s=zc(r)}):s=!0,s}function mg(t){return typeof t=="number"}function it(t){return typeof t<"u"&&typeof t!==null}function wg(t){return!(!t||typeof t!="object"||!t.code||!Gn(t.code,!1)||!t.message||!xe(t.message,!1))}function yg(t){return!(Ve(t)||!xe(t.method,!1))}function bg(t){return!(Ve(t)||Ve(t.result)&&Ve(t.error)||!Gn(t.id,!1)||!xe(t.jsonrpc,!1))}function vg(t){return!(Ve(t)||!xe(t.name,!1))}function Zo(t,e){return!(!vi(e)||!Yp(t).includes(e))}function Eg(t,e,s){return xe(s,!1)?Xp(t,e).includes(s):!1}function Cg(t,e,s){return xe(s,!1)?Zp(t,e).includes(s):!1}function Qo(t,e,s){let r=null;const i=Ig(t),n=Ng(e),o=Object.keys(i),a=Object.keys(n),c=ea(Object.keys(t)),l=ea(Object.keys(e)),u=c.filter(d=>!l.includes(d));return u.length&&(r=$("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
8
- Required: ${u.toString()}
9
- Received: ${Object.keys(e).toString()}`)),Ns(o,a)||(r=$("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.
10
- Required: ${o.toString()}
11
- Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||r)return;const g=mr(e[d].accounts);g.includes(d)||(r=$("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${d}
12
- Required: ${d}
13
- Approved: ${g.toString()}`))}),o.forEach(d=>{r||(Ns(i[d].methods,n[d].methods)?Ns(i[d].events,n[d].events)||(r=$("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${d}`)):r=$("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${d}`))}),r}function Ig(t){const e={};return Object.keys(t).forEach(s=>{var r;s.includes(":")?e[s]=t[s]:(r=t[s].chains)==null||r.forEach(i=>{e[i]={methods:t[s].methods,events:t[s].events}})}),e}function ea(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Ng(t){const e={};return Object.keys(t).forEach(s=>{if(s.includes(":"))e[s]=t[s];else{const r=mr(t[s].accounts);r==null||r.forEach(i=>{e[i]={accounts:t[s].accounts.filter(n=>n.includes(`${i}:`)),methods:t[s].methods,events:t[s].events}})}}),e}function Ag(t,e){return Gn(t,!1)&&t<=e.max&&t>=e.min}function ta(){const t=Hr();return new Promise(e=>{switch(t){case pt.browser:e(Sg());break;case pt.reactNative:e(_g());break;case pt.node:e(Pg());break;default:e(!0)}})}function Sg(){return pr()&&(navigator==null?void 0:navigator.onLine)}async function _g(){if(ps()&&typeof U.dist.global<"u"&&U.dist.global!=null&&U.dist.global.NetInfo){const t=await(U.dist.global==null?void 0:U.dist.global.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function Pg(){return!0}function Tg(t){switch(Hr()){case pt.browser:Og(t);break;case pt.reactNative:kg(t);break}}function Og(t){!ps()&&pr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function kg(t){var e;ps()&&typeof U.dist.global<"u"&&U.dist.global!=null&&U.dist.global.NetInfo&&((e=U.dist.global)==null||e.NetInfo.addEventListener(s=>t(s==null?void 0:s.isConnected)))}function xg(){var t;return pr()&&h.getDocument_1()?((t=h.getDocument_1())==null?void 0:t.visibilityState)==="visible":!0}const Gi={};class vr{static get(e){return Gi[e]}static set(e,s){Gi[e]=s}static delete(e){delete Gi[e]}}const Hc="wc",Kc=2,Nn="core",Dt=`${Hc}@2:${Nn}:`,Rg={logger:"error"},$g={database:":memory:"},Ug="crypto",sa="client_ed25519_seed",Dg=h.cjs.ONE_DAY,Lg="keychain",Fg="0.3",Bg="messages",Mg="0.3",ra=h.cjs.SIX_HOURS,jg="publisher",Vc="irn",qg="error",Gc="wss://relay.walletconnect.org",Wg="relayer",qe={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"},zg="_subscription",wt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Hg=.1,An="2.21.0",Se={link_mode:"link_mode",relay:"relay"},gi={inbound:"inbound",outbound:"outbound"},Kg="0.3",Vg="WALLETCONNECT_CLIENT_ID",ia="WALLETCONNECT_LINK_MODE_APPS",ut={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Gg="subscription",Jg="0.3",Yg="pairing",Xg="0.3",Er={wc_pairingDelete:{req:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:h.cjs.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:h.cjs.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:0},res:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:0}}},Es={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},It={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Zg="history",Qg="0.3",ef="expirer",bt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},tf="0.3",sf="verify-api",rf="https://verify.walletconnect.com",Jc="https://verify.walletconnect.org",$r=Jc,nf=`${$r}/v3`,of=[rf,Jc],af="echo",cf="https://echo.walletconnect.com",xt={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"},Ht={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Nt={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},ms={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"},ws={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"},Cr={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"},lf=.1,uf="event-client",df=86400,hf="https://pulse.walletconnect.org/batch";function pf(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),r=0;r<s.length;r++)s[r]=255;for(var i=0;i<t.length;i++){var n=t.charAt(i),o=n.charCodeAt(0);if(s[o]!==255)throw new TypeError(n+" is ambiguous");s[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var w=0,f=0,v=0,b=y.length;v!==b&&y[v]===0;)v++,w++;for(var E=(b-v)*u+1>>>0,S=new Uint8Array(E);v!==b;){for(var R=y[v],_=0,O=E-1;(R!==0||_<f)&&O!==-1;O--,_++)R+=256*S[O]>>>0,S[O]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");f=_,v++}for(var D=E-f;D!==E&&S[D]===0;)D++;for(var C=c.repeat(w);D<E;++D)C+=t.charAt(S[D]);return C}function g(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var w=0;if(y[w]!==" "){for(var f=0,v=0;y[w]===c;)f++,w++;for(var b=(y.length-w)*l+1>>>0,E=new Uint8Array(b);y[w];){var S=s[y.charCodeAt(w)];if(S===255)return;for(var R=0,_=b-1;(S!==0||R<v)&&_!==-1;_--,R++)S+=a*E[_]>>>0,E[_]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=R,w++}if(y[w]!==" "){for(var O=b-v;O!==b&&E[O]===0;)O++;for(var D=new Uint8Array(f+(b-O)),C=f;O!==b;)D[C++]=E[O++];return D}}}function m(y){var w=g(y);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:g,decode:m}}var gf=pf,ff=gf;const Yc=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},mf=t=>new TextEncoder().encode(t),wf=t=>new TextDecoder().decode(t);class yf{constructor(e,s,r){this.name=e,this.prefix=s,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class bf{constructor(e,s,r){if(this.name=e,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Xc(this,e)}}class vf{constructor(e){this.decoders=e}or(e){return Xc(this,e)}decode(e){const s=e[0],r=this.decoders[s];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Xc=(t,e)=>new vf({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Ef{constructor(e,s,r,i){this.name=e,this.prefix=s,this.baseEncode=r,this.baseDecode=i,this.encoder=new yf(e,s,r),this.decoder=new bf(e,s,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Oi=({name:t,prefix:e,encode:s,decode:r})=>new Ef(t,e,s,r),Xr=({prefix:t,name:e,alphabet:s})=>{const{encode:r,decode:i}=ff(s,e);return Oi({prefix:t,name:e,encode:r,decode:n=>Yc(i(n))})},Cf=(t,e,s,r)=>{const i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*s/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const d=i[t[u]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<s|d,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},If=(t,e,s)=>{const r=e[e.length-1]==="=",i=(1<<s)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>s;)o-=s,n+=e[i&a>>o];if(o&&(n+=e[i&a<<s-o]),r)for(;n.length*s&7;)n+="=";return n},Ge=({name:t,prefix:e,bitsPerChar:s,alphabet:r})=>Oi({prefix:e,name:t,encode(i){return If(i,r,s)},decode(i){return Cf(i,r,s,t)}}),Nf=Oi({prefix:"\0",name:"identity",encode:t=>wf(t),decode:t=>mf(t)});var Af=Object.freeze({__proto__:null,identity:Nf});const Sf=Ge({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var _f=Object.freeze({__proto__:null,base2:Sf});const Pf=Ge({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Tf=Object.freeze({__proto__:null,base8:Pf});const Of=Xr({prefix:"9",name:"base10",alphabet:"0123456789"});var kf=Object.freeze({__proto__:null,base10:Of});const xf=Ge({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Rf=Ge({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var $f=Object.freeze({__proto__:null,base16:xf,base16upper:Rf});const Uf=Ge({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Df=Ge({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Lf=Ge({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ff=Ge({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Bf=Ge({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Mf=Ge({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jf=Ge({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),qf=Ge({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Wf=Ge({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var zf=Object.freeze({__proto__:null,base32:Uf,base32upper:Df,base32pad:Lf,base32padupper:Ff,base32hex:Bf,base32hexupper:Mf,base32hexpad:jf,base32hexpadupper:qf,base32z:Wf});const Hf=Xr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Kf=Xr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Vf=Object.freeze({__proto__:null,base36:Hf,base36upper:Kf});const Gf=Xr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Jf=Xr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Yf=Object.freeze({__proto__:null,base58btc:Gf,base58flickr:Jf});const Xf=Ge({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zf=Ge({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Qf=Ge({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),em=Ge({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var tm=Object.freeze({__proto__:null,base64:Xf,base64pad:Zf,base64url:Qf,base64urlpad:em});const Zc=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),sm=Zc.reduce((t,e,s)=>(t[s]=e,t),[]),rm=Zc.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function im(t){return t.reduce((e,s)=>(e+=sm[s],e),"")}function nm(t){const e=[];for(const s of t){const r=rm[s.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(r)}return new Uint8Array(e)}const om=Oi({prefix:"🚀",name:"base256emoji",encode:im,decode:nm});var am=Object.freeze({__proto__:null,base256emoji:om}),cm=Qc,na=128,lm=-128,um=Math.pow(2,31);function Qc(t,e,s){e=e||[],s=s||0;for(var r=s;t>=um;)e[s++]=t&255|na,t/=128;for(;t&lm;)e[s++]=t&255|na,t>>>=7;return e[s]=t|0,Qc.bytes=s-r+1,e}var dm=Sn,hm=128,oa=127;function Sn(t,r){var s=0,r=r||0,i=0,n=r,o,a=t.length;do{if(n>=a)throw Sn.bytes=0,new RangeError("Could not decode varint");o=t[n++],s+=i<28?(o&oa)<<i:(o&oa)*Math.pow(2,i),i+=7}while(o>=hm);return Sn.bytes=n-r,s}var pm=Math.pow(2,7),gm=Math.pow(2,14),fm=Math.pow(2,21),mm=Math.pow(2,28),wm=Math.pow(2,35),ym=Math.pow(2,42),bm=Math.pow(2,49),vm=Math.pow(2,56),Em=Math.pow(2,63),Cm=function(t){return t<pm?1:t<gm?2:t<fm?3:t<mm?4:t<wm?5:t<ym?6:t<bm?7:t<vm?8:t<Em?9:10},Im={encode:cm,decode:dm,encodingLength:Cm},el=Im;const aa=(t,e,s=0)=>(el.encode(t,e,s),e),ca=t=>el.encodingLength(t),_n=(t,e)=>{const s=e.byteLength,r=ca(t),i=r+ca(s),n=new Uint8Array(i+s);return aa(t,n,0),aa(s,n,r),n.set(e,i),new Nm(t,s,e,n)};class Nm{constructor(e,s,r,i){this.code=e,this.size=s,this.digest=r,this.bytes=i}}const tl=({name:t,code:e,encode:s})=>new Am(t,e,s);class Am{constructor(e,s,r){this.name=e,this.code=s,this.encode=r}digest(e){if(e instanceof Uint8Array){const s=this.encode(e);return s instanceof Uint8Array?_n(this.code,s):s.then(r=>_n(this.code,r))}else throw Error("Unknown type, must be binary type")}}const sl=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Sm=tl({name:"sha2-256",code:18,encode:sl("SHA-256")}),_m=tl({name:"sha2-512",code:19,encode:sl("SHA-512")});var Pm=Object.freeze({__proto__:null,sha256:Sm,sha512:_m});const rl=0,Tm="identity",il=Yc,Om=t=>_n(rl,il(t)),km={code:rl,name:Tm,encode:il,digest:Om};var xm=Object.freeze({__proto__:null,identity:km});new TextEncoder,new TextDecoder;const la={...Af,..._f,...Tf,...kf,...$f,...zf,...Vf,...Yf,...tm,...am};({...Pm,...xm});function Rm(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function nl(t,e,s,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:r}}}const ua=nl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Ji=nl("ascii","a",t=>{let e="a";for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return e},t=>{t=t.substring(1);const e=Rm(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),$m={utf8:ua,"utf-8":ua,hex:la.base16,latin1:Ji,ascii:Ji,binary:Ji,...la};function Um(t,e="utf8"){const s=$m[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):s.decoder.decode(`${s.prefix}${t}`)}var Dm=Object.defineProperty,Lm=(t,e,s)=>e in t?Dm(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ot=(t,e,s)=>Lm(t,typeof e!="symbol"?e+"":e,s);class Fm{constructor(e,s){this.core=e,this.logger=s,Ot(this,"keychain",new Map),Ot(this,"name",Lg),Ot(this,"version",Fg),Ot(this,"initialized",!1),Ot(this,"storagePrefix",Dt),Ot(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Ot(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Ot(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),Ot(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:n}=$("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(n)}return i}),Ot(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=h.E(s,this.name)}get context(){return h.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,hn(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?pn(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Bm=Object.defineProperty,Mm=(t,e,s)=>e in t?Bm(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,He=(t,e,s)=>Mm(t,typeof e!="symbol"?e+"":e,s);class jm{constructor(e,s,r){this.core=e,this.logger=s,He(this,"name",Ug),He(this,"keychain"),He(this,"randomSessionIdentifier",In()),He(this,"initialized",!1),He(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),He(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),He(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),n=h.Po(i);return h.Qe(n.publicKey)}),He(this,"generateKeyPair",()=>{this.isInitialized();const i=Op();return this.setPrivateKey(i.publicKey,i.privateKey)}),He(this,"signJWT",async i=>{this.isInitialized();const n=await this.getClientSeed(),o=h.Po(n),a=this.randomSessionIdentifier,c=Dg;return await h.Qo(a,i,c,o)}),He(this,"generateSharedKey",(i,n,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=kp(a,n);return this.setSymKey(c,o)}),He(this,"setSymKey",async(i,n)=>{this.isInitialized();const o=n||pi(i);return await this.keychain.set(o,i),o}),He(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),He(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),He(this,"encode",async(i,n,o)=>{this.isInitialized();const a=qc(o),c=h.safeJsonStringify(n);if(zo(a))return $p(c,o==null?void 0:o.encoding);if(Wo(a)){const g=a.senderPublicKey,m=a.receiverPublicKey;i=await this.generateSharedKey(g,m)}const l=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return xp({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o==null?void 0:o.encoding})}),He(this,"decode",async(i,n,o)=>{this.isInitialized();const a=Dp(n,o);if(zo(a)){const c=Up(n,o==null?void 0:o.encoding);return h.safeJsonParse(c)}if(Wo(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=Rp({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return h.safeJsonParse(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),He(this,"getPayloadType",(i,n=_t)=>{const o=Wr({encoded:i,encoding:n});return Ts(o.type)}),He(this,"getPayloadSenderPublicKey",(i,n=_t)=>{const o=Wr({encoded:i,encoding:n});return o.senderPublicKey?h.toString(o.senderPublicKey,Ze):void 0}),this.core=e,this.logger=h.E(s,this.name),this.keychain=r||new Fm(this.core,this.logger)}get context(){return h.y(this.logger)}async setPrivateKey(e,s){return await this.keychain.set(e,s),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(sa)}catch{e=In(),await this.keychain.set(sa,e)}return Um(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var qm=Object.defineProperty,Wm=Object.defineProperties,zm=Object.getOwnPropertyDescriptors,da=Object.getOwnPropertySymbols,Hm=Object.prototype.hasOwnProperty,Km=Object.prototype.propertyIsEnumerable,Pn=(t,e,s)=>e in t?qm(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Vm=(t,e)=>{for(var s in e||(e={}))Hm.call(e,s)&&Pn(t,s,e[s]);if(da)for(var s of da(e))Km.call(e,s)&&Pn(t,s,e[s]);return t},Gm=(t,e)=>Wm(t,zm(e)),lt=(t,e,s)=>Pn(t,typeof e!="symbol"?e+"":e,s);class Jm extends fu{constructor(e,s){super(e,s),this.logger=e,this.core=s,lt(this,"messages",new Map),lt(this,"messagesWithoutClientAck",new Map),lt(this,"name",Bg),lt(this,"version",Mg),lt(this,"initialized",!1),lt(this,"storagePrefix",Dt),lt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),lt(this,"set",async(r,i,n)=>{this.isInitialized();const o=$t(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),n===gi.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,Gm(Vm({},c),{[o]:i}))}return await this.persist(),o}),lt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),lt(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const n of r){const o=this.messagesWithoutClientAck.get(n)||{};i[n]=Object.values(o)}return i}),lt(this,"has",(r,i)=>{this.isInitialized();const n=this.get(r),o=$t(i);return typeof n[o]<"u"}),lt(this,"ack",async(r,i)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(r);if(typeof n>"u")return;const o=$t(i);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,n),await this.persist()}),lt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=h.E(e,this.name),this.core=s}get context(){return h.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,hn(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,hn(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?pn(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?pn(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ym=Object.defineProperty,Xm=Object.defineProperties,Zm=Object.getOwnPropertyDescriptors,ha=Object.getOwnPropertySymbols,Qm=Object.prototype.hasOwnProperty,ew=Object.prototype.propertyIsEnumerable,Tn=(t,e,s)=>e in t?Ym(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ni=(t,e)=>{for(var s in e||(e={}))Qm.call(e,s)&&Tn(t,s,e[s]);if(ha)for(var s of ha(e))ew.call(e,s)&&Tn(t,s,e[s]);return t},Yi=(t,e)=>Xm(t,Zm(e)),At=(t,e,s)=>Tn(t,typeof e!="symbol"?e+"":e,s);class tw extends mu{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,At(this,"events",new Lt.eventsExports.EventEmitter),At(this,"name",jg),At(this,"queue",new Map),At(this,"publishTimeout",h.cjs.toMiliseconds(h.cjs.ONE_MINUTE)),At(this,"initialPublishTimeout",h.cjs.toMiliseconds(h.cjs.ONE_SECOND*15)),At(this,"needsTransportRestart",!1),At(this,"publish",async(r,i,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:n}});const a=(n==null?void 0:n.ttl)||ra,c=bi(n),l=(n==null?void 0:n.prompt)||!1,u=(n==null?void 0:n.tag)||0,d=(n==null?void 0:n.id)||h.getBigIntRpcId().toString(),g={topic:r,message:i,opts:{ttl:a,relay:c,prompt:l,tag:u,id:d,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},m=`Failed to publish payload, please try again. id:${d} tag:${u}`;try{const y=new Promise(async w=>{const f=({id:b})=>{g.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(qe.publish,f),w(g))};this.relayer.events.on(qe.publish,f);const v=os(new Promise((b,E)=>{this.rpcPublish({topic:r,message:i,ttl:a,prompt:l,tag:u,id:d,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(b).catch(S=>{this.logger.warn(S,S==null?void 0:S.message),E(S)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await v,this.events.removeListener(qe.publish,f)}catch(b){this.queue.set(d,Yi(ni({},g),{attempt:1})),this.logger.warn(b,b==null?void 0:b.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:r,message:i,opts:n}}),await os(y,this.publishTimeout,m)}catch(y){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(y),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw y}finally{this.queue.delete(d)}}),At(this,"on",(r,i)=>{this.events.on(r,i)}),At(this,"once",(r,i)=>{this.events.once(r,i)}),At(this,"off",(r,i)=>{this.events.off(r,i)}),At(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=h.E(s,this.name),this.registerEventListeners()}get context(){return h.y(this.logger)}async rpcPublish(e){var s,r,i,n;const{topic:o,message:a,ttl:c=ra,prompt:l,tag:u,id:d,attestation:g,tvf:m}=e,y={method:_r(bi().protocol).publish,params:ni({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:g},m),id:d};Ve((s=y.params)==null?void 0:s.prompt)&&((r=y.params)==null||delete r.prompt),Ve((i=y.params)==null?void 0:i.tag)&&((n=y.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:y});const w=await this.relayer.request(y);return this.relayer.events.emit(qe.publish,e),this.logger.debug("Successfully Published Payload"),w}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{const r=e.attempt+1;this.queue.set(s,Yi(ni({},e),{attempt:r}));const{topic:i,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${r}`),await this.rpcPublish(Yi(ni({},e),{topic:i,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(h.r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(qe.connection_stalled);return}this.checkQueue()}),this.relayer.on(qe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var sw=Object.defineProperty,rw=(t,e,s)=>e in t?sw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Us=(t,e,s)=>rw(t,typeof e!="symbol"?e+"":e,s);class iw{constructor(){Us(this,"map",new Map),Us(this,"set",(e,s)=>{const r=this.get(e);this.exists(e,s)||this.map.set(e,[...r,s])}),Us(this,"get",e=>this.map.get(e)||[]),Us(this,"exists",(e,s)=>this.get(e).includes(s)),Us(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,s))return;const i=r.filter(n=>n!==s);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),Us(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var nw=Object.defineProperty,ow=Object.defineProperties,aw=Object.getOwnPropertyDescriptors,pa=Object.getOwnPropertySymbols,cw=Object.prototype.hasOwnProperty,lw=Object.prototype.propertyIsEnumerable,On=(t,e,s)=>e in t?nw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ir=(t,e)=>{for(var s in e||(e={}))cw.call(e,s)&&On(t,s,e[s]);if(pa)for(var s of pa(e))lw.call(e,s)&&On(t,s,e[s]);return t},Xi=(t,e)=>ow(t,aw(e)),Ee=(t,e,s)=>On(t,typeof e!="symbol"?e+"":e,s);class uw extends bu{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Ee(this,"subscriptions",new Map),Ee(this,"topicMap",new iw),Ee(this,"events",new Lt.eventsExports.EventEmitter),Ee(this,"name",Gg),Ee(this,"version",Jg),Ee(this,"pending",new Map),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",Dt),Ee(this,"subscribeTimeout",h.cjs.toMiliseconds(h.cjs.ONE_MINUTE)),Ee(this,"initialSubscribeTimeout",h.cjs.toMiliseconds(h.cjs.ONE_SECOND*15)),Ee(this,"clientId"),Ee(this,"batchSubscribeTopicsLimit",500),Ee(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Ee(this,"subscribe",async(r,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const n=bi(i),o={topic:r,relay:n,transportType:i==null?void 0:i.transportType};this.pending.set(r,o);const a=await this.rpcSubscribe(r,n,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),Ee(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof(i==null?void 0:i.id)<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),Ee(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),Ee(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(n=>n.topic===r))})),Ee(this,"on",(r,i)=>{this.events.on(r,i)}),Ee(this,"once",(r,i)=>{this.events.once(r,i)}),Ee(this,"off",(r,i)=>{this.events.off(r,i)}),Ee(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),Ee(this,"start",async()=>{await this.onConnect()}),Ee(this,"stop",async()=>{await this.onDisconnect()}),Ee(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Ee(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),Ee(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(h.r.pulse,async()=>{await this.checkPending()}),this.events.on(ut.created,async r=>{const i=ut.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(ut.deleted,async r=>{const i=ut.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=h.E(s,this.name),this.clientId=""}get context(){return h.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,s){let r=!1;try{r=this.getSubscription(e).topic===s}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,s){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,s)))}async unsubscribeById(e,s,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:r}});try{const i=bi(r);await this.restartToComplete({topic:e,id:s,relay:i}),await this.rpcUnsubscribe(e,s,i);const n=ye("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,s,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,s,r){var i;(!r||(r==null?void 0:r.transportType)===Se.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const n={method:_r(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(i=r==null?void 0:r.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((r==null?void 0:r.transportType)===Se.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(u=>this.logger.warn(u))},h.cjs.toMiliseconds(h.cjs.ONE_SECOND)),a;const c=new Promise(async u=>{const d=g=>{g.topic===e&&(this.events.removeListener(ut.created,d),u(g.id))};this.events.on(ut.created,d);try{const g=await os(new Promise((m,y)=>{this.relayer.request(n).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),y(w)}).then(m)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(ut.created,d),u(g)}catch{}}),l=await os(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(qe.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,r={method:_r(s.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await os(new Promise(i=>{this.relayer.request(r).catch(n=>this.logger.warn(n)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(qe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,r={method:_r(s.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await os(new Promise((n,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(qe.connection_stalled)}return i}rpcUnsubscribe(e,s,r){const i={method:_r(r.protocol).unsubscribe,params:{topic:e,id:s}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,s){this.setSubscription(e,Xi(Ir({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,Ir({},s)),this.pending.delete(s.topic)})}async onUnsubscribe(e,s,r){this.events.removeAllListeners(s),this.hasSubscription(s,e)&&this.deleteSubscription(s,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,s){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:s}),this.addSubscription(e,s)}addSubscription(e,s){this.subscriptions.set(e,Ir({},s)),this.topicMap.set(s.topic,e),this.events.emit(ut.created,s)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const s=this.subscriptions.get(e);if(!s){const{message:r}=$("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(ut.deleted,Xi(Ir({},r),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ut.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<s;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(ut.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:s}=$("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async s=>Xi(Ir({},s),{id:await this.getSubscriptionId(s.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const s=await this.rpcBatchFetchMessages(e);s&&s.messages&&(await wd(h.cjs.toMiliseconds(h.cjs.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(s.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=$("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 $t(e+await this.getClientId())}}var dw=Object.defineProperty,ga=Object.getOwnPropertySymbols,hw=Object.prototype.hasOwnProperty,pw=Object.prototype.propertyIsEnumerable,kn=(t,e,s)=>e in t?dw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fa=(t,e)=>{for(var s in e||(e={}))hw.call(e,s)&&kn(t,s,e[s]);if(ga)for(var s of ga(e))pw.call(e,s)&&kn(t,s,e[s]);return t},de=(t,e,s)=>kn(t,typeof e!="symbol"?e+"":e,s);class gw extends wu{constructor(e){super(e),de(this,"protocol","wc"),de(this,"version",2),de(this,"core"),de(this,"logger"),de(this,"events",new Lt.eventsExports.EventEmitter),de(this,"provider"),de(this,"messages"),de(this,"subscriber"),de(this,"publisher"),de(this,"name",Wg),de(this,"transportExplicitlyClosed",!1),de(this,"initialized",!1),de(this,"connectionAttemptInProgress",!1),de(this,"relayUrl"),de(this,"projectId"),de(this,"packageName"),de(this,"bundleId"),de(this,"hasExperiencedNetworkDisruption",!1),de(this,"pingTimeout"),de(this,"heartBeatTimeout",h.cjs.toMiliseconds(h.cjs.THIRTY_SECONDS+h.cjs.FIVE_SECONDS)),de(this,"reconnectTimeout"),de(this,"connectPromise"),de(this,"reconnectInProgress",!1),de(this,"requestsInFlight",[]),de(this,"connectTimeout",h.cjs.toMiliseconds(h.cjs.ONE_SECOND*15)),de(this,"request",async s=>{var r,i;this.logger.debug("Publishing Request Payload");const n=s.id||h.getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:s.method,topic:(r=s.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${n}:${((i=s.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(s);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),de(this,"resetPingTimeout",()=>{wi()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var s,r,i,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(i=(r=(s=this.provider)==null?void 0:s.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||n.call(i)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),de(this,"onPayloadHandler",s=>{this.onProviderPayload(s),this.resetPingTimeout()}),de(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(qe.connect)}),de(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),de(this,"onProviderErrorHandler",s=>{this.logger.fatal(`Fatal socket error: ${s.message}`),this.events.emit(qe.error,s),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),de(this,"registerProviderListeners",()=>{this.provider.on(wt.payload,this.onPayloadHandler),this.provider.on(wt.connect,this.onConnectHandler),this.provider.on(wt.disconnect,this.onDisconnectHandler),this.provider.on(wt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?h.E(e.logger,this.name):h.Ot(h.k({level:e.logger||qg})),this.messages=new Jm(this.logger,e.core),this.subscriber=new uw(this,this.logger),this.publisher=new tw(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Gc,this.projectId=e.projectId,td()?this.packageName=po():sd()&&(this.bundleId=po()),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 h.y(this.logger)}get connected(){var e,s,r;return((r=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,s,r;return((r=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,s,r){this.isInitialized(),await this.publisher.publish(e,s,r),await this.recordMessageEvent({topic:e,message:s,publishedAt:Date.now(),transportType:Se.relay},gi.outbound)}async subscribe(e,s){var r,i,n;this.isInitialized(),(!(s!=null&&s.transportType)||(s==null?void 0:s.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((r=s==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=s==null?void 0:s.internal)==null?void 0:i.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(ut.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(ut.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,fa({internal:{throwOnFailedPublish:o}},s)).catch(g=>{o&&d(g)})||a,u()})]),a}async unsubscribe(e,s){this.isInitialized(),await this.subscriber.unsubscribe(e,s)}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}off(e,s){this.events.off(e,s)}removeListener(e,s){this.events.removeListener(e,s)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await os(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(s,r)=>{await this.connect(e).then(s).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await ta())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 s=e.sort((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const r of s)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+(i==null?void 0:i.message))}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:r}=e;if(!s.sessionExists){const i=De(h.cjs.FIVE_MINUTES),n={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,n)}this.events.emit(qe.message,e),await this.recordMessageEvent(e,gi.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let s=1;for(;s<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${s}...`),await this.createProvider(),await new Promise(async(r,i)=>{const n=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(wt.disconnect,n),await os(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(wt.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(wt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(wt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${s}`);break}await new Promise(r=>setTimeout(r,h.cjs.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,r,i,n;if(wi())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((n=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new h.o(new h.f(ad({sdkVersion:An,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,s){const{topic:r,message:i}=e;await this.messages.set(r,i,s)}async shouldIgnoreMessageEvent(e){const{topic:s,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(s))return this.logger.warn(`Ignoring message for unknown topic ${s}`),!0;const i=this.messages.has(s,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),h.isJsonRpcRequest(e)){if(!e.method.endsWith(zg))return;const s=e.params,{topic:r,message:i,publishedAt:n,attestation:o}=s.data,a={topic:r,message:i,publishedAt:n,transportType:Se.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(fa({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else h.isJsonRpcResponse(e)&&this.events.emit(qe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,gi.inbound),this.events.emit(qe.message,e))}async acknowledgePayload(e){const s=h.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(wt.payload,this.onPayloadHandler),this.provider.off(wt.connect,this.onConnectHandler),this.provider.off(wt.disconnect,this.onDisconnectHandler),this.provider.off(wt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await ta();Tg(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(r=>this.logger.error(r,r==null?void 0:r.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(h.r.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&xg())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s==null?void 0:s.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(qe.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},h.cjs.toMiliseconds(Hg)))))}isInitialized(){if(!this.initialized){const{message:e}=$("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 fw(){}function ma(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function wa(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function ya(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const mw="[object RegExp]",ww="[object String]",yw="[object Number]",bw="[object Boolean]",ba="[object Arguments]",vw="[object Symbol]",Ew="[object Date]",Cw="[object Map]",Iw="[object Set]",Nw="[object Array]",Aw="[object Function]",Sw="[object ArrayBuffer]",Zi="[object Object]",_w="[object Error]",Pw="[object DataView]",Tw="[object Uint8Array]",Ow="[object Uint8ClampedArray]",kw="[object Uint16Array]",xw="[object Uint32Array]",Rw="[object BigUint64Array]",$w="[object Int8Array]",Uw="[object Int16Array]",Dw="[object Int32Array]",Lw="[object BigInt64Array]",Fw="[object Float32Array]",Bw="[object Float64Array]";function Mw(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function jw(t,e,s){return Pr(t,e,void 0,void 0,void 0,void 0,s)}function Pr(t,e,s,r,i,n,o){const a=o(t,e,s,r,i,n);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Ur(t,e,n,o)}return Ur(t,e,n,o)}function Ur(t,e,s,r){if(Object.is(t,e))return!0;let i=ya(t),n=ya(e);if(i===ba&&(i=Zi),n===ba&&(n=Zi),i!==n)return!1;switch(i){case ww:return t.toString()===e.toString();case yw:{const c=t.valueOf(),l=e.valueOf();return Mw(c,l)}case bw:case Ew:case vw:return Object.is(t.valueOf(),e.valueOf());case mw:return t.source===e.source&&t.flags===e.flags;case Aw:return t===e}s=s??new Map;const o=s.get(t),a=s.get(e);if(o!=null&&a!=null)return o===e;s.set(t,e),s.set(e,t);try{switch(i){case Cw:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Pr(l,e.get(c),c,t,e,s,r))return!1;return!0}case Iw:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const d=c[u],g=l.findIndex(m=>Pr(d,m,void 0,t,e,s,r));if(g===-1)return!1;l.splice(g,1)}return!0}case Nw:case Tw:case Ow:case kw:case xw:case Rw:case $w:case Uw:case Dw:case Lw:case Fw:case Bw:{if(typeof U.dist.Buffer<"u"&&U.dist.Buffer.isBuffer(t)!==U.dist.Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Pr(t[c],e[c],c,t,e,s,r))return!1;return!0}case Sw:return t.byteLength!==e.byteLength?!1:Ur(new Uint8Array(t),new Uint8Array(e),s,r);case Pw:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Ur(new Uint8Array(t),new Uint8Array(e),s,r);case _w:return t.name===e.name&&t.message===e.message;case Zi:{if(!(Ur(t.constructor,e.constructor,s,r)||ma(t)&&ma(e)))return!1;const c=[...Object.keys(t),...wa(t)],l=[...Object.keys(e),...wa(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],g=t[d];if(!Object.hasOwn(e,d))return!1;const m=e[d];if(!Pr(g,m,d,t,e,s,r))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function qw(t,e){return jw(t,e,fw)}var Ww=Object.defineProperty,va=Object.getOwnPropertySymbols,zw=Object.prototype.hasOwnProperty,Hw=Object.prototype.propertyIsEnumerable,xn=(t,e,s)=>e in t?Ww(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ea=(t,e)=>{for(var s in e||(e={}))zw.call(e,s)&&xn(t,s,e[s]);if(va)for(var s of va(e))Hw.call(e,s)&&xn(t,s,e[s]);return t},st=(t,e,s)=>xn(t,typeof e!="symbol"?e+"":e,s);class Os extends yu{constructor(e,s,r,i=Dt,n=void 0){super(e,s,r,i),this.core=e,this.logger=s,this.name=r,st(this,"map",new Map),st(this,"version",Kg),st(this,"cached",[]),st(this,"initialized",!1),st(this,"getKey"),st(this,"storagePrefix",Dt),st(this,"recentlyDeleted",[]),st(this,"recentlyDeletedLimit",200),st(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ve(o)?this.map.set(this.getKey(o),o):og(o)?this.map.set(o.id,o):ag(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),st(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())}),st(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),st(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>qw(a[c],o[c]))):this.values)),st(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=Ea(Ea({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),st(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=h.E(s,this.name),this.storagePrefix=i,this.getKey=n}get context(){return h.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 s=this.map.get(e);if(!s){if(this.recentlyDeleted.includes(e)){const{message:i}=$("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=$("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return s}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:s}=$("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Kw=Object.defineProperty,Vw=(t,e,s)=>e in t?Kw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oe=(t,e,s)=>Vw(t,typeof e!="symbol"?e+"":e,s);class Gw{constructor(e,s){this.core=e,this.logger=s,oe(this,"name",Yg),oe(this,"version",Xg),oe(this,"events",new Lt.Nt),oe(this,"pairings"),oe(this,"initialized",!1),oe(this,"storagePrefix",Dt),oe(this,"ignoredPayloadTypes",[Jt]),oe(this,"registeredMethods",[]),oe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),oe(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),oe(this,"create",async r=>{this.isInitialized();const i=In(),n=await this.core.crypto.setSymKey(i),o=De(h.cjs.FIVE_MINUTES),a={protocol:Vc},c={topic:n,expiry:o,relay:a,active:!1,methods:r==null?void 0:r.methods},l=Ko({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:i,relay:a,expiryTimestamp:o,methods:r==null?void 0:r.methods});return this.events.emit(Es.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:r==null?void 0:r.transportType}),{topic:n,uri:l}}),oe(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r==null?void 0:r.uri,trace:[xt.pairing_started]}});this.isValidPair(r,i);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Ho(r.uri);i.props.properties.topic=n,i.addTrace(xt.pairing_uri_validation_success),i.addTrace(xt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),i.addTrace(xt.existing_pairing),u.active)throw i.setError(Ht.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);i.addTrace(xt.pairing_not_expired)}const d=c||De(h.cjs.FIVE_MINUTES),g={topic:n,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(n,d),await this.pairings.set(n,g),i.addTrace(xt.store_new_pairing),r.activatePairing&&await this.activate({topic:n}),this.events.emit(Es.create,g),i.addTrace(xt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),i.addTrace(xt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(Ht.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(m){throw i.setError(Ht.subscribe_pairing_topic_failure),m}return i.addTrace(xt.subscribe_pairing_topic_success),g}),oe(this,"activate",async({topic:r})=>{this.isInitialized();const i=De(h.cjs.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),oe(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const n=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=bs();this.events.once(fe("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),oe(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),oe(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),oe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),oe(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",ye("USER_DISCONNECTED")),await this.deletePairing(i))}),oe(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:n,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return Ko({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),oe(this,"sendRequest",async(r,i,n)=>{const o=h.formatJsonRpcRequest(i,n),a=await this.core.crypto.encode(r,o),c=Er[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),oe(this,"sendResult",async(r,i,n)=>{const o=h.formatJsonRpcResult(r,n),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=Er[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),oe(this,"sendError",async(r,i,n)=>{const o=h.formatJsonRpcError(r,n),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=Er[c]?Er[c].res:Er.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),oe(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,ye("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),oe(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>ss(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),oe(this,"onRelayEventRequest",async r=>{const{topic:i,payload:n}=r;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,n);default:return await this.onUnknownRpcMethodRequest(i,n)}}),oe(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n}=r,o=(await this.core.history.get(i,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,n);default:return this.onUnknownRpcMethodResponse(o)}}),oe(this,"onPairingPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult(n,r,!0),this.events.emit(Es.ping,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),oe(this,"onPairingPingResponse",(r,i)=>{const{id:n}=i;setTimeout(()=>{h.isJsonRpcResult(i)?this.events.emit(fe("pairing_ping",n),{}):h.isJsonRpcError(i)&&this.events.emit(fe("pairing_ping",n),{error:i.error})},500)}),oe(this,"onPairingDeleteRequest",async(r,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Es.delete,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),oe(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:n,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=ye("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,r,a),this.logger.error(a)}catch(a){await this.sendError(n,r,a),this.logger.error(a)}}),oe(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(ye("WC_METHOD_UNSUPPORTED",r))}),oe(this,"isValidPair",(r,i)=>{var n;if(!it(r)){const{message:a}=$("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(Ht.malformed_pairing_uri),new Error(a)}if(!ng(r.uri)){const{message:a}=$("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(Ht.malformed_pairing_uri),new Error(a)}const o=Ho(r==null?void 0:r.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=$("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(Ht.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=$("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(Ht.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&h.cjs.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){i.setError(Ht.pairing_expired);const{message:a}=$("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),oe(this,"isValidPing",async r=>{if(!it(r)){const{message:n}=$("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidPairingTopic(i)}),oe(this,"isValidDisconnect",async r=>{if(!it(r)){const{message:n}=$("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidPairingTopic(i)}),oe(this,"isValidPairingTopic",async r=>{if(!xe(r,!1)){const{message:i}=$("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=$("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(ss(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=$("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=h.E(s,this.name),this.pairings=new Os(this.core,this.logger,this.name,this.storagePrefix)}get context(){return h.y(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(qe.message,async e=>{const{topic:s,message:r,transportType:i}=e;if(this.pairings.keys.includes(s)&&i!==Se.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const n=await this.core.crypto.decode(s,r);h.isJsonRpcRequest(n)?(this.core.history.set(s,n),await this.onRelayEventRequest({topic:s,payload:n})):h.isJsonRpcResponse(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:s,payload:n}),this.core.history.delete(s,n.id)),await this.core.relayer.messages.ack(s,r)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(bt.expired,async e=>{const{topic:s}=lc(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(Es.expire,{topic:s}))})}}var Jw=Object.defineProperty,Yw=(t,e,s)=>e in t?Jw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ke=(t,e,s)=>Yw(t,typeof e!="symbol"?e+"":e,s);class Xw extends gu{constructor(e,s){super(e,s),this.core=e,this.logger=s,Ke(this,"records",new Map),Ke(this,"events",new Lt.eventsExports.EventEmitter),Ke(this,"name",Zg),Ke(this,"version",Qg),Ke(this,"cached",[]),Ke(this,"initialized",!1),Ke(this,"storagePrefix",Dt),Ke(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ke(this,"set",(r,i,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:n}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:n,expiry:De(h.cjs.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(It.created,o)}),Ke(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=h.isJsonRpcError(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(It.updated,i))}),Ke(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Ke(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(n=>{if(n.topic===r){if(typeof i<"u"&&n.id!==i)return;this.records.delete(n.id),this.events.emit(It.deleted,n)}}),this.persist()}),Ke(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Ke(this,"on",(r,i)=>{this.events.on(r,i)}),Ke(this,"once",(r,i)=>{this.events.once(r,i)}),Ke(this,"off",(r,i)=>{this.events.off(r,i)}),Ke(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=h.E(s,this.name)}get context(){return h.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(s=>{if(typeof s.response<"u")return;const r={topic:s.topic,request:h.formatJsonRpcRequest(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const s=this.records.get(e);if(!s){const{message:r}=$("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(It.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=$("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(It.created,e=>{const s=It.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(It.updated,e=>{const s=It.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(It.deleted,e=>{const s=It.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(h.r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{h.cjs.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(It.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Zw=Object.defineProperty,Qw=(t,e,s)=>e in t?Zw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ye=(t,e,s)=>Qw(t,typeof e!="symbol"?e+"":e,s);class ey extends vu{constructor(e,s){super(e,s),this.core=e,this.logger=s,Ye(this,"expirations",new Map),Ye(this,"events",new Lt.eventsExports.EventEmitter),Ye(this,"name",ef),Ye(this,"version",tf),Ye(this,"cached",[]),Ye(this,"initialized",!1),Ye(this,"storagePrefix",Dt),Ye(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ye(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),Ye(this,"set",(r,i)=>{this.isInitialized();const n=this.formatTarget(r),o={target:n,expiry:i};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(bt.created,{target:n,expiration:o})}),Ye(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),Ye(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),n=this.getExpiration(i);this.expirations.delete(i),this.events.emit(bt.deleted,{target:i,expiration:n})}}),Ye(this,"on",(r,i)=>{this.events.on(r,i)}),Ye(this,"once",(r,i)=>{this.events.once(r,i)}),Ye(this,"off",(r,i)=>{this.events.off(r,i)}),Ye(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=h.E(s,this.name)}get context(){return h.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 cd(e);if(typeof e=="number")return ld(e);const{message:s}=$("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(s)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(bt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=$("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const s=this.expirations.get(e);if(!s){const{message:r}=$("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return s}checkExpiry(e,s){const{expiry:r}=s;h.cjs.toMiliseconds(r)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(bt.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(h.r.pulse,()=>this.checkExpirations()),this.events.on(bt.created,e=>{const s=bt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(bt.expired,e=>{const s=bt.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(bt.deleted,e=>{const s=bt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ty=Object.defineProperty,sy=(t,e,s)=>e in t?ty(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ke=(t,e,s)=>sy(t,typeof e!="symbol"?e+"":e,s);class ry extends Eu{constructor(e,s,r){super(e,s,r),this.core=e,this.logger=s,this.store=r,ke(this,"name",sf),ke(this,"abortController"),ke(this,"isDevEnv"),ke(this,"verifyUrlV3",nf),ke(this,"storagePrefix",Dt),ke(this,"version",Kc),ke(this,"publicKey"),ke(this,"fetchPromise"),ke(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&h.cjs.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ke(this,"register",async i=>{if(!pr()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=h.getDocument_1(),u=this.startAbortTimer(h.cjs.ONE_SECOND*5),d=await new Promise((g,m)=>{const y=()=>{window.removeEventListener("message",f),l.body.removeChild(w),m("attestation aborted")};this.abortController.signal.addEventListener("abort",y);const w=l.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",y,{signal:this.abortController.signal});const f=v=>{if(v.data&&typeof v.data=="string")try{const b=JSON.parse(v.data);if(b.type==="verify_attestation"){if(h.sn(b.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(w),this.abortController.signal.removeEventListener("abort",y),window.removeEventListener("message",f),g(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};l.body.appendChild(w),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),ke(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=i;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(h.sn(n).payload.id!==a)return;const l=await this.isValidJwtAttestation(n);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(i==null?void 0:i.verifyUrl);return this.fetchAttestation(o,c)}),ke(this,"fetchAttestation",async(i,n)=>{this.logger.debug(`resolving attestation: ${i} from url: ${n}`);const o=this.startAbortTimer(h.cjs.ONE_SECOND*5),a=await fetch(`${n}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ke(this,"getVerifyUrl",i=>{let n=i||$r;return of.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${$r}`),n=$r),n}),ke(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(h.cjs.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await n.json()}catch(i){this.logger.warn(i)}}),ke(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),ke(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ke(this,"isValidJwtAttestation",async i=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(i,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ke(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ke(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),ke(this,"validateAttestation",(i,n)=>{const o=Fp(i,n.publicKey),a={hasExpired:h.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=h.E(s,this.name),this.abortController=new AbortController,this.isDevEnv=jn(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return h.y(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),h.cjs.toMiliseconds(e))}}var iy=Object.defineProperty,ny=(t,e,s)=>e in t?iy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ca=(t,e,s)=>ny(t,typeof e!="symbol"?e+"":e,s);class oy extends Cu{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,Ca(this,"context",af),Ca(this,"registerDeviceToken",async r=>{const{clientId:i,token:n,notificationType:o,enableEncrypted:a=!1}=r,c=`${cf}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:n,always_raw:a})})}),this.logger=h.E(s,this.context)}}var ay=Object.defineProperty,Ia=Object.getOwnPropertySymbols,cy=Object.prototype.hasOwnProperty,ly=Object.prototype.propertyIsEnumerable,Rn=(t,e,s)=>e in t?ay(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Nr=(t,e)=>{for(var s in e||(e={}))cy.call(e,s)&&Rn(t,s,e[s]);if(Ia)for(var s of Ia(e))ly.call(e,s)&&Rn(t,s,e[s]);return t},Be=(t,e,s)=>Rn(t,typeof e!="symbol"?e+"":e,s);class uy extends Iu{constructor(e,s,r=!0){super(e,s,r),this.core=e,this.logger=s,Be(this,"context",uf),Be(this,"storagePrefix",Dt),Be(this,"storageVersion",lf),Be(this,"events",new Map),Be(this,"shouldPersist",!1),Be(this,"init",async()=>{if(!jn())try{const i={eventId:fo(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:ac(this.core.relayer.protocol,this.core.relayer.version,An)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Be(this,"createEvent",i=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=fo(),u=this.core.projectId||"",d=Date.now(),g=Nr({eventId:l,timestamp:d,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,g),this.shouldPersist=!0),g}),Be(this,"getEvent",i=>{const{eventId:n,topic:o}=i;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Nr(Nr({},a),this.setMethods(a.eventId))}),Be(this,"deleteEvent",i=>{const{eventId:n}=i;this.events.delete(n),this.shouldPersist=!0}),Be(this,"setEventListeners",()=>{this.core.heartbeat.on(h.r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{h.cjs.fromMiliseconds(Date.now())-h.cjs.fromMiliseconds(i.timestamp)>df&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Be(this,"setMethods",i=>({addTrace:n=>this.addTrace(i,n),setError:n=>this.setError(i,n)})),Be(this,"addTrace",(i,n)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(n),this.events.set(i,o),this.shouldPersist=!0)}),Be(this,"setError",(i,n)=>{const o=this.events.get(i);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Be(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Be(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(n=>{this.events.set(n.eventId,Nr(Nr({},n),this.setMethods(n.eventId)))})}catch(i){this.logger.warn(i)}}),Be(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[n,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const n of i)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),Be(this,"sendEvent",async i=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${hf}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${An}${n}`,{method:"POST",body:JSON.stringify(i)})}),Be(this,"getAppDomain",()=>oc().url),this.logger=h.E(s,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var dy=Object.defineProperty,Na=Object.getOwnPropertySymbols,hy=Object.prototype.hasOwnProperty,py=Object.prototype.propertyIsEnumerable,$n=(t,e,s)=>e in t?dy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Aa=(t,e)=>{for(var s in e||(e={}))hy.call(e,s)&&$n(t,s,e[s]);if(Na)for(var s of Na(e))py.call(e,s)&&$n(t,s,e[s]);return t},Ae=(t,e,s)=>$n(t,typeof e!="symbol"?e+"":e,s);let gy=class ol extends uu{constructor(e){var s;super(e),Ae(this,"protocol",Hc),Ae(this,"version",Kc),Ae(this,"name",Nn),Ae(this,"relayUrl"),Ae(this,"projectId"),Ae(this,"customStoragePrefix"),Ae(this,"events",new Lt.eventsExports.EventEmitter),Ae(this,"logger"),Ae(this,"heartbeat"),Ae(this,"relayer"),Ae(this,"crypto"),Ae(this,"storage"),Ae(this,"history"),Ae(this,"expirer"),Ae(this,"pairing"),Ae(this,"verify"),Ae(this,"echoClient"),Ae(this,"linkModeSupportedApps"),Ae(this,"eventClient"),Ae(this,"initialized",!1),Ae(this,"logChunkController"),Ae(this,"on",(a,c)=>this.events.on(a,c)),Ae(this,"once",(a,c)=>this.events.once(a,c)),Ae(this,"off",(a,c)=>this.events.off(a,c)),Ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Se.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Gc,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=h.k({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:Rg.logger,name:Nn}),{logger:n,chunkLoggerController:o}=h.A({opts:i,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(s=this.logChunkController)!=null&&s.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=h.E(n,this.name),this.heartbeat=new h.i,this.crypto=new jm(this,this.logger,e==null?void 0:e.keychain),this.history=new Xw(this,this.logger),this.expirer=new ey(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new h.h(Aa(Aa({},$g),e==null?void 0:e.storageOptions)),this.relayer=new gw({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Gw(this,this.logger),this.verify=new ry(this,this.logger,this.storage),this.echoClient=new oy(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new uy(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new ol(e);await s.initialize();const r=await s.crypto.getClientId();return await s.storage.setItem(Vg,r),s}get context(){return h.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(ia,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(ia)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${e}`,r=`${s}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[s]}catch(s){console.warn("Failed to get global WalletConnect core",s);return}}setGlobalCore(e){var s;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((s=e.opts)==null?void 0:s.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof U.dist.process<"u"&&U.dist.process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const fy=gy,al="wc",cl=2,ll="client",Jn=`${al}@${cl}:${ll}:`,Qi={name:ll,logger:"error"},Sa="WALLETCONNECT_DEEPLINK_CHOICE",my="proposal",_a="Proposal expired",wy="session",Ds=h.cjs.SEVEN_DAYS,yy="engine",Me={wc_sessionPropose:{req:{ttl:h.cjs.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:h.cjs.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:h.cjs.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:h.cjs.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:h.cjs.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:h.cjs.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:1104},res:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:1106},res:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:h.cjs.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:h.cjs.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:h.cjs.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:h.cjs.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:1112},res:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:1114},res:{ttl:h.cjs.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:h.cjs.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:h.cjs.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:h.cjs.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:h.cjs.FIVE_MINUTES,prompt:!1,tag:1119}}},en={min:h.cjs.FIVE_MINUTES,max:h.cjs.SEVEN_DAYS},kt={idle:"IDLE",active:"ACTIVE"},Pa={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},by="request",vy=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Ey="wc",Cy="auth",Iy="authKeys",Ny="pairingTopics",Ay="requests",ki=`${Ey}@${1.5}:${Cy}:`,fi=`${ki}:PUB_KEY`;var Sy=Object.defineProperty,_y=Object.defineProperties,Py=Object.getOwnPropertyDescriptors,Ta=Object.getOwnPropertySymbols,Ty=Object.prototype.hasOwnProperty,Oy=Object.prototype.propertyIsEnumerable,Un=(t,e,s)=>e in t?Sy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ce=(t,e)=>{for(var s in e||(e={}))Ty.call(e,s)&&Un(t,s,e[s]);if(Ta)for(var s of Ta(e))Oy.call(e,s)&&Un(t,s,e[s]);return t},Xe=(t,e)=>_y(t,Py(e)),I=(t,e,s)=>Un(t,typeof e!="symbol"?e+"":e,s);class ky extends _u{constructor(e){super(e),I(this,"name",yy),I(this,"events",new Lt.Nt),I(this,"initialized",!1),I(this,"requestQueue",{state:kt.idle,queue:[]}),I(this,"sessionRequestQueue",{state:kt.idle,queue:[]}),I(this,"requestQueueDelay",h.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(Me)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},h.cjs.toMiliseconds(this.requestQueueDelay)))}),I(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=Xe(Ce({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=eg(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=r;let u=i,d,g=!1;try{if(u){const _=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),g=_.active}}catch(_){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),_}if(!u||!g){const{topic:_,uri:O}=await this.client.core.pairing.create();u=_,d=O}if(!u){const{message:_}=$("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(_)}const m=await this.client.core.crypto.generateKeyPair(),y=Me.wc_sessionPropose.req.ttl||h.cjs.FIVE_MINUTES,w=De(y),f=Xe(Ce(Ce({requiredNamespaces:n,optionalNamespaces:o,relays:l??[{protocol:Vc}],proposer:{publicKey:m,metadata:this.client.metadata},expiryTimestamp:w,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:h.payloadId()}),v=fe("session_connect",f.id),{reject:b,resolve:E,done:S}=bs(y,_a),R=({id:_})=>{_===f.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(f.id),this.events.emit(v,{error:{message:_a,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(v,({error:_,session:O})=>{this.client.events.off("proposal_expire",R),_?b(_):O&&E(O)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:d,approval:S}}),I(this,"pair",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(s)}catch(r){throw this.client.logger.error("pair() failed"),r}}),I(this,"approve",async s=>{var r,i,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=s==null?void 0:s.id)==null?void 0:r.toString(),trace:[Nt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(C){throw o.setError(ms.no_internet_connection),C}try{await this.isValidProposalId(s==null?void 0:s.id)}catch(C){throw this.client.logger.error(`approve() -> proposal.get(${s==null?void 0:s.id}) failed`),o.setError(ms.proposal_not_found),C}try{await this.isValidApprove(s)}catch(C){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(ms.session_approve_namespace_validation_failure),C}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:g}=s,m=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:y,proposer:w,requiredNamespaces:f,optionalNamespaces:v}=m;let b=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:y});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Nt.session_approve_started,properties:{topic:y,trace:[Nt.session_approve_started,Nt.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),S=w.publicKey,R=await this.client.core.crypto.generateSharedKey(E,S),_=Ce(Ce(Ce({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:E,metadata:this.client.metadata},expiry:De(Ds)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),g&&{sessionConfig:g}),O=Se.relay;b.addTrace(Nt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:O})}catch(C){throw b.setError(ms.subscribe_session_topic_failure),C}b.addTrace(Nt.subscribe_session_topic_success);const D=Xe(Ce({},_),{topic:R,requiredNamespaces:f,optionalNamespaces:v,pairingTopic:y,acknowledged:!1,self:_.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:E,transportType:Se.relay});await this.client.session.set(R,D),b.addTrace(Nt.store_session);try{b.addTrace(Nt.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:_,throwOnFailedPublish:!0}).catch(C=>{throw b==null||b.setError(ms.session_settle_publish_failure),C}),b.addTrace(Nt.session_settle_publish_success),b.addTrace(Nt.publishing_session_approve),await this.sendResult({id:a,topic:y,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(C=>{throw b==null||b.setError(ms.session_approve_publish_failure),C}),b.addTrace(Nt.session_approve_publish_success)}catch(C){throw this.client.logger.error(C),this.client.session.delete(R,ye("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),C}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:y,metadata:w.metadata}),await this.client.proposal.delete(a,ye("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:y}),await this.setExpiry(R,De(Ds)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}}),I(this,"reject",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(s)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:i}=s;let n;try{n=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}n&&(await this.sendError({id:r,topic:n,error:i,rpcOpts:Me.wc_sessionPropose.reject}),await this.client.proposal.delete(r,ye("USER_DISCONNECTED")))}),I(this,"update",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(s)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:r,namespaces:i}=s,{done:n,resolve:o,reject:a}=bs(),c=h.payloadId(),l=h.getBigIntRpcId().toString(),u=this.client.session.get(r).namespaces;return this.events.once(fe("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(r,{namespaces:u}),a(d)}),{acknowledged:n}}),I(this,"extend",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(s)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=s,i=h.payloadId(),{done:n,resolve:o,reject:a}=bs();return this.events.once(fe("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,De(Ds)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),I(this,"request",async s=>{this.isInitialized();try{await this.isValidRequest(s)}catch(v){throw this.client.logger.error("request() -> isValidRequest() failed"),v}const{chainId:r,request:i,topic:n,expiry:o=Me.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(n);(a==null?void 0:a.transportType)===Se.relay&&await this.confirmOnlineStateOrThrow();const c=h.payloadId(),l=h.getBigIntRpcId().toString(),{done:u,resolve:d,reject:g}=bs(o,"Request expired. Please try again.");this.events.once(fe("session_request",c),({error:v,result:b})=>{v?g(v):d(b)});const m="wc_sessionRequest",y=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(y)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:m,params:{request:Xe(Ce({},i),{expiryTimestamp:De(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:y}).catch(v=>g(v)),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:r,id:c}),await u();const w={request:Xe(Ce({},i),{expiryTimestamp:De(o)}),chainId:r},f=this.shouldSetTVF(m,w);return await Promise.all([new Promise(async v=>{await this.sendRequest(Ce({clientRpcId:c,relayRpcId:l,topic:n,method:m,params:w,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,w)})).catch(b=>g(b)),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:r,id:c}),v()}),new Promise(async v=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const E=await pd(this.client.core.storage,Sa);await ud({id:c,topic:n,wcDeepLink:E})}v()}),u()]).then(v=>v[2])}),I(this,"respond",async s=>{this.isInitialized(),await this.isValidRespond(s);const{topic:r,response:i}=s,{id:n}=i,o=this.client.session.get(r);o.transportType===Se.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);h.isJsonRpcResult(i)?await this.sendResult({id:n,topic:r,result:i.result,throwOnFailedPublish:!0,appLink:a}):h.isJsonRpcError(i)&&await this.sendError({id:n,topic:r,error:i.error,appLink:a}),this.cleanupAfterResponse(s)}),I(this,"ping",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(s)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=s;if(this.client.session.keys.includes(r)){const i=h.payloadId(),n=h.getBigIntRpcId().toString(),{done:o,resolve:a,reject:c}=bs();this.events.once(fe("session_ping",i),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),I(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:r,event:i,chainId:n}=s,o=h.getBigIntRpcId().toString(),a=h.payloadId();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),I(this,"disconnect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(s);const{topic:r}=s;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:ye("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=$("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),I(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(r=>rg(r,s)))),I(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),I(this,"authenticate",async(s,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(s);const n=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=n?Se.link_mode:Se.relay;o===Se.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:g,exp:m,nbf:y,methods:w=[],expiry:f}=s,v=[...s.resources||[]],{topic:b,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:E}});const S=await this.client.core.crypto.generateKeyPair(),R=pi(S);if(await Promise.all([this.client.auth.authKeys.set(fi,{responseTopic:R,publicKey:S}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:b})]),await this.client.core.relayer.subscribe(R,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),w.length>0){const{namespace:P}=tr(a[0]);let Y=nh(P,"request",w);hi(v)&&(Y=ah(Y,v.pop())),v.push(Y)}const _=f&&f>Me.wc_sessionAuthenticate.req.ttl?f:Me.wc_sessionAuthenticate.req.ttl,O={authPayload:{type:g??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:m,nbf:y,resources:v},requester:{publicKey:S,metadata:this.client.metadata},expiryTimestamp:De(_)},D={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},C={requiredNamespaces:{},optionalNamespaces:D,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:S,metadata:this.client.metadata},expiryTimestamp:De(Me.wc_sessionPropose.req.ttl),id:h.payloadId()},{done:G,resolve:M,reject:z}=bs(_,"Request expired"),Q=h.payloadId(),N=fe("session_connect",C.id),x=fe("session_request",Q),k=async({error:P,session:Y})=>{this.events.off(x,F),P?z(P):Y&&M({session:Y})},F=async P=>{var Y,te,ie;if(await this.deletePendingAuthRequest(Q,{message:"fulfilled",code:0}),P.error){const $e=ye("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===$e.code?void 0:(this.events.off(N,k),z(P.error.message))}await this.deleteProposal(C.id),this.events.off(N,k);const{cacaos:Ie,responder:ge}=P.result,Oe=[],Fe=[];for(const $e of Ie){await Io({cacao:$e,projectId:this.client.core.projectId})||(this.client.logger.error($e,"Signature verification failed"),z(ye("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:gs}=$e,Ft=hi(gs.resources),Pt=[gn(gs.iss)],Bt=yi(gs.iss);if(Ft){const Mt=No(Ft),Qr=Ao(Ft);Oe.push(...Mt),Pt.push(...Qr)}for(const Mt of Pt)Fe.push(`${Mt}:${Bt}`)}const Je=await this.client.core.crypto.generateSharedKey(S,ge.publicKey);let Re;Oe.length>0&&(Re={topic:Je,acknowledged:!0,self:{publicKey:S,metadata:this.client.metadata},peer:ge,controller:ge.publicKey,expiry:De(Ds),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:Yo([...new Set(Oe)],[...new Set(Fe)]),transportType:o},await this.client.core.relayer.subscribe(Je,{transportType:o}),await this.client.session.set(Je,Re),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:ge.metadata}),Re=this.client.session.get(Je)),(Y=this.client.metadata.redirect)!=null&&Y.linkMode&&(te=ge.metadata.redirect)!=null&&te.linkMode&&(ie=ge.metadata.redirect)!=null&&ie.universal&&r&&(this.client.core.addLinkModeSupportedApp(ge.metadata.redirect.universal),this.client.session.update(Je,{transportType:Se.link_mode})),M({auths:Ie,session:Re})};this.events.once(N,k),this.events.once(x,F);let j;try{if(n){const P=h.formatJsonRpcRequest("wc_sessionAuthenticate",O,Q);this.client.core.history.set(b,P);const Y=await this.client.core.crypto.encode("",P,{type:Yr,encoding:is});j=ii(r,b,Y)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:O,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:Q}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:C,expiry:Me.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:C.id})])}catch(P){throw this.events.off(N,k),this.events.off(x,F),P}return await this.setProposal(C.id,C),await this.setAuthRequest(Q,{request:Xe(Ce({},O),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:j??E,response:G}}),I(this,"approveSessionAuthenticate",async s=>{const{id:r,auths:i}=s,n=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[ws.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(Cr.no_internet_connection),f}const o=this.getPendingAuthRequest(r);if(!o)throw n.setError(Cr.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||Se.relay;a===Se.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=pi(c),d={type:Jt,receiverPublicKey:c,senderPublicKey:l},g=[],m=[];for(const f of i){if(!await Io({cacao:f,projectId:this.client.core.projectId})){n.setError(Cr.invalid_cacao);const R=ye("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:R,encodeOpts:d}),new Error(R.message)}n.addTrace(ws.cacaos_verified);const{p:v}=f,b=hi(v.resources),E=[gn(v.iss)],S=yi(v.iss);if(b){const R=No(b),_=Ao(b);g.push(...R),E.push(..._)}for(const R of E)m.push(`${R}:${S}`)}const y=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(ws.create_authenticated_session_topic);let w;if((g==null?void 0:g.length)>0){w={topic:y,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:De(Ds),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Yo([...new Set(g)],[...new Set(m)]),transportType:a},n.addTrace(ws.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(y,{transportType:a})}catch(f){throw n.setError(Cr.subscribe_authenticated_session_topic_failure),f}n.addTrace(ws.subscribe_authenticated_session_topic_success),await this.client.session.set(y,w),n.addTrace(ws.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(ws.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(f){throw n.setError(Cr.authenticated_session_approve_publish_failure),f}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:w}}),I(this,"rejectSessionAuthenticate",async s=>{this.isInitialized();const{id:r,reason:i}=s,n=this.getPendingAuthRequest(r);if(!n)throw new Error(`Could not find pending auth request with id ${r}`);n.transportType===Se.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=pi(o),l={type:Jt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:l,rpcOpts:Me.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.client.proposal.delete(r,ye("USER_DISCONNECTED"))}),I(this,"formatAuthMessage",s=>{this.isInitialized();const{request:r,iss:i}=s;return yc(r,i)}),I(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const s=this.relayMessageCache.shift();s&&await this.onRelayMessage(s)}catch(s){this.client.logger.error(s)}},50)}),I(this,"cleanupDuplicatePairings",async s=>{if(s.pairingTopic)try{const r=this.client.core.pairing.pairings.get(s.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===s.peer.metadata.url&&n.topic&&n.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),I(this,"deleteSession",async s=>{var r;const{topic:i,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=s,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,ye("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),n||this.client.core.expirer.del(i),this.client.core.storage.removeItem(Sa).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,ye("USER_DISCONNECTED"))}),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=kt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),I(this,"deleteProposal",async(s,r)=>{if(r)try{const i=this.client.proposal.get(s),n=this.client.core.eventClient.getEvent({topic:i.pairingTopic});n==null||n.setError(ms.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,ye("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),I(this,"deletePendingSessionRequest",async(s,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(s,r),i?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==s),i&&(this.sessionRequestQueue.state=kt.idle,this.client.events.emit("session_request_expire",{id:s}))}),I(this,"deletePendingAuthRequest",async(s,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(s,r),i?Promise.resolve():this.client.core.expirer.del(s)])}),I(this,"setExpiry",async(s,r)=>{this.client.session.keys.includes(s)&&(this.client.core.expirer.set(s,r),await this.client.session.update(s,{expiry:r}))}),I(this,"setProposal",async(s,r)=>{this.client.core.expirer.set(s,De(Me.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,r)}),I(this,"setAuthRequest",async(s,r)=>{const{request:i,pairingTopic:n,transportType:o=Se.relay}=r;this.client.core.expirer.set(s,i.expiryTimestamp),await this.client.auth.requests.set(s,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:s,pairingTopic:n,verifyContext:i.verifyContext,transportType:o})}),I(this,"setPendingSessionRequest",async s=>{const{id:r,topic:i,params:n,verifyContext:o}=s,a=n.request.expiryTimestamp||De(Me.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:n,verifyContext:o})}),I(this,"sendRequest",async s=>{const{topic:r,method:i,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d}=s,g=h.formatJsonRpcRequest(i,n,c);let m;const y=!!u;try{const v=y?is:_t;m=await this.client.core.crypto.encode(r,g,{encoding:v})}catch(v){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),v}let w;if(vy.includes(i)){const v=$t(JSON.stringify(g)),b=$t(m);w=await this.client.core.verify.register({id:b,decryptedId:v})}const f=Me[i].req;if(f.attestation=w,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(r,g),y){const v=ii(u,r,m);await U.dist.global.Linking.openURL(v,this.client.name)}else{const v=Me[i].req;o&&(v.ttl=o),a&&(v.id=a),v.tvf=Xe(Ce({},d),{correlationId:g.id}),l?(v.internal=Xe(Ce({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,m,v)):this.client.core.relayer.publish(r,m,v).catch(b=>this.client.logger.error(b))}return g.id}),I(this,"sendResult",async s=>{const{id:r,topic:i,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=h.formatJsonRpcResult(r,n);let u;const d=c&&typeof(U.dist.global==null?void 0:U.dist.global.Linking)<"u";try{const y=d?is:_t;u=await this.client.core.crypto.encode(i,l,Xe(Ce({},a||{}),{encoding:y}))}catch(y){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),y}let g,m;try{g=await this.client.core.history.get(i,r);const y=g.request;try{this.shouldSetTVF(y.method,y.params)&&(m=this.getTVFParams(r,y.params,n))}catch(w){this.client.logger.warn("sendResult() -> getTVFParams() failed",w)}}catch(y){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),y}if(d){const y=ii(c,i,u);await U.dist.global.Linking.openURL(y,this.client.name)}else{const y=g.request.method,w=Me[y].res;w.tvf=Xe(Ce({},m),{correlationId:r}),o?(w.internal=Xe(Ce({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,w)):this.client.core.relayer.publish(i,u,w).catch(f=>this.client.logger.error(f))}await this.client.core.history.resolve(l)}),I(this,"sendError",async s=>{const{id:r,topic:i,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=h.formatJsonRpcError(r,n);let u;const d=c&&typeof(U.dist.global==null?void 0:U.dist.global.Linking)<"u";try{const m=d?is:_t;u=await this.client.core.crypto.encode(i,l,Xe(Ce({},o||{}),{encoding:m}))}catch(m){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),m}let g;try{g=await this.client.core.history.get(i,r)}catch(m){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),m}if(d){const m=ii(c,i,u);await U.dist.global.Linking.openURL(m,this.client.name)}else{const m=g.request.method,y=a||Me[m].res;this.client.core.relayer.publish(i,u,y)}await this.client.core.history.resolve(l)}),I(this,"cleanup",async()=>{const s=[],r=[];this.client.session.getAll().forEach(i=>{let n=!1;ss(i.expiry)&&(n=!0),this.client.core.crypto.keychain.has(i.topic)||(n=!0),n&&s.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{ss(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...s.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),I(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),I(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),I(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===kt.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=kt.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=kt.idle}),I(this,"processRequest",async s=>{const{topic:r,payload:i,attestation:n,transportType:o,encryptedId:a}=s,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),I(this,"onRelayEventResponse",async s=>{const{topic:r,payload:i,transportType:n}=s,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,n);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),I(this,"onRelayEventUnknownPayload",s=>{const{topic:r}=s,{message:i}=$("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),I(this,"shouldIgnorePairingRequest",s=>{const{topic:r,requestMethod:i}=s,n=this.expectedPairingMethodMap.get(r);return!n||n.includes(i)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),I(this,"onSessionProposeRequest",async s=>{const{topic:r,payload:i,attestation:n,encryptedId:o}=s,{params:a,id:c}=i;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(Ht.proposal_listener_not_found)),this.isValidConnect(Ce({},i.params));const u=a.expiryTimestamp||De(Me.wc_sessionPropose.req.ttl),d=Ce({id:c,pairingTopic:r,expiryTimestamp:u},a);await this.setProposal(c,d);const g=await this.getVerifyContext({attestationId:n,hash:$t(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l==null||l.addTrace(xt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:g})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:Me.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),I(this,"onSessionProposeResponse",async(s,r,i)=>{const{id:n}=r;if(h.isJsonRpcResult(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(n,{sessionTopic:u,pairingTopic:s,proposalId:n,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:s})}else if(h.isJsonRpcError(r)){await this.client.proposal.delete(n,ye("USER_DISCONNECTED"));const o=fe("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),I(this,"onSessionSettleRequest",async(s,r)=>{const{id:i,params:n}=r;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:g}=r.params,m=[...this.pendingSessions.values()].find(f=>f.sessionTopic===s);if(!m)return this.client.logger.error(`Pending session not found for topic ${s}`);const y=this.client.proposal.get(m.proposalId),w=Xe(Ce(Ce(Ce({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:m.pairingTopic,requiredNamespaces:y.requiredNamespaces,optionalNamespaces:y.optionalNamespaces,controller:a.publicKey,self:{publicKey:m.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),g&&{sessionConfig:g}),{transportType:Se.relay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:m.pairingTopic,metadata:w.peer.metadata}),this.client.events.emit("session_connect",{session:w}),this.events.emit(fe("session_connect",m.proposalId),{session:w}),this.pendingSessions.delete(m.proposalId),this.deleteProposal(m.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:r.id,topic:s,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),I(this,"onSessionSettleResponse",async(s,r)=>{const{id:i}=r;h.isJsonRpcResult(r)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(fe("session_approve",i),{})):h.isJsonRpcError(r)&&(await this.client.session.delete(s,ye("USER_DISCONNECTED")),this.events.emit(fe("session_approve",i),{error:r.error}))}),I(this,"onSessionUpdateRequest",async(s,r)=>{const{params:i,id:n}=r;try{const o=`${s}_session_update`,a=vr.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:s,error:ye("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ce({topic:s},i));try{vr.set(o,n),await this.client.session.update(s,{namespaces:i.namespaces}),await this.sendResult({id:n,topic:s,result:!0,throwOnFailedPublish:!0})}catch(c){throw vr.delete(o),c}this.client.events.emit("session_update",{id:n,topic:s,params:i})}catch(o){await this.sendError({id:n,topic:s,error:o}),this.client.logger.error(o)}}),I(this,"isRequestOutOfSync",(s,r)=>r.toString().slice(0,-3)<s.toString().slice(0,-3)),I(this,"onSessionUpdateResponse",(s,r)=>{const{id:i}=r,n=fe("session_update",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);h.isJsonRpcResult(r)?this.events.emit(fe("session_update",i),{}):h.isJsonRpcError(r)&&this.events.emit(fe("session_update",i),{error:r.error})}),I(this,"onSessionExtendRequest",async(s,r)=>{const{id:i}=r;try{this.isValidExtend({topic:s}),await this.setExpiry(s,De(Ds)),await this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:s})}catch(n){await this.sendError({id:i,topic:s,error:n}),this.client.logger.error(n)}}),I(this,"onSessionExtendResponse",(s,r)=>{const{id:i}=r,n=fe("session_extend",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);h.isJsonRpcResult(r)?this.events.emit(fe("session_extend",i),{}):h.isJsonRpcError(r)&&this.events.emit(fe("session_extend",i),{error:r.error})}),I(this,"onSessionPingRequest",async(s,r)=>{const{id:i}=r;try{this.isValidPing({topic:s}),await this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:s})}catch(n){await this.sendError({id:i,topic:s,error:n}),this.client.logger.error(n)}}),I(this,"onSessionPingResponse",(s,r)=>{const{id:i}=r,n=fe("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);h.isJsonRpcResult(r)?this.events.emit(fe("session_ping",i),{}):h.isJsonRpcError(r)&&this.events.emit(fe("session_ping",i),{error:r.error})},500)}),I(this,"onSessionDeleteRequest",async(s,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:s,reason:r.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(qe.publish,async()=>{n(await this.deleteSession({topic:s,id:i}))})}),this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:s,error:ye("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),I(this,"onSessionRequest",async s=>{var r,i,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=s,{id:d,params:g}=a;try{await this.isValidRequest(Ce({topic:o},g));const m=this.client.session.get(o),y=await this.getVerifyContext({attestationId:c,hash:$t(JSON.stringify(h.formatJsonRpcRequest("wc_sessionRequest",g,d))),encryptedId:l,metadata:m.peer.metadata,transportType:u}),w={id:d,topic:o,params:g,verifyContext:y};await this.setPendingSessionRequest(w),u===Se.link_mode&&(r=m.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=m.peer.metadata.redirect)==null?void 0:i.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(m){await this.sendError({id:d,topic:o,error:m}),this.client.logger.error(m)}}),I(this,"onSessionRequestResponse",(s,r)=>{const{id:i}=r,n=fe("session_request",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);h.isJsonRpcResult(r)?this.events.emit(fe("session_request",i),{result:r.result}):h.isJsonRpcError(r)&&this.events.emit(fe("session_request",i),{error:r.error})}),I(this,"onSessionEventRequest",async(s,r)=>{const{id:i,params:n}=r;try{const o=`${s}_session_event_${n.event.name}`,a=vr.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Ce({topic:s},n)),this.client.events.emit("session_event",{id:i,topic:s,params:n}),vr.set(o,i)}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),I(this,"onSessionAuthenticateResponse",(s,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:r}),h.isJsonRpcResult(r)?this.events.emit(fe("session_request",i),{result:r.result}):h.isJsonRpcError(r)&&this.events.emit(fe("session_request",i),{error:r.error})}),I(this,"onSessionAuthenticateRequest",async s=>{var r;const{topic:i,payload:n,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:u,expiryTimestamp:d}=n.params,g=await this.getVerifyContext({attestationId:o,hash:$t(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),m={requester:l,pairingTopic:i,id:n.id,authPayload:u,verifyContext:g,expiryTimestamp:d};await this.setAuthRequest(n.id,{request:m,pairingTopic:i,transportType:c}),c===Se.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:n.params,id:n.id,verifyContext:g})}catch(l){this.client.logger.error(l);const u=n.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),g=this.getAppLinkIfEnabled(n.params.requester.metadata,c),m={type:Jt,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:n.id,topic:i,error:l,encodeOpts:m,rpcOpts:Me.wc_sessionAuthenticate.autoReject,appLink:g})}}),I(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),I(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=kt.idle,this.processSessionRequestQueue()},h.cjs.toMiliseconds(this.requestQueueDelay))}),I(this,"cleanupPendingSentRequestsForTopic",({topic:s,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(n=>n.topic===s&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=fe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(fe("session_request",n.request.id),{error:r})})}),I(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===kt.active){this.client.logger.info("session request queue is already active.");return}const s=this.sessionRequestQueue.queue[0];if(!s){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=kt.active,this.emitSessionRequest(s)}catch(r){this.client.logger.error(r)}}),I(this,"emitSessionRequest",s=>{this.client.events.emit("session_request",s)}),I(this,"onPairingCreated",s=>{if(s.methods&&this.expectedPairingMethodMap.set(s.topic,s.methods),s.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===s.topic);r&&this.onSessionProposeRequest({topic:s.topic,payload:h.formatJsonRpcRequest("wc_sessionPropose",Xe(Ce({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id)})}),I(this,"isValidConnect",async s=>{if(!it(s)){const{message:l}=$("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(s)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=s;if(Ve(r)||await this.isValidPairingTopic(r),!fg(c)){const{message:l}=$("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!Ve(i)&&us(i)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(i,"requiredNamespaces")}if(!Ve(n)&&us(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Ve(o)||this.validateSessionProps(o,"sessionProperties"),!Ve(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(u=>l.includes(u)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),I(this,"validateNamespaces",(s,r)=>{const i=gg(s,"connect()",r);if(i)throw new Error(i.message)}),I(this,"isValidApprove",async s=>{if(!it(s))throw new Error($("MISSING_OR_INVALID",`approve() params: ${s}`).message);const{id:r,namespaces:i,relayProtocol:n,sessionProperties:o,scopedProperties:a}=s;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=Vi(i,"approve()");if(l)throw new Error(l.message);const u=Qo(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!xe(n,!0)){const{message:d}=$("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(d)}if(Ve(o)||this.validateSessionProps(o,"sessionProperties"),!Ve(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(i));if(!Object.keys(a).every(g=>d.has(g)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),I(this,"isValidReject",async s=>{if(!it(s)){const{message:n}=$("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(n)}const{id:r,reason:i}=s;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!wg(i)){const{message:n}=$("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(n)}}),I(this,"isValidSessionSettleRequest",s=>{if(!it(s)){const{message:l}=$("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}const{relay:r,controller:i,namespaces:n,expiry:o}=s;if(!zc(r)){const{message:l}=$("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=cg(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Vi(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ss(o)){const{message:l}=$("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),I(this,"isValidUpdate",async s=>{if(!it(s)){const{message:c}=$("MISSING_OR_INVALID",`update() params: ${s}`);throw new Error(c)}const{topic:r,namespaces:i}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const n=this.client.session.get(r),o=Vi(i,"update()");if(o)throw new Error(o.message);const a=Qo(n.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),I(this,"isValidExtend",async s=>{if(!it(s)){const{message:i}=$("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(i)}const{topic:r}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),I(this,"isValidRequest",async s=>{if(!it(s)){const{message:c}=$("MISSING_OR_INVALID",`request() params: ${s}`);throw new Error(c)}const{topic:r,request:i,chainId:n,expiry:o}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!Zo(a,n)){const{message:c}=$("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!yg(i)){const{message:c}=$("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!Eg(a,n,i.method)){const{message:c}=$("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!Ag(o,en)){const{message:c}=$("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${en.min} and ${en.max}`);throw new Error(c)}}),I(this,"isValidRespond",async s=>{var r;if(!it(s)){const{message:o}=$("MISSING_OR_INVALID",`respond() params: ${s}`);throw new Error(o)}const{topic:i,response:n}=s;try{await this.isValidSessionTopic(i)}catch(o){throw(r=s==null?void 0:s.response)!=null&&r.id&&this.cleanupAfterResponse(s),o}if(!bg(n)){const{message:o}=$("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),I(this,"isValidPing",async s=>{if(!it(s)){const{message:i}=$("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(i)}const{topic:r}=s;await this.isValidSessionOrPairingTopic(r)}),I(this,"isValidEmit",async s=>{if(!it(s)){const{message:a}=$("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}const{topic:r,event:i,chainId:n}=s;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!Zo(o,n)){const{message:a}=$("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!vg(i)){const{message:a}=$("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!Cg(o,n,i.name)){const{message:a}=$("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),I(this,"isValidDisconnect",async s=>{if(!it(s)){const{message:i}=$("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(i)}const{topic:r}=s;await this.isValidSessionOrPairingTopic(r)}),I(this,"isValidAuthenticate",s=>{const{chains:r,uri:i,domain:n,nonce:o}=s;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!xe(i,!1))throw new Error("uri is required parameter");if(!xe(n,!1))throw new Error("domain is required parameter");if(!xe(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>tr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=tr(r[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 s=>{const{attestationId:r,hash:i,encryptedId:n,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||$r,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Se.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:n,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),I(this,"validateSessionProps",(s,r)=>{Object.values(s).forEach((i,n)=>{if(i==null){const{message:o}=$("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(s)[n]}`);throw new Error(o)}})}),I(this,"getPendingAuthRequest",s=>{const r=this.client.auth.requests.get(s);return typeof r=="object"?r:void 0}),I(this,"addToRecentlyDeleted",(s,r)=>{if(this.recentlyDeletedMap.set(s,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=n)break;this.recentlyDeletedMap.delete(o)}}}),I(this,"checkRecentlyDeleted",s=>{const r=this.recentlyDeletedMap.get(s);if(r){const{message:i}=$("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${s}`);throw new Error(i)}}),I(this,"isLinkModeEnabled",(s,r)=>{var i,n,o,a,c,l,u,d,g;return!s||r!==Se.link_mode?!1:((n=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=s==null?void 0:s.redirect)==null?void 0:u.universal)!==void 0&&((d=s==null?void 0:s.redirect)==null?void 0:d.universal)!==""&&((g=s==null?void 0:s.redirect)==null?void 0:g.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(U.dist.global==null?void 0:U.dist.global.Linking)<"u"}),I(this,"getAppLinkIfEnabled",(s,r)=>{var i;return this.isLinkModeEnabled(s,r)?(i=s==null?void 0:s.redirect)==null?void 0:i.universal:void 0}),I(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const r=go(s,"topic")||"",i=decodeURIComponent(go(s,"wc_ev")||""),n=this.client.session.keys.includes(r);n&&this.client.session.update(r,{transportType:Se.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:n})}),I(this,"registerLinkModeListeners",async()=>{var s;if(jn()||ps()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const r=U.dist.global==null?void 0:U.dist.global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),I(this,"shouldSetTVF",(s,r)=>{if(!r||s!=="wc_sessionRequest")return!1;const{request:i}=r;return Object.keys(Pa).includes(i.method)}),I(this,"getTVFParams",(s,r,i)=>{var n,o;try{const a=r.request.method,c=this.extractTxHashesFromResult(a,i);return Xe(Ce({correlationId:s,rpcMethods:[a],chainId:r.chainId},this.isValidContractData(r.request.params)&&{contractAddresses:[(o=(n=r.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),I(this,"isValidContractData",s=>{var r;if(!s)return!1;try{const i=(s==null?void 0:s.data)||((r=s==null?void 0:s[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const n=i.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),I(this,"extractTxHashesFromResult",(s,r)=>{try{const i=Pa[s];if(typeof r=="string")return[r];const n=r[i.key];if(ls(n))return s==="solana_signAllTransactions"?n.map(o=>Hd(o)):n;if(typeof n=="string")return[n]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,s=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,i]of Object.entries(s))for(const n of i)try{await this.onProviderMessageEvent({topic:r,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(qe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:s,message:r,attestation:i,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(fi)?this.client.auth.authKeys.get(fi):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,r,{receiverPublicKey:o,encoding:n===Se.link_mode?is:_t});h.isJsonRpcRequest(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:i,transportType:n,encryptedId:$t(r)})):h.isJsonRpcResponse(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:s,payload:a,transportType:n}),this.client.core.history.delete(s,a.id)):await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(s,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(bt.expired,async e=>{const{topic:s,id:r}=lc(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,$("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,$("EXPIRED"),!0);s?this.client.session.keys.includes(s)&&(await this.deleteSession({topic:s,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:s})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(Es.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Es.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!xe(e,!1)){const{message:s}=$("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(s)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:s}=$("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(ss(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=$("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!xe(e,!1)){const{message:s}=$("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(s)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:s}=$("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(ss(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=$("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=$("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(s)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(xe(e,!1)){const{message:s}=$("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=$("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!mg(e)){const{message:s}=$("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=$("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(ss(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=$("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class xy extends Os{constructor(e,s){super(e,s,my,Jn),this.core=e,this.logger=s}}let Ry=class extends Os{constructor(e,s){super(e,s,wy,Jn),this.core=e,this.logger=s}};class $y extends Os{constructor(e,s){super(e,s,by,Jn,r=>r.id),this.core=e,this.logger=s}}class Uy extends Os{constructor(e,s){super(e,s,Iy,ki,()=>fi),this.core=e,this.logger=s}}class Dy extends Os{constructor(e,s){super(e,s,Ny,ki),this.core=e,this.logger=s}}class Ly extends Os{constructor(e,s){super(e,s,Ay,ki,r=>r.id),this.core=e,this.logger=s}}var Fy=Object.defineProperty,By=(t,e,s)=>e in t?Fy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,tn=(t,e,s)=>By(t,typeof e!="symbol"?e+"":e,s);class My{constructor(e,s){this.core=e,this.logger=s,tn(this,"authKeys"),tn(this,"pairingTopics"),tn(this,"requests"),this.authKeys=new Uy(this.core,this.logger),this.pairingTopics=new Dy(this.core,this.logger),this.requests=new Ly(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var jy=Object.defineProperty,qy=(t,e,s)=>e in t?jy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ae=(t,e,s)=>qy(t,typeof e!="symbol"?e+"":e,s);let Wy=class ul extends Su{constructor(e){super(e),ae(this,"protocol",al),ae(this,"version",cl),ae(this,"name",Qi.name),ae(this,"metadata"),ae(this,"core"),ae(this,"logger"),ae(this,"events",new Lt.eventsExports.EventEmitter),ae(this,"engine"),ae(this,"session"),ae(this,"proposal"),ae(this,"pendingRequest"),ae(this,"auth"),ae(this,"signConfig"),ae(this,"on",(r,i)=>this.events.on(r,i)),ae(this,"once",(r,i)=>this.events.once(r,i)),ae(this,"off",(r,i)=>this.events.off(r,i)),ae(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),ae(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),ae(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),ae(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(n){throw this.logger.error(n.message),n}}),ae(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),ae(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=(e==null?void 0:e.name)||Qi.name,this.metadata=id(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const s=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:h.Ot(h.k({level:(e==null?void 0:e.logger)||Qi.logger}));this.core=(e==null?void 0:e.core)||new fy(e),this.logger=h.E(s,this.name),this.session=new Ry(this.core,this.logger),this.proposal=new xy(this.core,this.logger),this.pendingRequest=new $y(this.core,this.logger),this.engine=new ky(this),this.auth=new My(this.core,this.logger)}static async init(e){const s=new ul(e);return await s.initialize(),s}get context(){return h.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()},h.cjs.toMiliseconds(h.cjs.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Oa="error",zy="wss://relay.walletconnect.org",Hy="wc",Ky="universal_provider",oi=`${Hy}@2:${Ky}:`,dl="https://rpc.walletconnect.org/v1/",Js="generic",Vy=`${dl}bundler`,Ct={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Gy(){}function Yn(t){return t==null||typeof t!="object"&&typeof t!="function"}function Xn(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Jy(t){if(Yn(t))return t;if(Array.isArray(t)||Xn(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),s=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new s(t);if(t instanceof RegExp){const r=new s(t);return r.lastIndex=t.lastIndex,r}if(t instanceof DataView)return new s(t.buffer.slice(0));if(t instanceof Error){const r=new s(t.message);return r.stack=t.stack,r.name=t.name,r.cause=t.cause,r}if(typeof File<"u"&&t instanceof File)return new s([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const r=Object.create(e);return Object.assign(r,t)}return t}function ka(t){return typeof t=="object"&&t!==null}function hl(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function pl(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const Yy="[object RegExp]",gl="[object String]",fl="[object Number]",ml="[object Boolean]",wl="[object Arguments]",Xy="[object Symbol]",Zy="[object Date]",Qy="[object Map]",eb="[object Set]",tb="[object Array]",sb="[object ArrayBuffer]",rb="[object Object]",ib="[object DataView]",nb="[object Uint8Array]",ob="[object Uint8ClampedArray]",ab="[object Uint16Array]",cb="[object Uint32Array]",lb="[object Int8Array]",ub="[object Int16Array]",db="[object Int32Array]",hb="[object Float32Array]",pb="[object Float64Array]";function gb(t,e){return Qs(t,void 0,t,new Map,e)}function Qs(t,e,s,r=new Map,i=void 0){const n=i==null?void 0:i(t,e,s,r);if(n!=null)return n;if(Yn(t))return t;if(r.has(t))return r.get(t);if(Array.isArray(t)){const o=new Array(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=Qs(t[a],a,s,r,i);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;r.set(t,o);for(const[a,c]of t)o.set(a,Qs(c,a,s,r,i));return o}if(t instanceof Set){const o=new Set;r.set(t,o);for(const a of t)o.add(Qs(a,void 0,s,r,i));return o}if(typeof U.dist.Buffer<"u"&&U.dist.Buffer.isBuffer(t))return t.subarray();if(Xn(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=Qs(t[a],a,s,r,i);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return r.set(t,o),Cs(o,t,s,r,i),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return r.set(t,o),Cs(o,t,s,r,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return r.set(t,o),Cs(o,t,s,r,i),o}if(t instanceof Error){const o=new t.constructor;return r.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Cs(o,t,s,r,i),o}if(typeof t=="object"&&fb(t)){const o=Object.create(Object.getPrototypeOf(t));return r.set(t,o),Cs(o,t,s,r,i),o}return t}function Cs(t,e,s=t,r,i){const n=[...Object.keys(e),...hl(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Qs(e[a],a,s,r,i))}}function fb(t){switch(pl(t)){case wl:case tb:case sb:case ib:case ml:case Zy:case hb:case pb:case lb:case ub:case db:case Qy:case fl:case rb:case Yy:case eb:case gl:case Xy:case nb:case ob:case ab:case cb:return!0;default:return!1}}function mb(t,e){return gb(t,(s,r,i,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case fl:case gl:case ml:{const o=new t.constructor(t==null?void 0:t.valueOf());return Cs(o,t),o}case wl:{const o={};return Cs(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function xa(t){return mb(t)}function Ra(t){return t!==null&&typeof t=="object"&&pl(t)==="[object Arguments]"}function wb(t){return Xn(t)}function yb(t){var s;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const r=t[Symbol.toStringTag];return r==null||!((s=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&s.writable)?!1:t.toString()===`[object ${r}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function bb(t,...e){const s=e.slice(0,-1),r=e[e.length-1];let i=t;for(let n=0;n<s.length;n++){const o=s[n];i=Dn(i,o,r,new Map)}return i}function Dn(t,e,s,r){if(Yn(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(r.has(e))return Jy(r.get(e));if(r.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const i=[...Object.keys(e),...hl(e)];for(let n=0;n<i.length;n++){const o=i[n];let a=e[o],c=t[o];if(Ra(a)&&(a={...a}),Ra(c)&&(c={...c}),typeof U.dist.Buffer<"u"&&U.dist.Buffer.isBuffer(a)&&(a=xa(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],d=Reflect.ownKeys(c);for(let g=0;g<d.length;g++){const m=d[g];u[m]=c[m]}c=u}else c=[];const l=s(c,a,o,t,e,r);l!=null?t[o]=l:Array.isArray(a)||ka(c)&&ka(a)?t[o]=Dn(c,a,s,r):c==null&&yb(a)?t[o]=Dn({},a,s,r):c==null&&wb(a)?t[o]=xa(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function vb(t,...e){return bb(t,...e,Gy)}var Eb=Object.defineProperty,Cb=Object.defineProperties,Ib=Object.getOwnPropertyDescriptors,$a=Object.getOwnPropertySymbols,Nb=Object.prototype.hasOwnProperty,Ab=Object.prototype.propertyIsEnumerable,Ua=(t,e,s)=>e in t?Eb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ai=(t,e)=>{for(var s in e||(e={}))Nb.call(e,s)&&Ua(t,s,e[s]);if($a)for(var s of $a(e))Ab.call(e,s)&&Ua(t,s,e[s]);return t},Sb=(t,e)=>Cb(t,Ib(e));function gt(t,e,s){var r;const i=tr(t);return((r=e.rpcMap)==null?void 0:r[i.reference])||`${dl}?chainId=${i.namespace}:${i.reference}&projectId=${s}`}function ks(t){return t.includes(":")?t.split(":")[1]:t}function yl(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function _b(t,e){const s=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!s.length)return[];const r=[];return s.forEach(i=>{const n=e.namespaces[i].accounts;r.push(...n)}),r}function ci(t={},e={}){const s=Da(t),r=Da(e);return vb(s,r)}function Da(t){var e,s,r,i,n;const o={};if(!us(t))return o;for(const[a,c]of Object.entries(t)){const l=Ti(a)?[a]:c.chains,u=c.methods||[],d=c.events||[],g=c.rpcMap||{},m=Zs(a);o[m]=Sb(ai(ai({},o[m]),c),{chains:Ut(l,(e=o[m])==null?void 0:e.chains),methods:Ut(u,(s=o[m])==null?void 0:s.methods),events:Ut(d,(r=o[m])==null?void 0:r.events)}),(us(g)||us(((i=o[m])==null?void 0:i.rpcMap)||{}))&&(o[m].rpcMap=ai(ai({},g),(n=o[m])==null?void 0:n.rpcMap))}return o}function La(t){return t.includes(":")?t.split(":")[2]:t}function Fa(t){const e={};for(const[s,r]of Object.entries(t)){const i=r.methods||[],n=r.events||[],o=r.accounts||[],a=Ti(s)?[s]:r.chains?r.chains:yl(r.accounts);e[s]={chains:a,methods:i,events:n,accounts:o}}return e}function sn(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const bl={},he=t=>bl[t],rn=(t,e)=>{bl[t]=e};var Pb=Object.defineProperty,Tb=(t,e,s)=>e in t?Pb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ls=(t,e,s)=>Tb(t,typeof e!="symbol"?e+"":e,s);class Ob{constructor(e){Ls(this,"name","polkadot"),Ls(this,"client"),Ls(this,"httpProviders"),Ls(this,"events"),Ls(this,"namespace"),Ls(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ks(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||gt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(r,he("disableProviderPing")))}}var kb=Object.defineProperty,xb=Object.defineProperties,Rb=Object.getOwnPropertyDescriptors,Ba=Object.getOwnPropertySymbols,$b=Object.prototype.hasOwnProperty,Ub=Object.prototype.propertyIsEnumerable,Ln=(t,e,s)=>e in t?kb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ma=(t,e)=>{for(var s in e||(e={}))$b.call(e,s)&&Ln(t,s,e[s]);if(Ba)for(var s of Ba(e))Ub.call(e,s)&&Ln(t,s,e[s]);return t},ja=(t,e)=>xb(t,Rb(e)),Fs=(t,e,s)=>Ln(t,typeof e!="symbol"?e+"":e,s);class Db{constructor(e){Fs(this,"name","eip155"),Fs(this,"client"),Fs(this,"chainId"),Fs(this,"namespace"),Fs(this,"httpProviders"),Fs(this,"events"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(parseInt(e),s),this.chainId=parseInt(e),this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,s){const r=s||gt(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(r,he("disableProviderPing")))}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=parseInt(ks(s));e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}async handleSwitchChain(e){var s,r;let i=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const n=parseInt(i,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,r,i,n,o;const a=(r=(s=e.request)==null?void 0:s.params)==null?void 0:r[0],c=((n=(i=e.request)==null?void 0:i.params)==null?void 0:n[1])||[],l=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const u=this.client.session.get(e.topic),d=((o=u==null?void 0:u.sessionProperties)==null?void 0:o.capabilities)||{};if(d!=null&&d[l])return d==null?void 0:d[l];const g=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ja(Ma({},u.sessionProperties||{}),{capabilities:ja(Ma({},d||{}),{[l]:g})})})}catch(m){console.warn("Failed to update session with capabilities",m)}return g}async getCallStatus(e){var s,r;const i=this.client.session.get(e.topic),n=(s=i.sessionProperties)==null?void 0:s.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(r=i.sessionProperties)==null?void 0:r.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,s){var r;const i=new URL(e),n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h.formatJsonRpcRequest("eth_getUserOperationReceipt",[(r=s.request.params)==null?void 0:r[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,s){return`${Vy}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}}var Lb=Object.defineProperty,Fb=(t,e,s)=>e in t?Lb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Bs=(t,e,s)=>Fb(t,typeof e!="symbol"?e+"":e,s);class Bb{constructor(e){Bs(this,"name","solana"),Bs(this,"client"),Bs(this,"httpProviders"),Bs(this,"events"),Bs(this,"namespace"),Bs(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ks(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||gt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(r,he("disableProviderPing")))}}var Mb=Object.defineProperty,jb=(t,e,s)=>e in t?Mb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ms=(t,e,s)=>jb(t,typeof e!="symbol"?e+"":e,s);class qb{constructor(e){Ms(this,"name","cosmos"),Ms(this,"client"),Ms(this,"httpProviders"),Ms(this,"events"),Ms(this,"namespace"),Ms(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ks(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||gt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(r,he("disableProviderPing")))}}var Wb=Object.defineProperty,zb=(t,e,s)=>e in t?Wb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,js=(t,e,s)=>zb(t,typeof e!="symbol"?e+"":e,s);class Hb{constructor(e){js(this,"name","algorand"),js(this,"client"),js(this,"httpProviders"),js(this,"events"),js(this,"namespace"),js(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(!this.httpProviders[e]){const r=s||gt(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.chainId=e,this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||gt(e,this.namespace,this.client.core.projectId);return typeof r>"u"?void 0:new h.o(new h.f$1(r,he("disableProviderPing")))}}var Kb=Object.defineProperty,Vb=(t,e,s)=>e in t?Kb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qs=(t,e,s)=>Vb(t,typeof e!="symbol"?e+"":e,s);class Gb{constructor(e){qs(this,"name","cip34"),qs(this,"client"),qs(this,"httpProviders"),qs(this,"events"),qs(this,"namespace"),qs(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{const r=this.getCardanoRPCUrl(s),i=ks(s);e[i]=this.createHttpProvider(i,r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}getCardanoRPCUrl(e){const s=this.namespace.rpcMap;if(s)return s[e]}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||this.getCardanoRPCUrl(e);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(r,he("disableProviderPing")))}}var Jb=Object.defineProperty,Yb=(t,e,s)=>e in t?Jb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ws=(t,e,s)=>Yb(t,typeof e!="symbol"?e+"":e,s);class Xb{constructor(e){Ws(this,"name","elrond"),Ws(this,"client"),Ws(this,"httpProviders"),Ws(this,"events"),Ws(this,"namespace"),Ws(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ks(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||gt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(r,he("disableProviderPing")))}}var Zb=Object.defineProperty,Qb=(t,e,s)=>e in t?Zb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,zs=(t,e,s)=>Qb(t,typeof e!="symbol"?e+"":e,s);class ev{constructor(e){zs(this,"name","multiversx"),zs(this,"client"),zs(this,"httpProviders"),zs(this,"events"),zs(this,"namespace"),zs(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ks(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||gt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(r,he("disableProviderPing")))}}var tv=Object.defineProperty,sv=(t,e,s)=>e in t?tv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Hs=(t,e,s)=>sv(t,typeof e!="symbol"?e+"":e,s);class rv{constructor(e){Hs(this,"name","near"),Hs(this,"client"),Hs(this,"httpProviders"),Hs(this,"events"),Hs(this,"namespace"),Hs(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const r=s||gt(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||gt(e,this.namespace);return typeof r>"u"?void 0:new h.o(new h.f$1(r,he("disableProviderPing")))}}var iv=Object.defineProperty,nv=(t,e,s)=>e in t?iv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ks=(t,e,s)=>nv(t,typeof e!="symbol"?e+"":e,s);class ov{constructor(e){Ks(this,"name","tezos"),Ks(this,"client"),Ks(this,"httpProviders"),Ks(this,"events"),Ks(this,"namespace"),Ks(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const r=s||gt(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{e[s]=this.createHttpProvider(s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||gt(e,this.namespace);return typeof r>"u"?void 0:new h.o(new h.f$1(r))}}var av=Object.defineProperty,cv=(t,e,s)=>e in t?av(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Vs=(t,e,s)=>cv(t,typeof e!="symbol"?e+"":e,s);class lv{constructor(e){Vs(this,"name",Js),Vs(this,"client"),Vs(this,"httpProviders"),Vs(this,"events"),Vs(this,"namespace"),Vs(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Ct.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){var e,s;const r={};return(s=(e=this.namespace)==null?void 0:e.accounts)==null||s.forEach(i=>{const n=tr(i);r[`${n.namespace}:${n.reference}`]=this.createHttpProvider(i)}),r}getHttpProvider(e){const s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||gt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(r,he("disableProviderPing")))}}var uv=Object.defineProperty,dv=Object.defineProperties,hv=Object.getOwnPropertyDescriptors,qa=Object.getOwnPropertySymbols,pv=Object.prototype.hasOwnProperty,gv=Object.prototype.propertyIsEnumerable,Fn=(t,e,s)=>e in t?uv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,li=(t,e)=>{for(var s in e||(e={}))pv.call(e,s)&&Fn(t,s,e[s]);if(qa)for(var s of qa(e))gv.call(e,s)&&Fn(t,s,e[s]);return t},nn=(t,e)=>dv(t,hv(e)),yt=(t,e,s)=>Fn(t,typeof e!="symbol"?e+"":e,s);class Zn{constructor(e){yt(this,"client"),yt(this,"namespaces"),yt(this,"optionalNamespaces"),yt(this,"sessionProperties"),yt(this,"scopedProperties"),yt(this,"events",new Lt.Nt),yt(this,"rpcProviders",{}),yt(this,"session"),yt(this,"providerOpts"),yt(this,"logger"),yt(this,"uri"),yt(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:h.Ot(h.k({level:(e==null?void 0:e.logger)||Oa})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const s=new Zn(e);return await s.initialize(),s}async request(e,s,r){const[i,n]=this.validateChain(s);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:li({},e),chainId:`${i}:${n}`,topic:this.session.topic,expiry:r})}sendAsync(e,s,r,i){const n=new Date().getTime();this.request(e,r,i).then(o=>s(null,h.formatJsonRpcResult(n,o))).catch(o=>s(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:ye("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,s){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:i}=await this.client.authenticate(e,s);r&&(this.uri=r,this.events.emit("display_uri",r));const n=await i();if(this.session=n.session,this.session){const o=Fa(this.session.namespaces);this.namespaces=ci(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}removeListener(e,s){this.events.removeListener(e,s)}off(e,s){this.events.off(e,s)}get isWalletConnect(){return!0}async pair(e){const{uri:s,approval:r}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});s&&(this.uri=s,this.events.emit("display_uri",s));const i=await r();this.session=i;const n=Fa(i.namespaces);return this.namespaces=ci(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,s){try{if(!this.session)return;const[r,i]=this.validateChain(e),n=this.getProvider(r);n.name===Js?n.setDefaultChain(`${r}:${i}`,s):n.setDefaultChain(i,s)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const s=this.client.pairing.getAll();if(ls(s)){for(const r of s)e.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${s.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,s;if(this.client=this.providerOpts.client||await Wy.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Oa,relayUrl:this.providerOpts.relayUrl||zy,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(r){throw this.logger.error("Failed to get session",r),new Error(`The provided session: ${(s=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:s.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(s=>Zs(s)))];rn("client",this.client),rn("events",this.events),rn("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const r=_b(s,this.session),i=yl(r),n=ci(this.namespaces,this.optionalNamespaces),o=nn(li({},n[s]),{accounts:r,chains:i});switch(s){case"eip155":this.rpcProviders[s]=new Db({namespace:o});break;case"algorand":this.rpcProviders[s]=new Hb({namespace:o});break;case"solana":this.rpcProviders[s]=new Bb({namespace:o});break;case"cosmos":this.rpcProviders[s]=new qb({namespace:o});break;case"polkadot":this.rpcProviders[s]=new Ob({namespace:o});break;case"cip34":this.rpcProviders[s]=new Gb({namespace:o});break;case"elrond":this.rpcProviders[s]=new Xb({namespace:o});break;case"multiversx":this.rpcProviders[s]=new ev({namespace:o});break;case"near":this.rpcProviders[s]=new rv({namespace:o});break;case"tezos":this.rpcProviders[s]=new ov({namespace:o});break;default:this.rpcProviders[Js]?this.rpcProviders[Js].updateNamespace(o):this.rpcProviders[Js]=new lv({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var s;const{topic:r}=e;r===((s=this.session)==null?void 0:s.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var s;const{params:r,topic:i}=e;if(i!==((s=this.session)==null?void 0:s.topic))return;const{event:n}=r;if(n.name==="accountsChanged"){const o=n.data;o&&ls(o)&&this.events.emit("accountsChanged",o.map(La))}else if(n.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=Zs(o),l=sn(o)!==sn(a)?`${c}:${sn(a)}`:o;this.onChainChanged(l)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:s})=>{var r,i;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:n}=s,o=(i=this.client)==null?void 0:i.session.get(e);this.session=nn(li({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:s})}),this.client.on("session_delete",async e=>{var s;e.topic===((s=this.session)==null?void 0:s.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",nn(li({},ye("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Ct.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Js]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var s;this.getProvider(e).updateNamespace((s=this.session)==null?void 0:s.namespaces[e])})}setNamespaces(e){const{namespaces:s={},optionalNamespaces:r={},sessionProperties:i,scopedProperties:n}=e;this.optionalNamespaces=ci(s,r),this.sessionProperties=i,this.scopedProperties=n}validateChain(e){const[s,r]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,r];if(s&&!Object.keys(this.namespaces||{}).map(o=>Zs(o)).includes(s))throw new Error(`Namespace '${s}' is not configured. Please call connect() first with namespace config.`);if(s&&r)return[s,r];const i=Zs(Object.keys(this.namespaces)[0]),n=this.rpcProviders[i].getDefaultChain();return[i,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,s=!1){if(!this.namespaces)return;const[r,i]=this.validateChain(e);if(!i)return;this.updateNamespaceChain(r,i),this.events.emit("chainChanged",i);const n=this.getProvider(r).getDefaultChain();s||this.getProvider(r).setDefaultChain(i),this.emitAccountsChangedOnChainChange({namespace:r,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:s,newChainId:r}){var i,n;try{if(s===r)return;const o=(n=(i=this.session)==null?void 0:i.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(La);if(!ls(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,s){if(!this.namespaces)return;const r=this.namespaces[e]?e:`${e}:${s}`,i={chains:[],methods:[],events:[],defaultChain:s};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=s):this.namespaces[r]=i}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,s){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${oi}/${e}${i}`,s)}async getFromStore(e){var s;const r=((s=this.session)==null?void 0:s.topic)||"";return await this.client.core.storage.getItem(`${oi}/${e}${r}`)}async deleteFromStore(e){var s;const r=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${oi}/${e}${r}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const s=await this.client.core.storage.getKeys();for(const r of s)r.startsWith(oi)&&await this.client.core.storage.removeItem(r)}catch(s){this.logger.warn("Failed to cleanup storage",s)}}}function ui(t,e){return B.getConnectorId(t)===e}function fv(t){const e=Array.from(p.state.chains.keys());let s=[];return t?(s.push([t,p.state.chains.get(t)]),ui(t,H.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(r=>{r!==t&&ui(r,H.CONNECTOR_ID.WALLET_CONNECT)&&s.push([r,p.state.chains.get(r)])}):ui(t,H.CONNECTOR_ID.AUTH)&&e.forEach(r=>{r!==t&&ui(r,H.CONNECTOR_ID.AUTH)&&s.push([r,p.state.chains.get(r)])})):s=Array.from(p.state.chains.entries()),s}const ts={EIP155:"eip155",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED"},Ei={NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200"},ConnectorImageIds:{[H.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[H.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[H.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[H.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[H.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[H.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[H.CONNECTOR_ID.INJECTED]:"Browser Wallet",[H.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[H.CONNECTOR_ID.COINBASE]:"Coinbase",[H.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[H.CONNECTOR_ID.LEDGER]:"Ledger",[H.CONNECTOR_ID.SAFE]:"Safe"}},Qn={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,r])=>{e[`${ts.EIP155}:${s}`]=r}),e},isLowerCaseMatch(t,e){return(t==null?void 0:t.toLowerCase())===(e==null?void 0:e.toLowerCase())}};new AbortController;const Gs={UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"INVALID_APP_CONFIGURATION"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{shortMessage:"Network Not Found",longMessage:"Network not found - please make sure it is included in 'networks' array in createAppKit function"},INVALID_APP_CONFIGURATION:{shortMessage:"Invalid App Configuration",longMessage:()=>`Origin ${mv()?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},IFRAME_LOAD_FAILED:{shortMessage:"Network Error - Could not load embedded wallet",longMessage:()=>"There was an issue loading the embedded wallet. Please try again later."},IFRAME_REQUEST_TIMEOUT:{shortMessage:"Embedded Wallet Request Timed Out",longMessage:()=>"There was an issue doing the request to the embedded wallet. Please try again later."},UNVERIFIED_DOMAIN:{shortMessage:"Invalid App Configuration",longMessage:()=>"There was an issue loading the embedded wallet. Please verify that your domain is allowed at cloud.reown.com"},JWT_TOKEN_NOT_VALID:{shortMessage:"Session Expired",longMessage:"Invalid session found on UniversalProvider - please check your time settings and connect again"},INVALID_PROJECT_ID:{shortMessage:"Invalid App Configuration",longMessage:"Invalid Project ID - update configuration"},PROJECT_ID_NOT_CONFIGURED:{shortMessage:"Project ID Not Configured",longMessage:"Project ID Not Configured - update configuration on cloud.reown.com"}}};function mv(){return typeof window<"u"}const wv={createLogger(t,e="error"){const s=h.k({level:e}),{logger:r}=h.A({opts:s});return r.error=(...i)=>{for(const n of i)if(n instanceof Error){t(n,...i);return}t(void 0,...i)},r}},yv="rpc.walletconnect.org";function Wa(t,e){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",t),s.searchParams.set("projectId",e),s.toString()}const on=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],Ys={extendRpcUrlWithProjectId(t,e){let s=!1;try{s=new URL(t).host===yv}catch{s=!1}if(s){const r=new URL(t);return r.searchParams.has("projectId")||r.searchParams.set("projectId",e),r.toString()}return t},isCaipNetwork(t){return"chainNamespace"in t&&"caipNetworkId"in t},getChainNamespace(t){return this.isCaipNetwork(t)?t.chainNamespace:H.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${H.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){var i,n,o;const r=(o=(n=(i=t.rpcUrls)==null?void 0:i.default)==null?void 0:n.http)==null?void 0:o[0];return on.includes(e)?Wa(e,s):r||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:r}){var g,m,y,w,f;const i=this.getChainNamespace(t),n=this.getCaipNetworkId(t),o=(g=t.rpcUrls.default.http)==null?void 0:g[0],a=this.getDefaultRpcUrl(t,n,s),c=((w=(y=(m=t==null?void 0:t.rpcUrls)==null?void 0:m.chainDefault)==null?void 0:y.http)==null?void 0:w[0])||o,l=((f=r==null?void 0:r[n])==null?void 0:f.map(v=>v.url))||[],u=[...l,a],d=[...l];return c&&!d.includes(c)&&d.push(c),{...t,chainNamespace:i,caipNetworkId:n,assets:{imageId:Ei.NetworkImageIds[t.id],imageUrl:e==null?void 0:e[t.id]},rpcUrls:{...t.rpcUrls,default:{http:u},chainDefault:{http:d}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:r}){return t.map(i=>Ys.extendCaipNetwork(i,{customNetworkImageUrls:e,customRpcUrls:r,projectId:s}))},getViemTransport(t,e,s){var i,n,o;const r=[];return s==null||s.forEach(a=>{r.push(Is.http(a.url,a.config))}),on.includes(t.caipNetworkId)&&r.push(Is.http(Wa(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),(o=(n=(i=t==null?void 0:t.rpcUrls)==null?void 0:i.default)==null?void 0:n.http)==null||o.forEach(a=>{r.push(Is.http(a))}),T.fallback(r)},extendWagmiTransports(t,e,s){if(on.includes(t.caipNetworkId)){const r=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return T.fallback([s,Is.http(r)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:H.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){var c;const e=q.getActiveCaipNetworkId(),s=p.getAllRequestedCaipNetworks(),r=Array.from(((c=p.state.chains)==null?void 0:c.keys())||[]),i=e==null?void 0:e.split(":")[0],n=i?r.includes(i):!1,o=s==null?void 0:s.find(l=>l.caipNetworkId===e);return n&&!o&&e?this.getUnsupportedNetwork(e):o||t||(s==null?void 0:s[0])}},Ci={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},rt=T.proxy({providers:{...Ci},providerIds:{...Ci}}),Pe={state:rt,subscribeKey(t,e){return T.subscribeKey(rt,t,e)},subscribe(t){return T.subscribe(rt,()=>{t(rt)})},subscribeProviders(t){return T.subscribe(rt.providers,()=>t(rt.providers))},setProvider(t,e){e&&(rt.providers[t]=T.ref(e))},getProvider(t){return rt.providers[t]},setProviderId(t,e){e&&(rt.providerIds[t]=e)},getProviderId(t){if(t)return rt.providerIds[t]},reset(){rt.providers={...Ci},rt.providerIds={...Ci}},resetChain(t){rt.providers[t]=void 0,rt.providerIds[t]=void 0}},vl={SECURE_SITE_ORIGIN:(typeof U.dist.process<"u"&&typeof U.dist.process.env<"u"?U.dist.process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},Ii={filterOutDuplicatesByRDNS(t){const e=A.state.enableEIP6963?B.state.connectors:[],s=q.getRecentWallets(),r=e.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}).filter(Boolean),i=s.map(a=>a.rdns).filter(Boolean),n=r.concat(i);if(n.includes("io.metamask.mobile")&&Z.isMobile()){const a=n.indexOf("io.metamask.mobile");n[a]="io.metamask"}return t.filter(a=>!n.includes(String(a==null?void 0:a.rdns)))},filterOutDuplicatesByIds(t){const e=B.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),s=q.getRecentWallets(),r=e.map(a=>a.explorerId),i=s.map(a=>a.id),n=r.concat(i);return t.filter(a=>!n.includes(a==null?void 0:a.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=B.state,{featuredWalletIds:s}=A.state,r=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>{var c;return(c=a.info)!=null&&c.rdns&&(o[a.info.rdns]=!0),o},{});return t.map(o=>({...o,installed:!!o.rdns&&!!r[o.rdns??""]})).sort((o,a)=>{const c=Number(a.installed)-Number(o.installed);if(c!==0)return c;if(s!=null&&s.length){const l=s.indexOf(o.id),u=s.indexOf(a.id);if(l!==-1&&u!==-1)return l-u;if(l!==-1)return-1;if(u!==-1)return 1}return 0})},getConnectOrderMethod(t,e){var c;const s=(t==null?void 0:t.connectMethodsOrder)||((c=A.state.features)==null?void 0:c.connectMethodsOrder),r=e||B.state.connectors;if(s)return s;const{injected:i,announced:n}=Dr.getConnectorsByType(r,K.state.recommended,K.state.featured),o=i.filter(Dr.showConnector),a=n.filter(Dr.showConnector);return o.length||a.length?["wallet","email","social"]:vl.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&K.state.excludedWallets.some(r=>r.rdns===t.rdns),s=!!t.name&&K.state.excludedWallets.some(r=>Qn.isLowerCaseMatch(r.name,t.name));return e||s}},Dr={getConnectorsByType(t,e,s){const{customWallets:r}=A.state,i=q.getRecentWallets(),n=Ii.filterOutDuplicateWallets(e),o=Ii.filterOutDuplicateWallets(s),a=t.filter(d=>d.type==="MULTI_CHAIN"),c=t.filter(d=>d.type==="ANNOUNCED"),l=t.filter(d=>d.type==="INJECTED"),u=t.filter(d=>d.type==="EXTERNAL");return{custom:r,recent:i,external:u,multiChain:a,announced:c,injected:l,recommended:n,featured:o}},showConnector(t){var i;const e=(i=t.info)==null?void 0:i.rdns,s=!!e&&K.state.excludedWallets.some(n=>!!n.rdns&&n.rdns===e),r=!!t.name&&K.state.excludedWallets.some(n=>Qn.isLowerCaseMatch(n.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!Z.isMobile()||Z.isMobile()&&!e&&!J.checkInstalled())||s||r)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||r))},getIsConnectedWithWC(){return Array.from(p.state.chains.values()).some(s=>B.getConnectorId(s.namespace)===H.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:r,announced:i,injected:n,multiChain:o,external:a,overriddenConnectors:c=(l=>(l=A.state.features)==null?void 0:l.connectorTypeOrder)()??[]}){const u=Dr.getIsConnectedWithWC(),m=[{type:"walletConnect",isEnabled:A.state.enableWalletConnect&&!u},{type:"recent",isEnabled:r.length>0},{type:"injected",isEnabled:[...n,...i,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:t.length>0}].filter(v=>v.isEnabled),y=new Set(m.map(v=>v.type)),w=c.filter(v=>y.has(v)).map(v=>({type:v,isEnabled:!0})),f=m.filter(({type:v})=>!w.some(({type:E})=>E===v));return Array.from(new Set([...w,...f].map(({type:v})=>v)))}};let Lr,ds,hs;function bv(t,e){Lr=document.createElement("style"),ds=document.createElement("style"),hs=document.createElement("style"),Lr.textContent=sr(t).core.cssText,ds.textContent=sr(t).dark.cssText,hs.textContent=sr(t).light.cssText,document.head.appendChild(Lr),document.head.appendChild(ds),document.head.appendChild(hs),El(e)}function El(t){ds&&hs&&(t==="light"?(ds.removeAttribute("media"),hs.media="enabled"):(hs.removeAttribute("media"),ds.media="enabled"))}function vv(t){Lr&&ds&&hs&&(Lr.textContent=sr(t).core.cssText,ds.textContent=sr(t).dark.cssText,hs.textContent=sr(t).light.cssText)}function sr(t){return{core:T.i`
14
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
15
- @keyframes w3m-shake {
16
- 0% {
17
- transform: scale(1) rotate(0deg);
18
- }
19
- 20% {
20
- transform: scale(1) rotate(-1deg);
21
- }
22
- 40% {
23
- transform: scale(1) rotate(1.5deg);
24
- }
25
- 60% {
26
- transform: scale(1) rotate(-1.5deg);
27
- }
28
- 80% {
29
- transform: scale(1) rotate(1deg);
30
- }
31
- 100% {
32
- transform: scale(1) rotate(0deg);
33
- }
34
- }
35
- @keyframes w3m-iframe-fade-out {
36
- 0% {
37
- opacity: 1;
38
- }
39
- 100% {
40
- opacity: 0;
41
- }
42
- }
43
- @keyframes w3m-iframe-zoom-in {
44
- 0% {
45
- transform: translateY(50px);
46
- opacity: 0;
47
- }
48
- 100% {
49
- transform: translateY(0px);
50
- opacity: 1;
51
- }
52
- }
53
- @keyframes w3m-iframe-zoom-in-mobile {
54
- 0% {
55
- transform: scale(0.95);
56
- opacity: 0;
57
- }
58
- 100% {
59
- transform: scale(1);
60
- opacity: 1;
61
- }
62
- }
63
- :root {
64
- --w3m-modal-width: 360px;
65
- --w3m-color-mix-strength: ${T.r(t!=null&&t["--w3m-color-mix-strength"]?`${t["--w3m-color-mix-strength"]}%`:"0%")};
66
- --w3m-font-family: ${T.r((t==null?void 0:t["--w3m-font-family"])||"Inter, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;")};
67
- --w3m-font-size-master: ${T.r((t==null?void 0:t["--w3m-font-size-master"])||"10px")};
68
- --w3m-border-radius-master: ${T.r((t==null?void 0:t["--w3m-border-radius-master"])||"4px")};
69
- --w3m-z-index: ${T.r((t==null?void 0:t["--w3m-z-index"])||999)};
70
-
71
- --wui-font-family: var(--w3m-font-family);
72
-
73
- --wui-font-size-mini: calc(var(--w3m-font-size-master) * 0.8);
74
- --wui-font-size-micro: var(--w3m-font-size-master);
75
- --wui-font-size-tiny: calc(var(--w3m-font-size-master) * 1.2);
76
- --wui-font-size-small: calc(var(--w3m-font-size-master) * 1.4);
77
- --wui-font-size-paragraph: calc(var(--w3m-font-size-master) * 1.6);
78
- --wui-font-size-medium: calc(var(--w3m-font-size-master) * 1.8);
79
- --wui-font-size-large: calc(var(--w3m-font-size-master) * 2);
80
- --wui-font-size-title-6: calc(var(--w3m-font-size-master) * 2.2);
81
- --wui-font-size-medium-title: calc(var(--w3m-font-size-master) * 2.4);
82
- --wui-font-size-2xl: calc(var(--w3m-font-size-master) * 4);
83
-
84
- --wui-border-radius-5xs: var(--w3m-border-radius-master);
85
- --wui-border-radius-4xs: calc(var(--w3m-border-radius-master) * 1.5);
86
- --wui-border-radius-3xs: calc(var(--w3m-border-radius-master) * 2);
87
- --wui-border-radius-xxs: calc(var(--w3m-border-radius-master) * 3);
88
- --wui-border-radius-xs: calc(var(--w3m-border-radius-master) * 4);
89
- --wui-border-radius-s: calc(var(--w3m-border-radius-master) * 5);
90
- --wui-border-radius-m: calc(var(--w3m-border-radius-master) * 7);
91
- --wui-border-radius-l: calc(var(--w3m-border-radius-master) * 9);
92
- --wui-border-radius-3xl: calc(var(--w3m-border-radius-master) * 20);
93
-
94
- --wui-font-weight-light: 400;
95
- --wui-font-weight-regular: 500;
96
- --wui-font-weight-medium: 600;
97
- --wui-font-weight-bold: 700;
98
-
99
- --wui-letter-spacing-2xl: -1.6px;
100
- --wui-letter-spacing-medium-title: -0.96px;
101
- --wui-letter-spacing-title-6: -0.88px;
102
- --wui-letter-spacing-large: -0.8px;
103
- --wui-letter-spacing-medium: -0.72px;
104
- --wui-letter-spacing-paragraph: -0.64px;
105
- --wui-letter-spacing-small: -0.56px;
106
- --wui-letter-spacing-tiny: -0.48px;
107
- --wui-letter-spacing-micro: -0.2px;
108
- --wui-letter-spacing-mini: -0.16px;
109
-
110
- --wui-spacing-0: 0px;
111
- --wui-spacing-4xs: 2px;
112
- --wui-spacing-3xs: 4px;
113
- --wui-spacing-xxs: 6px;
114
- --wui-spacing-2xs: 7px;
115
- --wui-spacing-xs: 8px;
116
- --wui-spacing-1xs: 10px;
117
- --wui-spacing-s: 12px;
118
- --wui-spacing-m: 14px;
119
- --wui-spacing-l: 16px;
120
- --wui-spacing-2l: 18px;
121
- --wui-spacing-xl: 20px;
122
- --wui-spacing-xxl: 24px;
123
- --wui-spacing-2xl: 32px;
124
- --wui-spacing-3xl: 40px;
125
- --wui-spacing-4xl: 90px;
126
- --wui-spacing-5xl: 95px;
127
-
128
- --wui-icon-box-size-xxs: 14px;
129
- --wui-icon-box-size-xs: 20px;
130
- --wui-icon-box-size-sm: 24px;
131
- --wui-icon-box-size-md: 32px;
132
- --wui-icon-box-size-mdl: 36px;
133
- --wui-icon-box-size-lg: 40px;
134
- --wui-icon-box-size-2lg: 48px;
135
- --wui-icon-box-size-xl: 64px;
136
-
137
- --wui-icon-size-inherit: inherit;
138
- --wui-icon-size-xxs: 10px;
139
- --wui-icon-size-xs: 12px;
140
- --wui-icon-size-sm: 14px;
141
- --wui-icon-size-md: 16px;
142
- --wui-icon-size-mdl: 18px;
143
- --wui-icon-size-lg: 20px;
144
- --wui-icon-size-xl: 24px;
145
- --wui-icon-size-xxl: 28px;
146
-
147
- --wui-wallet-image-size-inherit: inherit;
148
- --wui-wallet-image-size-sm: 40px;
149
- --wui-wallet-image-size-md: 56px;
150
- --wui-wallet-image-size-lg: 80px;
151
-
152
- --wui-visual-size-size-inherit: inherit;
153
- --wui-visual-size-sm: 40px;
154
- --wui-visual-size-md: 55px;
155
- --wui-visual-size-lg: 80px;
156
-
157
- --wui-box-size-md: 100px;
158
- --wui-box-size-lg: 120px;
159
-
160
- --wui-ease-out-power-2: cubic-bezier(0, 0, 0.22, 1);
161
- --wui-ease-out-power-1: cubic-bezier(0, 0, 0.55, 1);
162
-
163
- --wui-ease-in-power-3: cubic-bezier(0.66, 0, 1, 1);
164
- --wui-ease-in-power-2: cubic-bezier(0.45, 0, 1, 1);
165
- --wui-ease-in-power-1: cubic-bezier(0.3, 0, 1, 1);
166
-
167
- --wui-ease-inout-power-1: cubic-bezier(0.45, 0, 0.55, 1);
168
-
169
- --wui-duration-lg: 200ms;
170
- --wui-duration-md: 125ms;
171
- --wui-duration-sm: 75ms;
172
-
173
- --wui-path-network-sm: path(
174
- 'M15.4 2.1a5.21 5.21 0 0 1 5.2 0l11.61 6.7a5.21 5.21 0 0 1 2.61 4.52v13.4c0 1.87-1 3.59-2.6 4.52l-11.61 6.7c-1.62.93-3.6.93-5.22 0l-11.6-6.7a5.21 5.21 0 0 1-2.61-4.51v-13.4c0-1.87 1-3.6 2.6-4.52L15.4 2.1Z'
175
- );
176
-
177
- --wui-path-network-md: path(
178
- 'M43.4605 10.7248L28.0485 1.61089C25.5438 0.129705 22.4562 0.129705 19.9515 1.61088L4.53951 10.7248C2.03626 12.2051 0.5 14.9365 0.5 17.886V36.1139C0.5 39.0635 2.03626 41.7949 4.53951 43.2752L19.9515 52.3891C22.4562 53.8703 25.5438 53.8703 28.0485 52.3891L43.4605 43.2752C45.9637 41.7949 47.5 39.0635 47.5 36.114V17.8861C47.5 14.9365 45.9637 12.2051 43.4605 10.7248Z'
179
- );
180
-
181
- --wui-path-network-lg: path(
182
- 'M78.3244 18.926L50.1808 2.45078C45.7376 -0.150261 40.2624 -0.150262 35.8192 2.45078L7.6756 18.926C3.23322 21.5266 0.5 26.3301 0.5 31.5248V64.4752C0.5 69.6699 3.23322 74.4734 7.6756 77.074L35.8192 93.5492C40.2624 96.1503 45.7376 96.1503 50.1808 93.5492L78.3244 77.074C82.7668 74.4734 85.5 69.6699 85.5 64.4752V31.5248C85.5 26.3301 82.7668 21.5266 78.3244 18.926Z'
183
- );
184
-
185
- --wui-width-network-sm: 36px;
186
- --wui-width-network-md: 48px;
187
- --wui-width-network-lg: 86px;
188
-
189
- --wui-height-network-sm: 40px;
190
- --wui-height-network-md: 54px;
191
- --wui-height-network-lg: 96px;
192
-
193
- --wui-icon-size-network-xs: 12px;
194
- --wui-icon-size-network-sm: 16px;
195
- --wui-icon-size-network-md: 24px;
196
- --wui-icon-size-network-lg: 42px;
197
-
198
- --wui-color-inherit: inherit;
199
-
200
- --wui-color-inverse-100: #fff;
201
- --wui-color-inverse-000: #000;
202
-
203
- --wui-cover: rgba(20, 20, 20, 0.8);
204
-
205
- --wui-color-modal-bg: var(--wui-color-modal-bg-base);
206
-
207
- --wui-color-accent-100: var(--wui-color-accent-base-100);
208
- --wui-color-accent-090: var(--wui-color-accent-base-090);
209
- --wui-color-accent-080: var(--wui-color-accent-base-080);
210
-
211
- --wui-color-success-100: var(--wui-color-success-base-100);
212
- --wui-color-success-125: var(--wui-color-success-base-125);
213
-
214
- --wui-color-warning-100: var(--wui-color-warning-base-100);
215
-
216
- --wui-color-error-100: var(--wui-color-error-base-100);
217
- --wui-color-error-125: var(--wui-color-error-base-125);
218
-
219
- --wui-color-blue-100: var(--wui-color-blue-base-100);
220
- --wui-color-blue-90: var(--wui-color-blue-base-90);
221
-
222
- --wui-icon-box-bg-error-100: var(--wui-icon-box-bg-error-base-100);
223
- --wui-icon-box-bg-blue-100: var(--wui-icon-box-bg-blue-base-100);
224
- --wui-icon-box-bg-success-100: var(--wui-icon-box-bg-success-base-100);
225
- --wui-icon-box-bg-inverse-100: var(--wui-icon-box-bg-inverse-base-100);
226
-
227
- --wui-all-wallets-bg-100: var(--wui-all-wallets-bg-100);
228
-
229
- --wui-avatar-border: var(--wui-avatar-border-base);
230
-
231
- --wui-thumbnail-border: var(--wui-thumbnail-border-base);
232
-
233
- --wui-wallet-button-bg: var(--wui-wallet-button-bg-base);
234
-
235
- --wui-box-shadow-blue: var(--wui-color-accent-glass-020);
236
- }
237
-
238
- @supports (background: color-mix(in srgb, white 50%, black)) {
239
- :root {
240
- --wui-color-modal-bg: color-mix(
241
- in srgb,
242
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
243
- var(--wui-color-modal-bg-base)
244
- );
245
-
246
- --wui-box-shadow-blue: color-mix(in srgb, var(--wui-color-accent-100) 20%, transparent);
247
-
248
- --wui-color-accent-100: color-mix(
249
- in srgb,
250
- var(--wui-color-accent-base-100) 100%,
251
- transparent
252
- );
253
- --wui-color-accent-090: color-mix(
254
- in srgb,
255
- var(--wui-color-accent-base-100) 90%,
256
- transparent
257
- );
258
- --wui-color-accent-080: color-mix(
259
- in srgb,
260
- var(--wui-color-accent-base-100) 80%,
261
- transparent
262
- );
263
- --wui-color-accent-glass-090: color-mix(
264
- in srgb,
265
- var(--wui-color-accent-base-100) 90%,
266
- transparent
267
- );
268
- --wui-color-accent-glass-080: color-mix(
269
- in srgb,
270
- var(--wui-color-accent-base-100) 80%,
271
- transparent
272
- );
273
- --wui-color-accent-glass-020: color-mix(
274
- in srgb,
275
- var(--wui-color-accent-base-100) 20%,
276
- transparent
277
- );
278
- --wui-color-accent-glass-015: color-mix(
279
- in srgb,
280
- var(--wui-color-accent-base-100) 15%,
281
- transparent
282
- );
283
- --wui-color-accent-glass-010: color-mix(
284
- in srgb,
285
- var(--wui-color-accent-base-100) 10%,
286
- transparent
287
- );
288
- --wui-color-accent-glass-005: color-mix(
289
- in srgb,
290
- var(--wui-color-accent-base-100) 5%,
291
- transparent
292
- );
293
- --wui-color-accent-002: color-mix(
294
- in srgb,
295
- var(--wui-color-accent-base-100) 2%,
296
- transparent
297
- );
298
-
299
- --wui-color-fg-100: color-mix(
300
- in srgb,
301
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
302
- var(--wui-color-fg-100)
303
- );
304
- --wui-color-fg-125: color-mix(
305
- in srgb,
306
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
307
- var(--wui-color-fg-125)
308
- );
309
- --wui-color-fg-150: color-mix(
310
- in srgb,
311
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
312
- var(--wui-color-fg-150)
313
- );
314
- --wui-color-fg-175: color-mix(
315
- in srgb,
316
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
317
- var(--wui-color-fg-175)
318
- );
319
- --wui-color-fg-200: color-mix(
320
- in srgb,
321
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
322
- var(--wui-color-fg-200)
323
- );
324
- --wui-color-fg-225: color-mix(
325
- in srgb,
326
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
327
- var(--wui-color-fg-225)
328
- );
329
- --wui-color-fg-250: color-mix(
330
- in srgb,
331
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
332
- var(--wui-color-fg-250)
333
- );
334
- --wui-color-fg-275: color-mix(
335
- in srgb,
336
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
337
- var(--wui-color-fg-275)
338
- );
339
- --wui-color-fg-300: color-mix(
340
- in srgb,
341
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
342
- var(--wui-color-fg-300)
343
- );
344
- --wui-color-fg-325: color-mix(
345
- in srgb,
346
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
347
- var(--wui-color-fg-325)
348
- );
349
- --wui-color-fg-350: color-mix(
350
- in srgb,
351
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
352
- var(--wui-color-fg-350)
353
- );
354
-
355
- --wui-color-bg-100: color-mix(
356
- in srgb,
357
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
358
- var(--wui-color-bg-100)
359
- );
360
- --wui-color-bg-125: color-mix(
361
- in srgb,
362
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
363
- var(--wui-color-bg-125)
364
- );
365
- --wui-color-bg-150: color-mix(
366
- in srgb,
367
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
368
- var(--wui-color-bg-150)
369
- );
370
- --wui-color-bg-175: color-mix(
371
- in srgb,
372
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
373
- var(--wui-color-bg-175)
374
- );
375
- --wui-color-bg-200: color-mix(
376
- in srgb,
377
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
378
- var(--wui-color-bg-200)
379
- );
380
- --wui-color-bg-225: color-mix(
381
- in srgb,
382
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
383
- var(--wui-color-bg-225)
384
- );
385
- --wui-color-bg-250: color-mix(
386
- in srgb,
387
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
388
- var(--wui-color-bg-250)
389
- );
390
- --wui-color-bg-275: color-mix(
391
- in srgb,
392
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
393
- var(--wui-color-bg-275)
394
- );
395
- --wui-color-bg-300: color-mix(
396
- in srgb,
397
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
398
- var(--wui-color-bg-300)
399
- );
400
- --wui-color-bg-325: color-mix(
401
- in srgb,
402
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
403
- var(--wui-color-bg-325)
404
- );
405
- --wui-color-bg-350: color-mix(
406
- in srgb,
407
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
408
- var(--wui-color-bg-350)
409
- );
410
-
411
- --wui-color-success-100: color-mix(
412
- in srgb,
413
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
414
- var(--wui-color-success-base-100)
415
- );
416
- --wui-color-success-125: color-mix(
417
- in srgb,
418
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
419
- var(--wui-color-success-base-125)
420
- );
421
-
422
- --wui-color-warning-100: color-mix(
423
- in srgb,
424
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
425
- var(--wui-color-warning-base-100)
426
- );
427
-
428
- --wui-color-error-100: color-mix(
429
- in srgb,
430
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
431
- var(--wui-color-error-base-100)
432
- );
433
- --wui-color-blue-100: color-mix(
434
- in srgb,
435
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
436
- var(--wui-color-blue-base-100)
437
- );
438
- --wui-color-blue-90: color-mix(
439
- in srgb,
440
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
441
- var(--wui-color-blue-base-90)
442
- );
443
- --wui-color-error-125: color-mix(
444
- in srgb,
445
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
446
- var(--wui-color-error-base-125)
447
- );
448
-
449
- --wui-icon-box-bg-error-100: color-mix(
450
- in srgb,
451
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
452
- var(--wui-icon-box-bg-error-base-100)
453
- );
454
- --wui-icon-box-bg-accent-100: color-mix(
455
- in srgb,
456
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
457
- var(--wui-icon-box-bg-blue-base-100)
458
- );
459
- --wui-icon-box-bg-success-100: color-mix(
460
- in srgb,
461
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
462
- var(--wui-icon-box-bg-success-base-100)
463
- );
464
- --wui-icon-box-bg-inverse-100: color-mix(
465
- in srgb,
466
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
467
- var(--wui-icon-box-bg-inverse-base-100)
468
- );
469
-
470
- --wui-all-wallets-bg-100: color-mix(
471
- in srgb,
472
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
473
- var(--wui-all-wallets-bg-100)
474
- );
475
-
476
- --wui-avatar-border: color-mix(
477
- in srgb,
478
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
479
- var(--wui-avatar-border-base)
480
- );
481
-
482
- --wui-thumbnail-border: color-mix(
483
- in srgb,
484
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
485
- var(--wui-thumbnail-border-base)
486
- );
487
-
488
- --wui-wallet-button-bg: color-mix(
489
- in srgb,
490
- var(--w3m-color-mix) var(--w3m-color-mix-strength),
491
- var(--wui-wallet-button-bg-base)
492
- );
493
- }
494
- }
495
- `,light:T.i`
496
- :root {
497
- --w3m-color-mix: ${T.r((t==null?void 0:t["--w3m-color-mix"])||"#fff")};
498
- --w3m-accent: ${T.r(ns(t,"dark")["--w3m-accent"])};
499
- --w3m-default: #fff;
500
-
501
- --wui-color-modal-bg-base: ${T.r(ns(t,"dark")["--w3m-background"])};
502
- --wui-color-accent-base-100: var(--w3m-accent);
503
-
504
- --wui-color-blueberry-100: hsla(230, 100%, 67%, 1);
505
- --wui-color-blueberry-090: hsla(231, 76%, 61%, 1);
506
- --wui-color-blueberry-080: hsla(230, 59%, 55%, 1);
507
- --wui-color-blueberry-050: hsla(231, 100%, 70%, 0.1);
508
-
509
- --wui-color-fg-100: #e4e7e7;
510
- --wui-color-fg-125: #d0d5d5;
511
- --wui-color-fg-150: #a8b1b1;
512
- --wui-color-fg-175: #a8b0b0;
513
- --wui-color-fg-200: #949e9e;
514
- --wui-color-fg-225: #868f8f;
515
- --wui-color-fg-250: #788080;
516
- --wui-color-fg-275: #788181;
517
- --wui-color-fg-300: #6e7777;
518
- --wui-color-fg-325: #9a9a9a;
519
- --wui-color-fg-350: #363636;
520
-
521
- --wui-color-bg-100: #141414;
522
- --wui-color-bg-125: #191a1a;
523
- --wui-color-bg-150: #1e1f1f;
524
- --wui-color-bg-175: #222525;
525
- --wui-color-bg-200: #272a2a;
526
- --wui-color-bg-225: #2c3030;
527
- --wui-color-bg-250: #313535;
528
- --wui-color-bg-275: #363b3b;
529
- --wui-color-bg-300: #3b4040;
530
- --wui-color-bg-325: #252525;
531
- --wui-color-bg-350: #ffffff;
532
-
533
- --wui-color-success-base-100: #26d962;
534
- --wui-color-success-base-125: #30a46b;
535
-
536
- --wui-color-warning-base-100: #f3a13f;
537
-
538
- --wui-color-error-base-100: #f25a67;
539
- --wui-color-error-base-125: #df4a34;
540
-
541
- --wui-color-blue-base-100: rgba(102, 125, 255, 1);
542
- --wui-color-blue-base-90: rgba(102, 125, 255, 0.9);
543
-
544
- --wui-color-success-glass-001: rgba(38, 217, 98, 0.01);
545
- --wui-color-success-glass-002: rgba(38, 217, 98, 0.02);
546
- --wui-color-success-glass-005: rgba(38, 217, 98, 0.05);
547
- --wui-color-success-glass-010: rgba(38, 217, 98, 0.1);
548
- --wui-color-success-glass-015: rgba(38, 217, 98, 0.15);
549
- --wui-color-success-glass-020: rgba(38, 217, 98, 0.2);
550
- --wui-color-success-glass-025: rgba(38, 217, 98, 0.25);
551
- --wui-color-success-glass-030: rgba(38, 217, 98, 0.3);
552
- --wui-color-success-glass-060: rgba(38, 217, 98, 0.6);
553
- --wui-color-success-glass-080: rgba(38, 217, 98, 0.8);
554
-
555
- --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2);
556
-
557
- --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2);
558
-
559
- --wui-color-error-glass-001: rgba(242, 90, 103, 0.01);
560
- --wui-color-error-glass-002: rgba(242, 90, 103, 0.02);
561
- --wui-color-error-glass-005: rgba(242, 90, 103, 0.05);
562
- --wui-color-error-glass-010: rgba(242, 90, 103, 0.1);
563
- --wui-color-error-glass-015: rgba(242, 90, 103, 0.15);
564
- --wui-color-error-glass-020: rgba(242, 90, 103, 0.2);
565
- --wui-color-error-glass-025: rgba(242, 90, 103, 0.25);
566
- --wui-color-error-glass-030: rgba(242, 90, 103, 0.3);
567
- --wui-color-error-glass-060: rgba(242, 90, 103, 0.6);
568
- --wui-color-error-glass-080: rgba(242, 90, 103, 0.8);
569
-
570
- --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2);
571
-
572
- --wui-color-gray-glass-001: rgba(255, 255, 255, 0.01);
573
- --wui-color-gray-glass-002: rgba(255, 255, 255, 0.02);
574
- --wui-color-gray-glass-005: rgba(255, 255, 255, 0.05);
575
- --wui-color-gray-glass-010: rgba(255, 255, 255, 0.1);
576
- --wui-color-gray-glass-015: rgba(255, 255, 255, 0.15);
577
- --wui-color-gray-glass-020: rgba(255, 255, 255, 0.2);
578
- --wui-color-gray-glass-025: rgba(255, 255, 255, 0.25);
579
- --wui-color-gray-glass-030: rgba(255, 255, 255, 0.3);
580
- --wui-color-gray-glass-060: rgba(255, 255, 255, 0.6);
581
- --wui-color-gray-glass-080: rgba(255, 255, 255, 0.8);
582
- --wui-color-gray-glass-090: rgba(255, 255, 255, 0.9);
583
-
584
- --wui-color-dark-glass-100: rgba(42, 42, 42, 1);
585
-
586
- --wui-icon-box-bg-error-base-100: #3c2426;
587
- --wui-icon-box-bg-blue-base-100: #20303f;
588
- --wui-icon-box-bg-success-base-100: #1f3a28;
589
- --wui-icon-box-bg-inverse-base-100: #243240;
590
-
591
- --wui-all-wallets-bg-100: #222b35;
592
-
593
- --wui-avatar-border-base: #252525;
594
-
595
- --wui-thumbnail-border-base: #252525;
596
-
597
- --wui-wallet-button-bg-base: var(--wui-color-bg-125);
598
-
599
- --w3m-card-embedded-shadow-color: rgb(17 17 18 / 25%);
600
- }
601
- `,dark:T.i`
602
- :root {
603
- --w3m-color-mix: ${T.r((t==null?void 0:t["--w3m-color-mix"])||"#000")};
604
- --w3m-accent: ${T.r(ns(t,"light")["--w3m-accent"])};
605
- --w3m-default: #000;
606
-
607
- --wui-color-modal-bg-base: ${T.r(ns(t,"light")["--w3m-background"])};
608
- --wui-color-accent-base-100: var(--w3m-accent);
609
-
610
- --wui-color-blueberry-100: hsla(231, 100%, 70%, 1);
611
- --wui-color-blueberry-090: hsla(231, 97%, 72%, 1);
612
- --wui-color-blueberry-080: hsla(231, 92%, 74%, 1);
613
-
614
- --wui-color-fg-100: #141414;
615
- --wui-color-fg-125: #2d3131;
616
- --wui-color-fg-150: #474d4d;
617
- --wui-color-fg-175: #636d6d;
618
- --wui-color-fg-200: #798686;
619
- --wui-color-fg-225: #828f8f;
620
- --wui-color-fg-250: #8b9797;
621
- --wui-color-fg-275: #95a0a0;
622
- --wui-color-fg-300: #9ea9a9;
623
- --wui-color-fg-325: #9a9a9a;
624
- --wui-color-fg-350: #d0d0d0;
625
-
626
- --wui-color-bg-100: #ffffff;
627
- --wui-color-bg-125: #f5fafa;
628
- --wui-color-bg-150: #f3f8f8;
629
- --wui-color-bg-175: #eef4f4;
630
- --wui-color-bg-200: #eaf1f1;
631
- --wui-color-bg-225: #e5eded;
632
- --wui-color-bg-250: #e1e9e9;
633
- --wui-color-bg-275: #dce7e7;
634
- --wui-color-bg-300: #d8e3e3;
635
- --wui-color-bg-325: #f3f3f3;
636
- --wui-color-bg-350: #202020;
637
-
638
- --wui-color-success-base-100: #26b562;
639
- --wui-color-success-base-125: #30a46b;
640
-
641
- --wui-color-warning-base-100: #f3a13f;
642
-
643
- --wui-color-error-base-100: #f05142;
644
- --wui-color-error-base-125: #df4a34;
645
-
646
- --wui-color-blue-base-100: rgba(102, 125, 255, 1);
647
- --wui-color-blue-base-90: rgba(102, 125, 255, 0.9);
648
-
649
- --wui-color-success-glass-001: rgba(38, 181, 98, 0.01);
650
- --wui-color-success-glass-002: rgba(38, 181, 98, 0.02);
651
- --wui-color-success-glass-005: rgba(38, 181, 98, 0.05);
652
- --wui-color-success-glass-010: rgba(38, 181, 98, 0.1);
653
- --wui-color-success-glass-015: rgba(38, 181, 98, 0.15);
654
- --wui-color-success-glass-020: rgba(38, 181, 98, 0.2);
655
- --wui-color-success-glass-025: rgba(38, 181, 98, 0.25);
656
- --wui-color-success-glass-030: rgba(38, 181, 98, 0.3);
657
- --wui-color-success-glass-060: rgba(38, 181, 98, 0.6);
658
- --wui-color-success-glass-080: rgba(38, 181, 98, 0.8);
659
-
660
- --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2);
661
-
662
- --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2);
663
-
664
- --wui-color-error-glass-001: rgba(240, 81, 66, 0.01);
665
- --wui-color-error-glass-002: rgba(240, 81, 66, 0.02);
666
- --wui-color-error-glass-005: rgba(240, 81, 66, 0.05);
667
- --wui-color-error-glass-010: rgba(240, 81, 66, 0.1);
668
- --wui-color-error-glass-015: rgba(240, 81, 66, 0.15);
669
- --wui-color-error-glass-020: rgba(240, 81, 66, 0.2);
670
- --wui-color-error-glass-025: rgba(240, 81, 66, 0.25);
671
- --wui-color-error-glass-030: rgba(240, 81, 66, 0.3);
672
- --wui-color-error-glass-060: rgba(240, 81, 66, 0.6);
673
- --wui-color-error-glass-080: rgba(240, 81, 66, 0.8);
674
-
675
- --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2);
676
-
677
- --wui-icon-box-bg-error-base-100: #f4dfdd;
678
- --wui-icon-box-bg-blue-base-100: #d9ecfb;
679
- --wui-icon-box-bg-success-base-100: #daf0e4;
680
- --wui-icon-box-bg-inverse-base-100: #dcecfc;
681
-
682
- --wui-all-wallets-bg-100: #e8f1fa;
683
-
684
- --wui-avatar-border-base: #f3f4f4;
685
-
686
- --wui-thumbnail-border-base: #eaefef;
687
-
688
- --wui-wallet-button-bg-base: var(--wui-color-bg-125);
689
-
690
- --wui-color-gray-glass-001: rgba(0, 0, 0, 0.01);
691
- --wui-color-gray-glass-002: rgba(0, 0, 0, 0.02);
692
- --wui-color-gray-glass-005: rgba(0, 0, 0, 0.05);
693
- --wui-color-gray-glass-010: rgba(0, 0, 0, 0.1);
694
- --wui-color-gray-glass-015: rgba(0, 0, 0, 0.15);
695
- --wui-color-gray-glass-020: rgba(0, 0, 0, 0.2);
696
- --wui-color-gray-glass-025: rgba(0, 0, 0, 0.25);
697
- --wui-color-gray-glass-030: rgba(0, 0, 0, 0.3);
698
- --wui-color-gray-glass-060: rgba(0, 0, 0, 0.6);
699
- --wui-color-gray-glass-080: rgba(0, 0, 0, 0.8);
700
- --wui-color-gray-glass-090: rgba(0, 0, 0, 0.9);
701
-
702
- --wui-color-dark-glass-100: rgba(233, 233, 233, 1);
703
-
704
- --w3m-card-embedded-shadow-color: rgb(224 225 233 / 25%);
705
- }
706
- `}}const Ev=T.i`
707
- *,
708
- *::after,
709
- *::before,
710
- :host {
711
- margin: 0;
712
- padding: 0;
713
- box-sizing: border-box;
714
- font-style: normal;
715
- text-rendering: optimizeSpeed;
716
- -webkit-font-smoothing: antialiased;
717
- -moz-osx-font-smoothing: grayscale;
718
- -webkit-tap-highlight-color: transparent;
719
- font-family: var(--wui-font-family);
720
- backface-visibility: hidden;
721
- }
722
- `,Cv=T.i`
723
- button,
724
- a {
725
- cursor: pointer;
726
- display: flex;
727
- justify-content: center;
728
- align-items: center;
729
- position: relative;
730
- transition:
731
- color var(--wui-duration-lg) var(--wui-ease-out-power-1),
732
- background-color var(--wui-duration-lg) var(--wui-ease-out-power-1),
733
- border var(--wui-duration-lg) var(--wui-ease-out-power-1),
734
- border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1),
735
- box-shadow var(--wui-duration-lg) var(--wui-ease-out-power-1);
736
- will-change: background-color, color, border, box-shadow, border-radius;
737
- outline: none;
738
- border: none;
739
- column-gap: var(--wui-spacing-3xs);
740
- background-color: transparent;
741
- text-decoration: none;
742
- }
743
-
744
- wui-flex {
745
- transition: border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1);
746
- will-change: border-radius;
747
- }
748
-
749
- button:disabled > wui-wallet-image,
750
- button:disabled > wui-all-wallets-image,
751
- button:disabled > wui-network-image,
752
- button:disabled > wui-image,
753
- button:disabled > wui-transaction-visual,
754
- button:disabled > wui-logo {
755
- filter: grayscale(1);
756
- }
757
-
758
- @media (hover: hover) and (pointer: fine) {
759
- button:hover:enabled {
760
- background-color: var(--wui-color-gray-glass-005);
761
- }
762
-
763
- button:active:enabled {
764
- background-color: var(--wui-color-gray-glass-010);
765
- }
766
- }
767
-
768
- button:disabled > wui-icon-box {
769
- opacity: 0.5;
770
- }
771
-
772
- input {
773
- border: none;
774
- outline: none;
775
- appearance: none;
776
- }
777
- `,Iv=T.i`
778
- .wui-color-inherit {
779
- color: var(--wui-color-inherit);
780
- }
781
-
782
- .wui-color-accent-100 {
783
- color: var(--wui-color-accent-100);
784
- }
785
-
786
- .wui-color-error-100 {
787
- color: var(--wui-color-error-100);
788
- }
789
-
790
- .wui-color-blue-100 {
791
- color: var(--wui-color-blue-100);
792
- }
793
-
794
- .wui-color-blue-90 {
795
- color: var(--wui-color-blue-90);
796
- }
797
-
798
- .wui-color-error-125 {
799
- color: var(--wui-color-error-125);
800
- }
801
-
802
- .wui-color-success-100 {
803
- color: var(--wui-color-success-100);
804
- }
805
-
806
- .wui-color-success-125 {
807
- color: var(--wui-color-success-125);
808
- }
809
-
810
- .wui-color-inverse-100 {
811
- color: var(--wui-color-inverse-100);
812
- }
813
-
814
- .wui-color-inverse-000 {
815
- color: var(--wui-color-inverse-000);
816
- }
817
-
818
- .wui-color-fg-100 {
819
- color: var(--wui-color-fg-100);
820
- }
821
-
822
- .wui-color-fg-200 {
823
- color: var(--wui-color-fg-200);
824
- }
825
-
826
- .wui-color-fg-300 {
827
- color: var(--wui-color-fg-300);
828
- }
829
-
830
- .wui-color-fg-325 {
831
- color: var(--wui-color-fg-325);
832
- }
833
-
834
- .wui-color-fg-350 {
835
- color: var(--wui-color-fg-350);
836
- }
837
-
838
- .wui-bg-color-inherit {
839
- background-color: var(--wui-color-inherit);
840
- }
841
-
842
- .wui-bg-color-blue-100 {
843
- background-color: var(--wui-color-accent-100);
844
- }
845
-
846
- .wui-bg-color-error-100 {
847
- background-color: var(--wui-color-error-100);
848
- }
849
-
850
- .wui-bg-color-error-125 {
851
- background-color: var(--wui-color-error-125);
852
- }
853
-
854
- .wui-bg-color-success-100 {
855
- background-color: var(--wui-color-success-100);
856
- }
857
-
858
- .wui-bg-color-success-125 {
859
- background-color: var(--wui-color-success-100);
860
- }
861
-
862
- .wui-bg-color-inverse-100 {
863
- background-color: var(--wui-color-inverse-100);
864
- }
865
-
866
- .wui-bg-color-inverse-000 {
867
- background-color: var(--wui-color-inverse-000);
868
- }
869
-
870
- .wui-bg-color-fg-100 {
871
- background-color: var(--wui-color-fg-100);
872
- }
873
-
874
- .wui-bg-color-fg-200 {
875
- background-color: var(--wui-color-fg-200);
876
- }
877
-
878
- .wui-bg-color-fg-300 {
879
- background-color: var(--wui-color-fg-300);
880
- }
881
-
882
- .wui-color-fg-325 {
883
- background-color: var(--wui-color-fg-325);
884
- }
885
-
886
- .wui-color-fg-350 {
887
- background-color: var(--wui-color-fg-350);
888
- }
889
- `,Tr={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]};function Zr(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const za=Zr({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"}),Ha=Zr({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"});Zr({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"});Zr({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});Zr({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const Nv={solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"]},mi={getMethodsByChainNamespace(t){return Nv[t]||[]},createDefaultNamespace(t){return{methods:this.getMethodsByChainNamespace(t),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(t,e){if(!e)return{...t};const s={...t},r=new Set;if(e.methods&&Object.keys(e.methods).forEach(i=>r.add(i)),e.chains&&Object.keys(e.chains).forEach(i=>r.add(i)),e.events&&Object.keys(e.events).forEach(i=>r.add(i)),e.rpcMap&&Object.keys(e.rpcMap).forEach(i=>{const[n]=i.split(":");n&&r.add(n)}),r.forEach(i=>{s[i]||(s[i]=this.createDefaultNamespace(i))}),e.methods&&Object.entries(e.methods).forEach(([i,n])=>{s[i]&&(s[i].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([i,n])=>{s[i]&&(s[i].chains=n)}),e.events&&Object.entries(e.events).forEach(([i,n])=>{s[i]&&(s[i].events=n)}),e.rpcMap){const i=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,c]=n.split(":");!a||!c||!s[a]||(s[a].rpcMap||(s[a].rpcMap={}),i.has(a)||(s[a].rpcMap={},i.add(a)),s[a].rpcMap[c]=o)})}return s},createNamespaces(t,e){const s=t.reduce((r,i)=>{const{id:n,chainNamespace:o,rpcUrls:a}=i,c=a.default.http[0];r[o]||(r[o]=this.createDefaultNamespace(o));const l=`${o}:${n}`,u=r[o];switch(u.chains.push(l),l){case za.caipNetworkId:u.chains.push(za.deprecatedCaipNetworkId);break;case Ha.caipNetworkId:u.chains.push(Ha.deprecatedCaipNetworkId);break}return u!=null&&u.rpcMap&&c&&(u.rpcMap[n]=c),r},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{var r;const e=await xr.resolveName(t);return((r=(Object.values(e==null?void 0:e.addresses)||[])[0])==null?void 0:r.address)||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const s=e.chains||[],r=e.accounts.map(i=>{const[n,o]=i.split(":");return`${n}:${o}`});return Array.from(new Set([...s,...r]))})},isSessionEventData(t){return typeof t=="object"&&t!==null&&"id"in t&&"topic"in t&&"params"in t&&typeof t.params=="object"&&t.params!==null&&"chainId"in t.params&&"event"in t.params&&typeof t.params.event=="object"&&t.params.event!==null},isOriginAllowed(t,e,s){for(const r of[...e,...s])if(r.includes("*")){const n=`^${r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(n,"u").test(t))return!0}else try{if(new URL(r).origin===t)return!0}catch{if(r===t)return!0}return!1}};class Cl{constructor({provider:e,namespace:s}){this.id=H.CONNECTOR_ID.WALLET_CONNECT,this.name=Ei.ConnectorNamesMap[H.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Ei.ConnectorImageIds[H.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=p.getCaipNetworks.bind(p),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=s}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const s=this.getCaipNetworks(),r=A.state.universalProviderConfigOverride,i=mi.createNamespaces(s,r);await this.provider.connect({optionalNamespaces:i})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(s=>s.caipNetworkId);return er.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:Av})}}const Av=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"];class Sv{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,this.getCaipNetworks=s=>p.getCaipNetworks(s),e&&this.construct(e)}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.getCaipNetworks(this.namespace)}setAuthProvider(e){this.addConnector({id:H.CONNECTOR_ID.AUTH,type:"AUTH",name:H.CONNECTOR_NAMES.AUTH,provider:e,imageId:Ei.ConnectorImageIds[H.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const s=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(r=>s.has(r.id)?!1:(s.add(r.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,s){W.setStatus(e,s)}on(e,s){var r;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(r=this.eventListeners.get(e))==null||r.add(s)}off(e,s){const r=this.eventListeners.get(e);r&&r.delete(s)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,s){const r=this.eventListeners.get(e);r&&r.forEach(i=>i(s))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){var n;const{caipNetwork:s,providerType:r}=e;if(!e.provider)return;const i="provider"in e.provider?e.provider.provider:e.provider;if(r==="WALLET_CONNECT"){i.setDefaultChain(s.caipNetworkId);return}if(i&&r==="AUTH"){const o=i,a=(n=W.state.preferredAccountTypes)==null?void 0:n[s.chainNamespace];await o.switchNetwork(s.caipNetworkId);const c=await o.getUser({chainId:s.caipNetworkId,preferredAccountType:a});this.emit("switchNetwork",c)}}getWalletConnectConnector(){const e=this.connectors.find(s=>s instanceof Cl);if(!e)throw new Error("WalletConnectConnector not found");return e}}class _v extends Sv{setUniversalProvider(e){this.addConnector(new Cl({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace}))}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){var i,n,o,a;const s=this.provider,r=((a=(o=(n=(i=s==null?void 0:s.session)==null?void 0:i.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const[,,l]=c.split(":");return l}).filter((c,l,u)=>u.indexOf(c)===l))||[];return Promise.resolve({accounts:r.map(c=>Z.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var n,o,a,c,l;if(!(e.caipNetwork&&be.BALANCE_SUPPORTED_CHAINS.includes((n=e.caipNetwork)==null?void 0:n.chainNamespace))||(o=e.caipNetwork)!=null&&o.testnet)return{balance:"0.00",symbol:((a=e.caipNetwork)==null?void 0:a.nativeCurrency.symbol)||""};if(W.state.balanceLoading&&e.chainId===((c=p.state.activeCaipNetwork)==null?void 0:c.id))return{balance:W.state.balance||"0.00",symbol:W.state.balanceSymbol||""};const i=(await W.fetchTokenBalance()).find(u=>{var d,g;return u.chainId===`${(d=e.caipNetwork)==null?void 0:d.chainNamespace}:${e.chainId}`&&u.symbol===((g=e.caipNetwork)==null?void 0:g.nativeCurrency.symbol)});return{balance:(i==null?void 0:i.quantity.numeric)||"0.00",symbol:(i==null?void 0:i.symbol)||((l=e.caipNetwork)==null?void 0:l.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,c;const{provider:s,message:r,address:i}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return((o=p.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===H.CHAIN.SOLANA?n=(await s.request({method:"solana_signMessage",params:{message:Bn.bs58.encode(new TextEncoder().encode(r)),pubkey:i}},(a=p.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:n=await s.request({method:"personal_sign",params:[r,i]},(c=p.state.activeCaipNetwork)==null?void 0:c.caipNetworkId),{signature:n}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){var i,n,o,a,c,l;const{caipNetwork:s}=e,r=this.getWalletConnectConnector();if(s.chainNamespace===H.CHAIN.EVM)try{await((i=r.provider)==null?void 0:i.request({method:"wallet_switchEthereumChain",params:[{chainId:Is.toHex(s.id)}]}))}catch(u){if(u.code===Tr.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||u.code===Tr.ERROR_INVALID_CHAIN_ID||u.code===Tr.ERROR_CODE_DEFAULT||((o=(n=u==null?void 0:u.data)==null?void 0:n.originalError)==null?void 0:o.code)===Tr.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=r.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:Is.toHex(s.id),rpcUrls:[(a=s==null?void 0:s.rpcUrls.chainDefault)==null?void 0:a.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[(c=s.blockExplorers)==null?void 0:c.default.url]}]}))}catch{throw new Error("Chain is not supported")}}r.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(r=>r.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}const Pv=["email","socials","swaps","onramp","activity","reownBranding"],di={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e.filter(s=>s!=="email"):!1},processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?be.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?be.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?be.DEFAULT_REMOTE_FEATURES.onramp:!1:t},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.activity:!!t},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.reownBranding:!!t}},Tv={localSettingsOverridden:new Set,getApiConfig(t,e){return e==null?void 0:e.find(s=>s.id===t)},addWarning(t,e){if(t!==void 0){const s=di[e],r=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(r)}},processFeature(t,e,s,r,i){const n=di[t],o=e[n.localFeatureName];if(i&&!n.isAvailableOnBasic)return!1;if(r){const a=this.getApiConfig(n.apiFeatureName,s);return(a==null?void 0:a.config)===null?this.processFallbackFeature(t,o):a!=null&&a.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return di[t].processApi(e)},processFallbackFeature(t,e){return di[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,s=t.features||{};this.localSettingsOverridden.clear();let r=null,i=!1;try{r=await K.fetchProjectConfig(),i=r!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const n=i&&!e?be.DEFAULT_REMOTE_FEATURES:be.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of Pv){const a=this.processFeature(o,s,r,i,e);Object.assign(n,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),be.DEFAULT_REMOTE_FEATURES}if(i&&this.localSettingsOverridden.size>0){const o=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;rs.open({shortMessage:"Local configuration ignored",longMessage:`[Reown Config Notice] ${o}`},"warning")}return n}};class Ov{constructor(e){this.chainNamespaces=[],this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,r)=>{var i,n,o,a;if(s){const c=(n=(i=p.getNetworkData(s))==null?void 0:i.requestedCaipNetworks)==null?void 0:n.find(d=>d.id===r);if(c)return c;const l=(o=p.getNetworkData(s))==null?void 0:o.caipNetwork;return l||((a=p.getRequestedCaipNetworks(s).filter(d=>d.chainNamespace===s))==null?void 0:a[0])}return p.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>p.getCaipNetworks(s),this.getActiveChainNamespace=()=>p.state.activeChain,this.setRequestedCaipNetworks=(s,r)=>{p.setRequestedCaipNetworks(s,r)},this.getApprovedCaipNetworkIds=()=>p.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>p.state.activeChain===s||!s?p.state.activeCaipAddress:p.getAccountProp("caipAddress",s),this.setClientId=s=>{X.setClientId(s)},this.getProvider=s=>Pe.getProvider(s),this.getProviderType=s=>Pe.getProviderId(s),this.getPreferredAccountType=s=>{var r;return(r=W.state.preferredAccountTypes)==null?void 0:r[s]},this.setCaipAddress=(s,r)=>{W.setCaipAddress(s,r),s&&A.state.enableEmbedded&&this.close()},this.setBalance=(s,r,i)=>{W.setBalance(s,r,i)},this.setProfileName=(s,r)=>{W.setProfileName(s,r)},this.setProfileImage=(s,r)=>{W.setProfileImage(s,r)},this.setUser=(s,r)=>{W.setUser(s,r)},this.resetAccount=s=>{W.resetAccount(s)},this.setCaipNetwork=s=>{p.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,r)=>{p.setChainNetworkData(r,{caipNetwork:s})},this.setAllAccounts=(s,r)=>{W.setAllAccounts(s,r),A.setHasMultipleAddresses((s==null?void 0:s.length)>1)},this.setStatus=(s,r)=>{W.setStatus(s,r),B.isConnected()?q.setConnectionStatus("connected"):q.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>p.getAccountProp("address",s),this.setConnectors=s=>{const r=[...B.state.allConnectors,...s];B.setConnectors(r)},this.setConnections=(s,r)=>{J.setConnections(s,r)},this.fetchIdentity=s=>X.fetchIdentity(s),this.getReownName=s=>xr.getNamesForAddress(s),this.getConnectors=()=>B.getConnectors(),this.getConnectorImage=s=>Mn.getConnectorImage(s),this.setConnectedWalletInfo=(s,r)=>{const i=Pe.getProviderId(r),n=s?{...s,type:i}:void 0;W.setConnectedWalletInfo(n,r)},this.getIsConnectedState=()=>!!p.state.activeCaipAddress,this.addAddressLabel=(s,r,i)=>{W.addAddressLabel(s,r,i)},this.removeAddressLabel=(s,r)=>{W.removeAddressLabel(s,r)},this.getAddress=s=>p.state.activeChain===s||!s?W.state.address:p.getAccountProp("address",s),this.setApprovedCaipNetworksData=s=>p.setApprovedCaipNetworksData(s),this.resetNetwork=s=>{p.resetNetwork(s)},this.addConnector=s=>{B.addConnector(s)},this.resetWcConnection=()=>{J.resetWcConnection()},this.setAddressExplorerUrl=(s,r)=>{W.setAddressExplorerUrl(s,r)},this.setSmartAccountDeployed=(s,r)=>{W.setSmartAccountDeployed(s,r)},this.setSmartAccountEnabledNetworks=(s,r)=>{p.setSmartAccountEnabledNetworks(s,r)},this.setPreferredAccountType=(s,r)=>{W.setPreferredAccountType(s,r)},this.setEIP6963Enabled=s=>{A.setEIP6963Enabled(s)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,s){const r=e==null?void 0:e.map(n=>n.namespace).filter(n=>!!n);if(r!=null&&r.length)return[...new Set(r)];const i=s==null?void 0:s.map(n=>n.chainNamespace);return[...new Set(i)]}async initialize(e){var s,r,i;this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),await this.syncExistingConnection(),this.remoteFeatures=await Tv.fetchRemoteFeatures(e),A.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&ln.setOnrampProviders(this.remoteFeatures.onramp),((s=A.state.remoteFeatures)!=null&&s.email||Array.isArray((r=A.state.remoteFeatures)==null?void 0:r.socials)&&((i=A.state.remoteFeatures)==null?void 0:i.socials.length)>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){const e=await K.fetchAllowedOrigins();if(e&&Z.isClient()){const s=window.location.origin;mi.isOriginAllowed(s,e,Tr.DEFAULT_ALLOWED_ANCESTORS)||rs.open(Gs.ALERT_ERRORS.INVALID_APP_CONFIGURATION,"error")}else rs.open(Gs.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}sendInitializeEvent(e){var r;const{...s}=e;delete s.adapters,delete s.universalProvider,_e.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(i=>i.id),siweConfig:{options:((r=e.siweConfig)==null?void 0:r.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&nt.setThemeMode(e.themeMode),e.themeVariables&&nt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");p.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const s=this.getDefaultNetwork();s&&p.setActiveCaipNetwork(s)}initializeConnectionController(e){J.setWcBasic(e.basic??!1)}initializeConnectorController(){B.initialize(this.chainNamespaces)}initializeProjectSettings(e){A.setProjectId(e.projectId),A.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){var o;A.setDebug(e.debug!==!1),A.setEnableWalletConnect(e.enableWalletConnect!==!1),A.setEnableWalletGuide(e.enableWalletGuide!==!1),A.setEnableWallets(e.enableWallets!==!1),A.setEIP6963Enabled(e.enableEIP6963!==!1),A.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),A.setEnableAuthLogger(e.enableAuthLogger!==!1),A.setCustomRpcUrls(e.customRpcUrls),A.setEnableEmbedded(e.enableEmbedded),A.setAllWallets(e.allWallets),A.setIncludeWalletIds(e.includeWalletIds),A.setExcludeWalletIds(e.excludeWalletIds),A.setFeaturedWalletIds(e.featuredWalletIds),A.setTokens(e.tokens),A.setTermsConditionsUrl(e.termsConditionsUrl),A.setPrivacyPolicyUrl(e.privacyPolicyUrl),A.setCustomWallets(e.customWallets),A.setFeatures(e.features),A.setAllowUnsupportedChain(e.allowUnsupportedChain),A.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),A.setPreferUniversalLinks(e.experimental_preferUniversalLinks),A.setDefaultAccountTypes(e.defaultAccountTypes);const s=q.getPreferredAccountTypes()||{},r={...A.state.defaultAccountTypes,...s};W.setPreferredAccountTypes(r);const i=this.getDefaultMetaData();if(!e.metadata&&i&&(e.metadata=i),A.setMetadata(e.metadata),A.setDisableAppend(e.disableAppend),A.setEnableEmbedded(e.enableEmbedded),A.setSIWX(e.siwx),!e.projectId){rs.open(Gs.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((o=e.adapters)==null?void 0:o.find(a=>a.namespace===H.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");A.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,s,r,i;return Z.isClient()?{name:((s=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:s.textContent)||"",description:((r=document.querySelector('meta[property="og:description"]'))==null?void 0:r.content)||"",url:window.location.origin,icons:[((i=document.querySelector('link[rel~="icon"]'))==null?void 0:i.href)||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const r=Ys.getUnsupportedNetwork(`${s}:${e}`);p.setActiveCaipNetwork(r)}}getDefaultNetwork(){return Ys.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,s){return Ys.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return Ys.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(i=>{var n;return i.id===((n=e.defaultNetwork)==null?void 0:n.id)});return s?Ys.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectNamespace(e){try{const s=this.getAdapter(e),r=Pe.getProvider(e),i=Pe.getProviderId(e),{caipAddress:n}=p.getAccountData(e)||{};this.setLoading(!0,e),n&&(s!=null&&s.disconnect)&&await s.disconnect({provider:r,providerType:i}),q.removeConnectedNamespace(e),Pe.resetChain(e),this.setUser(void 0,e),this.setStatus("disconnected",e),this.setConnectedWalletInfo(void 0,e),B.removeConnectorId(e),p.resetAccount(e),p.resetNetwork(e),this.setLoading(!1,e)}catch(s){throw this.setLoading(!1,e),new Error(`Failed to disconnect chain ${e}: ${s.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var n;const e=p.state.activeChain,s=this.getAdapter(e),r=(n=this.getCaipNetwork(e))==null?void 0:n.id;if(!s)throw new Error("Adapter not found");const i=await s.connectWalletConnect(r);this.close(),this.setClientId((i==null?void 0:i.clientId)||null),q.setConnectedNamespaces([...p.state.chains.keys()]),this.chainNamespaces.forEach(o=>{B.setConnectorId(ts.CONNECTOR_TYPE_WALLET_CONNECT,o)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:s,type:r,provider:i,chain:n,caipNetwork:o,socialUri:a})=>{var w,f,v,b,E,S;const c=p.state.activeChain,l=n||c,u=this.getAdapter(l);if(n&&n!==c&&!o){const R=this.getCaipNetworks().find(_=>_.chainNamespace===n);R&&this.setCaipNetwork(R)}if(!u)throw new Error("Adapter not found");const d=this.getCaipNetwork(l),g=await u.connect({id:e,info:s,type:r,provider:i,socialUri:a,chainId:(o==null?void 0:o.id)||(d==null?void 0:d.id),rpcUrl:((v=(f=(w=o==null?void 0:o.rpcUrls)==null?void 0:w.default)==null?void 0:f.http)==null?void 0:v[0])||((S=(E=(b=d==null?void 0:d.rpcUrls)==null?void 0:b.default)==null?void 0:E.http)==null?void 0:S[0])});if(!g)return;q.addConnectedNamespace(l),this.syncProvider({...g,chainNamespace:l});const m=W.state.allAccounts,{accounts:y}=(m==null?void 0:m.length)>0?{accounts:[...m]}:await u.getAccounts({namespace:l,id:e});this.setAllAccounts(y,l),this.setStatus("connected",l),this.syncConnectedWalletInfo(l)},reconnectExternal:async({id:e,info:s,type:r,provider:i})=>{var a;const n=p.state.activeChain,o=this.getAdapter(n);o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:s,type:r,provider:i,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),q.addConnectedNamespace(n),this.syncConnectedWalletInfo(n))},disconnect:async e=>{const s=fv(e);try{const r=await Promise.allSettled(s.map(async([n])=>this.disconnectNamespace(n)));pe.resetSend(),J.resetWcConnection(),await er.clearSessions(),B.setFilterByNamespace(void 0);const i=r.filter(n=>n.status==="rejected");if(i.length>0)throw new Error(i.map(n=>n.reason.message).join(", "));q.deleteConnectedSocialProvider(),_e.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:e||"all"}})}catch(r){throw new Error(`Failed to disconnect chains: ${r.message}`)}},checkInstalled:e=>e?e.some(s=>{var r;return!!((r=window.ethereum)!=null&&r[String(s)])}):!!window.ethereum,signMessage:async e=>{const s=this.getAdapter(p.state.activeChain),r=await(s==null?void 0:s.signMessage({message:e,address:W.state.address,provider:Pe.getProvider(p.state.activeChain)}));return(r==null?void 0:r.signature)||""},sendTransaction:async e=>{const s=e.chainNamespace;if(be.SEND_SUPPORTED_NAMESPACES.includes(s)){const r=this.getAdapter(p.state.activeChain),i=Pe.getProvider(s),n=await(r==null?void 0:r.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}));return(n==null?void 0:n.hash)||""}return""},estimateGas:async e=>{if(e.chainNamespace===H.CHAIN.EVM){const s=this.getAdapter(p.state.activeChain),r=Pe.getProvider(p.state.activeChain),i=this.getCaipNetwork();if(!i)throw new Error("CaipNetwork is undefined");const n=await(s==null?void 0:s.estimateGas({...e,provider:r,caipNetwork:i}));return(n==null?void 0:n.gas)||0n}return 0n},getEnsAvatar:async()=>{var e;return await this.syncIdentity({address:W.state.address,chainId:Number((e=this.getCaipNetwork())==null?void 0:e.id),chainNamespace:p.state.activeChain}),W.state.profileImage||!1},getEnsAddress:async e=>await mi.resolveReownName(e),writeContract:async e=>{const s=this.getAdapter(p.state.activeChain),r=this.getCaipNetwork(),i=this.getCaipAddress(),n=Pe.getProvider(p.state.activeChain);if(!r||!i)throw new Error("CaipNetwork or CaipAddress is undefined");const o=await(s==null?void 0:s.writeContract({...e,caipNetwork:r,provider:n,caipAddress:i}));return o==null?void 0:o.hash},parseUnits:(e,s)=>{const r=this.getAdapter(p.state.activeChain);return(r==null?void 0:r.parseUnits({value:e,decimals:s}))??0n},formatUnits:(e,s)=>{const r=this.getAdapter(p.state.activeChain);return(r==null?void 0:r.formatUnits({value:e,decimals:s}))??"0"},getCapabilities:async e=>{const s=this.getAdapter(p.state.activeChain);return await(s==null?void 0:s.getCapabilities(e))},grantPermissions:async e=>{const s=this.getAdapter(p.state.activeChain);return await(s==null?void 0:s.grantPermissions(e))},revokePermissions:async e=>{const s=this.getAdapter(p.state.activeChain);return s!=null&&s.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>{const s=this.getAdapter(p.state.activeChain);return await(s==null?void 0:s.walletGetAssets(e))??{}},updateBalance:e=>{const s=this.getCaipNetwork(e);!s||!W.state.address||this.updateNativeBalance(W.state.address,s==null?void 0:s.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},J.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){var s,r,i,n,o;if(Pe.getProviderId(p.state.activeChain)===ts.CONNECTOR_TYPE_WALLET_CONNECT){const a=(r=(s=this.universalProvider)==null?void 0:s.session)==null?void 0:r.namespaces;return{supportsAllNetworks:((o=(n=(i=this.universalProvider)==null?void 0:i.session)==null?void 0:n.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const i=Pe.getProvider(s),n=Pe.getProviderId(s);if(e.chainNamespace===p.state.activeChain){const o=this.getAdapter(s);await(o==null?void 0:o.switchNetwork({caipNetwork:e,provider:i,providerType:n}))}else if(this.setCaipNetwork(e),n===ts.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(s);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:s})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(s=>{const r=s.chains||[],i=s.accounts.map(n=>{const{chainId:o,chainNamespace:a}=Yt.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...r,...i]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,r)=>{var n;const i=e==null?void 0:e.find(o=>o.namespace===r);return i?(i.construct({namespace:r,projectId:(n=this.options)==null?void 0:n.projectId,networks:this.getCaipNetworks()}),s[r]=i):s[r]=new _v({namespace:r,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){var s;this.onConnectors(e),this.listenAdapter(e),await((s=this.chainAdapters)==null?void 0:s[e].syncConnectors(this.options,this)),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){const s=this.getAdapter(e);s==null||s.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const r=q.getConnectionStatus();r==="connected"?this.setStatus("connecting",e):r==="disconnected"?(q.clearAddressCache(),this.setStatus(r,e)):this.setStatus(r,e),s.on("switchNetwork",({address:i,chainId:n})=>{const o=this.getCaipNetworks().find(l=>l.id===n||l.caipNetworkId===n),a=p.state.activeChain===e,c=p.getAccountProp("address",e);if(o){const l=a&&i?i:c;l&&this.syncAccount({address:l,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),s.on("disconnect",this.disconnect.bind(this,e)),s.on("connections",i=>{this.setConnections(i,e)}),s.on("pendingTransactions",()=>{const i=W.state.address,n=p.state.activeCaipNetwork;!i||!(n!=null&&n.id)||this.updateNativeBalance(i,n.id,n.chainNamespace)}),s.on("accountChanged",({address:i,chainId:n})=>{var a,c;const o=p.state.activeChain===e;o&&n?this.syncAccount({address:i,chainId:n,chainNamespace:e}):o&&((a=p.state.activeCaipNetwork)!=null&&a.id)?this.syncAccount({address:i,chainId:(c=p.state.activeCaipNetwork)==null?void 0:c.id,chainNamespace:e}):this.syncAccountInfo(i,n,e),this.syncAllAccounts(e)})}async createUniversalProviderForAdapter(e){var s,r,i;await this.getUniversalProvider(),this.universalProvider&&((i=(r=(s=this.chainAdapters)==null?void 0:s[e])==null?void 0:r.setUniversalProvider)==null||i.call(r,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{e===H.CHAIN.EVM&&Z.isSafeApp()&&B.setConnectorId(H.CONNECTOR_ID.SAFE,e);const s=B.getConnectorId(e);switch(this.setStatus("connecting",e),s){case H.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case H.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){var a,c,l;const s=this.getAdapter(e),r=B.getConnectorId(e),i=this.getCaipNetwork(e),o=B.getConnectors(e).find(u=>u.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(i!=null&&i.id))throw new Error("CaipNetwork not found");const u=await(s==null?void 0:s.syncConnection({namespace:e,id:o.id,chainId:i.id,rpcUrl:(l=(c=(a=i==null?void 0:i.rpcUrls)==null?void 0:a.default)==null?void 0:c.http)==null?void 0:l[0]}));if(u){const d=await(s==null?void 0:s.getAccounts({namespace:e,id:o.id}));d&&d.accounts.length>0?this.setAllAccounts(d.accounts,e):this.setAllAccounts([Z.createAccount(e,u.address,"eoa")],e),this.syncProvider({...u,chainNamespace:e}),await this.syncAccount({...u,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async s=>{var a,c,l,u,d;const r=this.getAdapter(s),i=((u=(l=(c=(a=this.universalProvider)==null?void 0:a.session)==null?void 0:c.namespaces)==null?void 0:l[s])==null?void 0:u.accounts)||[],n=(d=p.state.activeCaipNetwork)==null?void 0:d.id,o=i.find(g=>{const{chainId:m}=Yt.parseCaipAddress(g);return m===(n==null?void 0:n.toString())})||i[0];if(o){const g=Yt.validateCaipAddress(o),{chainId:m,address:y}=Yt.parseCaipAddress(g);if(Pe.setProviderId(s,ts.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&p.state.activeCaipNetwork&&(r==null?void 0:r.namespace)!==H.CHAIN.EVM){const w=r==null?void 0:r.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:p.state.activeCaipNetwork});Pe.setProvider(s,w)}else Pe.setProvider(s,this.universalProvider);B.setConnectorId(H.CONNECTOR_ID.WALLET_CONNECT,s),q.addConnectedNamespace(s),this.syncWalletConnectAccounts(s),await this.syncAccount({address:y,chainId:m,chainNamespace:s})}else this.setStatus("disconnected",s);this.syncConnectedWalletInfo(s),await p.setApprovedCaipNetworksData(s)});await Promise.all(e)}syncWalletConnectAccounts(e){var r,i,n,o,a;const s=(a=(o=(n=(i=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:i.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const{address:l}=Yt.parseCaipAddress(c);return l}).filter((c,l,u)=>u.indexOf(c)===l);s&&this.setAllAccounts(s.map(c=>Z.createAccount(e,c,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:s,id:r,chainNamespace:i}){Pe.setProviderId(i,e),Pe.setProvider(i,s),B.setConnectorId(r,i)}async syncAllAccounts(e){const s=B.getConnectorId(e);if(!s)return;const r=this.getAdapter(e),i=await(r==null?void 0:r.getAccounts({namespace:e,id:s}));i&&i.accounts.length>0&&this.setAllAccounts(i.accounts,e)}async syncAccount(e){var d,g;const s=e.chainNamespace===p.state.activeChain,r=p.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:i,chainId:n,chainNamespace:o}=e,{chainId:a}=q.getActiveNetworkProps(),c=n||a,l=((d=p.state.activeCaipNetwork)==null?void 0:d.name)===H.UNSUPPORTED_NETWORK_NAME,u=p.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!u)&&c){let m=this.getCaipNetworks().find(f=>f.id.toString()===c.toString()),y=this.getCaipNetworks().find(f=>f.chainNamespace===o);if(!u&&!m&&!y){const f=this.getApprovedCaipNetworkIds()||[],v=f.find(E=>{var S;return((S=Yt.parseCaipNetworkId(E))==null?void 0:S.chainId)===c.toString()}),b=f.find(E=>{var S;return((S=Yt.parseCaipNetworkId(E))==null?void 0:S.chainNamespace)===o});m=this.getCaipNetworks().find(E=>E.caipNetworkId===v),y=this.getCaipNetworks().find(E=>E.caipNetworkId===b||"deprecatedCaipNetworkId"in E&&E.deprecatedCaipNetworkId===b)}const w=m||y;(w==null?void 0:w.chainNamespace)===p.state.activeChain?A.state.enableNetworkSwitch&&!A.state.allowUnsupportedChain&&((g=p.state.activeCaipNetwork)==null?void 0:g.name)===H.UNSUPPORTED_NETWORK_NAME?p.showUnsupportedChainUI():this.setCaipNetwork(w):s||r&&this.setCaipNetworkOfNamespace(r,o),this.syncConnectedWalletInfo(o),Qn.isLowerCaseMatch(i,W.state.address)||this.syncAccountInfo(i,w==null?void 0:w.id,o),s?await this.syncBalance({address:i,chainId:w==null?void 0:w.id,chainNamespace:o}):await this.syncBalance({address:i,chainId:r==null?void 0:r.id,chainNamespace:o})}}async syncAccountInfo(e,s,r){const i=this.getCaipAddress(r),n=s||(i==null?void 0:i.split(":")[1]);if(!n)return;const o=`${r}:${n}:${e}`;this.setCaipAddress(o,r),await this.syncIdentity({address:e,chainId:n,chainNamespace:r})}async syncReownName(e,s){try{const r=await this.getReownName(e);if(r[0]){const i=r[0];this.setProfileName(i.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){var i;const s=B.getConnectorId(e),r=Pe.getProviderId(e);if(r===ts.CONNECTOR_TYPE_ANNOUNCED||r===ts.CONNECTOR_TYPE_INJECTED){if(s){const n=this.getConnectors().find(o=>o.id===s);if(n){const{info:o,name:a,imageUrl:c}=n,l=c||this.getConnectorImage(n);this.setConnectedWalletInfo({name:a,icon:l,...o},e)}}}else if(r===ts.CONNECTOR_TYPE_WALLET_CONNECT){const n=Pe.getProvider(e);n!=null&&n.session&&this.setConnectedWalletInfo({...n.session.peer.metadata,name:n.session.peer.metadata.name,icon:(i=n.session.peer.metadata.icons)==null?void 0:i[0]},e)}else if(s&&s===H.CONNECTOR_ID.COINBASE){const n=this.getConnectors().find(o=>o.id===H.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(n)},e)}}async syncBalance(e){!Va.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(r=>{var i;return r.id.toString()===((i=e.chainId)==null?void 0:i.toString())})||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,r){const i=this.getAdapter(r),n=p.getCaipNetworkByNamespace(r,s);if(i){const o=await i.getBalance({address:e,chainId:s,caipNetwork:n,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,r),o}}async initializeUniversalAdapter(){var r,i,n,o,a,c,l,u,d,g;const e=wv.createLogger((m,...y)=>{m&&this.handleAlertError(m),console.error(...y)}),s={projectId:(r=this.options)==null?void 0:r.projectId,metadata:{name:(i=this.options)!=null&&i.metadata?(n=this.options)==null?void 0:n.metadata.name:"",description:(o=this.options)!=null&&o.metadata?(a=this.options)==null?void 0:a.metadata.description:"",url:(c=this.options)!=null&&c.metadata?(l=this.options)==null?void 0:l.metadata.url:"",icons:(u=this.options)!=null&&u.metadata?(d=this.options)==null?void 0:d.metadata.icons:[""]},logger:e};A.setManualWCControl(!!((g=this.options)!=null&&g.manualWCControl)),this.universalProvider=this.options.universalProvider??await Zn.init(s),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{J.setUri(e)}),this.universalProvider.on("connect",J.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),J.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{const s=this.getCaipNetworks().find(i=>i.id==e),r=this.getCaipNetwork();if(!s){this.setUnsupportedNetwork(e);return}(r==null?void 0:r.id)!==(s==null?void 0:s.id)&&this.setCaipNetwork(s)}),this.universalProvider.on("session_event",e=>{if(mi.isSessionEventData(e)){const{name:s,data:r}=e.params.event;s==="accountsChanged"&&Array.isArray(r)&&Z.isCaipAddress(r[0])&&this.syncAccount(Yt.parseCaipAddress(r[0]))}}))}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&Z.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){_e.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const s=Object.entries(Gs.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[r,i]=s??[],{message:n,alertErrorKey:o}=i??{};if(r&&n&&!this.reportedAlertErrors[r]){const a=Gs.ALERT_ERRORS[o];a&&(rs.open(a,"error"),this.reportedAlertErrors[r]=!0)}}getAdapter(e){var s;if(e)return(s=this.chainAdapters)==null?void 0:s[e]}createAdapter(e){var i;if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const r=e;r.namespace=s,r.construct({namespace:s,projectId:(i=this.options)==null?void 0:i.projectId,networks:this.getCaipNetworks()}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=r)}async open(e){if(await this.injectModalUi(),e!=null&&e.uri&&J.setUri(e.uri),e!=null&&e.arguments)switch(e==null?void 0:e.view){case"Swap":return Le.open({...e,data:{swap:e.arguments}})}return Le.open(e)}async close(){await this.injectModalUi(),Le.close()}setLoading(e,s){Le.setLoading(e,s)}async disconnect(e){await J.disconnect(e)}getSIWX(){return A.state.siwx}getError(){return""}getChainId(){var e;return(e=p.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e){const s=this.getCaipNetworks().find(r=>r.id===e.id);if(!s){rs.open(Gs.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await p.switchActiveNetwork(s)}getWalletProvider(){return p.state.activeChain?Pe.state.providers[p.state.activeChain]:null}getWalletProviderType(){return Pe.getProviderId(p.state.activeChain)}subscribeProviders(e){return Pe.subscribeProviders(e)}getThemeMode(){return nt.state.themeMode}getThemeVariables(){return nt.state.themeVariables}setThemeMode(e){nt.setThemeMode(e),El(nt.state.themeMode)}setTermsConditionsUrl(e){A.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){A.setPrivacyPolicyUrl(e)}setThemeVariables(e){nt.setThemeVariables(e),vv(nt.state.themeVariables)}subscribeTheme(e){return nt.subscribe(e)}getWalletInfo(){return W.state.connectedWalletInfo}getAccount(e){var o;const s=B.getAuthConnector(e),r=p.getAccountData(e),i=p.state.activeChain,n=q.getConnectedConnectorId(e||i);if(r)return{allAccounts:r.allAccounts,caipAddress:r.caipAddress,address:Z.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:s&&n===H.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:q.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:(o=r.preferredAccountTypes)==null?void 0:o[e||i],isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const r=()=>{const i=this.getAccount(s);i&&e(i)};s?p.subscribeChainProp("accountState",r,s):p.subscribe(r),B.subscribe(r)}subscribeNetwork(e){return p.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s==null?void 0:s.id,caipNetworkId:s==null?void 0:s.caipNetworkId})})}subscribeWalletInfo(e){return W.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){W.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){p.subscribeKey("activeCaipNetwork",e)}getState(){return as.state}subscribeState(e){return as.subscribe(e)}showErrorMessage(e){Et.showError(e)}showSuccessMessage(e){Et.showSuccess(e)}getEvent(){return{..._e.state}}subscribeEvents(e){return _e.subscribe(e)}replace(e){ne.replace(e)}redirect(e){ne.push(e)}popTransactionStack(e){ne.popTransactionStack(e)}isOpen(){return Le.state.open}isTransactionStackEmpty(){return ne.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){A.setFeatures(e)}updateRemoteFeatures(e){A.setRemoteFeatures(e)}updateOptions(e){const r={...A.state||{},...e};A.setOptions(r)}setConnectMethodsOrder(e){A.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){A.setWalletFeaturesOrder(e)}setCollapseWallets(e){A.setCollapseWallets(e)}setSocialsOrder(e){A.setSocialsOrder(e)}getConnectMethodsOrder(){return Ii.getConnectOrderMethod(A.state.features,B.getConnectors())}addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const r=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(i=>i.id===r.id)||p.addNetwork(r)}removeNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(i=>i.id===s)&&p.removeNetwork(e,s)}}let Ka=!1;class Il extends Ov{async open(e){B.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&J.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!Ka&&Z.isClient()){if(await Promise.resolve().then(()=>require("./basic-E2M-9h1u.js")),await Promise.resolve().then(()=>require("./w3m-modal-CrfHWSrF.js")),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!A.state.disableAppend&&!A.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}Ka=!0}}}const kv="1.7.8";function xv(t){return new Il({...t,basic:!0,sdkVersion:`html-core-${kv}`})}const Rv=Object.freeze(Object.defineProperty({__proto__:null,AppKit:Il,createAppKit:xv},Symbol.toStringTag,{value:"Module"}));exports.AccountController=W;exports.AlertController=rs;exports.ApiController=K;exports.AssetController=vt;exports.AssetUtil=Mn;exports.ChainController=p;exports.ConnectionController=J;exports.ConnectorController=B;exports.ConnectorUtil=Dr;exports.ConstantsUtil=H;exports.ConstantsUtil$1=be;exports.ConstantsUtil$2=vl;exports.CoreHelperUtil=Z;exports.EventsController=_e;exports.ModalController=Le;exports.OptionsController=A;exports.RouterController=ne;exports.SIWXUtil=er;exports.SnackController=Et;exports.StorageUtil=q;exports.ThemeController=nt;exports.WalletUtil=Ii;exports.colorStyles=Iv;exports.core=Rv;exports.elementStyles=Cv;exports.initializeTheming=bv;exports.resetStyles=Ev;exports.withErrorBoundary=at;