@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.
- package/README.md +1 -1
- package/dist/assets/{basic-ChNCp6rI.js → basic-PUjrTVXb.js} +1 -1
- package/dist/assets/{evm-DSirgd5b.js → evm-CO5UWnAY.js} +2 -2
- package/dist/assets/{index-L-lC4rqb.js → index-1lzfHdT2.js} +1 -1
- package/dist/assets/{index-CHfaLf5J.js → index-DBVZDYF7.js} +1 -1
- package/dist/assets/index-DKlPX3ZI.js +1 -0
- package/dist/assets/{index-BtCrMDAu.js → index-Ddk7n7Ti.js} +1 -1
- package/dist/assets/{index-HhyysXFu.js → index-DyUmO4PR.js} +1 -1
- package/dist/assets/{index-BiwA3Bbq.js → index-MMzKxP1N.js} +1 -1
- package/dist/assets/{secp256k1-Cd7rIav0.js → secp256k1-0LtSM2L1.js} +1 -1
- package/dist/assets/{secp256k1-BQBOR8e3.js → secp256k1-DwTU3j1N.js} +1 -1
- package/dist/assets/{solana-DcwLWeKT.js → solana-DlGdMBSL.js} +4 -4
- package/dist/assets/{w3m-modal-DdptuLHe.js → w3m-modal-DD9Jgepz.js} +1 -1
- package/dist/main.js +72 -70
- package/dist/src/AppRouter.d.ts.map +1 -1
- package/dist/src/config/mainnet/tokens.d.ts.map +1 -1
- package/dist/src/config/testnet/tokens.d.ts.map +1 -1
- package/dist/src/config/tokens.d.ts +1 -1
- package/dist/src/config/tokens.d.ts.map +1 -1
- package/dist/src/exports/index.d.ts +2 -2
- package/dist/src/exports/index.d.ts.map +1 -1
- package/dist/src/hooks/useFetchQuotes.d.ts.map +1 -1
- package/dist/src/icons/Chains/PLUME.d.ts.map +1 -1
- package/dist/src/icons/PoweredBy.d.ts.map +1 -1
- package/dist/src/icons/Routing.d.ts +5 -0
- package/dist/src/icons/Routing.d.ts.map +1 -0
- package/dist/src/icons/Tokens/PLUME.d.ts.map +1 -1
- package/dist/src/store/transferInput.d.ts +1 -1
- package/dist/src/store/transferInput.d.ts.map +1 -1
- package/dist/src/utils/coingecko.d.ts.map +1 -1
- package/dist/src/utils/formatNumber.d.ts +23 -0
- package/dist/src/utils/formatNumber.d.ts.map +1 -0
- package/dist/src/utils/index.d.ts +3 -1
- package/dist/src/utils/index.d.ts.map +1 -1
- package/dist/src/utils/routes.d.ts +12 -0
- package/dist/src/utils/routes.d.ts.map +1 -0
- package/dist/src/views/v2/Bridge/AmountInput/index.d.ts.map +1 -1
- package/dist/src/views/v2/Bridge/AssetPicker/TokenItem.d.ts.map +1 -1
- package/dist/src/views/v2/Bridge/Routes/SingleRoute.d.ts.map +1 -1
- package/dist/src/views/v2/Redeem/TransactionDetails/index.d.ts.map +1 -1
- package/dist/src/views/v3/Bridge/AmountInput/index.d.ts.map +1 -1
- package/dist/src/views/v3/Bridge/AssetPicker/TokenItem.d.ts.map +1 -1
- package/dist/src/views/v3/Bridge/AssetPicker/index.d.ts.map +1 -1
- package/dist/src/views/v3/Bridge/GasSlider/index.d.ts.map +1 -1
- package/dist/src/views/v3/Bridge/Routes/Eta.d.ts +6 -0
- package/dist/src/views/v3/Bridge/Routes/Eta.d.ts.map +1 -0
- package/dist/src/views/v3/Bridge/Routes/RouteBadge.d.ts.map +1 -1
- package/dist/src/views/v3/Bridge/Routes/RoutesBottomSheet.d.ts +7 -6
- package/dist/src/views/v3/Bridge/Routes/RoutesBottomSheet.d.ts.map +1 -1
- package/dist/src/views/v3/Bridge/Routes/RoutesLink.d.ts +7 -0
- package/dist/src/views/v3/Bridge/Routes/RoutesLink.d.ts.map +1 -0
- package/dist/src/views/v3/Bridge/Routes/RoutesList.d.ts +2 -1
- package/dist/src/views/v3/Bridge/Routes/RoutesList.d.ts.map +1 -1
- package/dist/src/views/v3/Bridge/Routes/RoutesLoader.d.ts +4 -0
- package/dist/src/views/v3/Bridge/Routes/RoutesLoader.d.ts.map +1 -0
- package/dist/src/views/v3/Bridge/Routes/RoutesModal.d.ts +6 -5
- package/dist/src/views/v3/Bridge/Routes/RoutesModal.d.ts.map +1 -1
- package/dist/src/views/v3/Bridge/Routes/SingleRoute.d.ts +1 -0
- package/dist/src/views/v3/Bridge/Routes/SingleRoute.d.ts.map +1 -1
- package/dist/src/views/v3/Bridge/Routes/index.d.ts.map +1 -1
- package/dist/src/views/v3/Redeem/TransactionDetails/index.d.ts.map +1 -1
- package/lib/account-Br8E7RB6.js +1 -0
- package/lib/{account-BTK2b2Fv.mjs → account-CVa_3S2g.mjs} +1 -1
- package/lib/{address-8wLqn60W.mjs → address-BApwdEpr.mjs} +96 -96
- package/lib/address-BwQqFkyh.js +1 -0
- package/lib/address-C2pxq9b2.js +1 -0
- package/lib/{address-n0gAFMrZ.mjs → address-f6joE_ig.mjs} +12 -12
- package/lib/aptos-CMRGggVs.js +2 -0
- package/lib/{aptos-CK-j196x.js → aptos-CTKQNmlP.js} +1 -1
- package/lib/{aptos-B-DJQlwt.mjs → aptos-CfFbx7uf.mjs} +9 -9
- package/lib/{aptos-Bwcz9wZX.mjs → aptos-fozuppXh.mjs} +3 -3
- package/lib/{basic-DHWVLmCq.mjs → basic-BA2aRJJn.mjs} +2 -2
- package/lib/{basic-B5ZFelC_.js → basic-DUWaF2I0.js} +1 -1
- package/lib/{basic-E2M-9h1u.js → basic-DeiUayOA.js} +1 -1
- package/lib/{basic-Pour9Ggp.mjs → basic-DoC8u7J8.mjs} +2 -2
- package/lib/{blake2b-C5HyObld.mjs → blake2b-BGxWUAjG.mjs} +23 -23
- package/lib/blake2b-Fj1aPKgL.js +1 -0
- package/lib/{browser-ponyfill-jK8MKVVg.mjs → browser-ponyfill-D5AN8ZPp.mjs} +1 -1
- package/lib/browser-ponyfill-Dn6gsMYK.js +2 -0
- package/lib/{chain-Bm6u6eUF.mjs → chain-DAw2I5H8.mjs} +1 -1
- package/lib/chain-DnPXlO8g.js +1 -0
- package/lib/chunk-KJH4KKG6-BjF7YUcU.js +470 -0
- package/lib/{chunk-KJH4KKG6-DJsu-Y-X.mjs → chunk-KJH4KKG6-DmVjhXO7.mjs} +144 -144
- package/lib/{constants-Cf2YMjNo.js → constants-BtNs_2F4.js} +1 -1
- package/lib/{constants-B7AbX6qr.mjs → constants-Dcc2nVaW.mjs} +3 -3
- package/lib/contract-BEHYQLvJ.js +1 -0
- package/lib/{contract-llnN6ki0.mjs → contract-BkMAZomO.mjs} +123 -123
- package/lib/{core-CF5c7Vev.mjs → core-BHV42Qa0.mjs} +25 -26
- package/lib/core-CV23yxnG.js +889 -0
- package/lib/create-CHcGblj6.js +1 -0
- package/lib/{create-Dm87_0zG.mjs → create-CKLtL7hr.mjs} +1 -1
- package/lib/{evm-BYIGg8e4.mjs → evm-Bf7qbM19.mjs} +42 -42
- package/lib/{evm-B2hUWkt7.js → evm-ClWkquRx.js} +2 -2
- package/lib/{evm-fvvpk-li.mjs → evm-DhMoy8cH.mjs} +6 -6
- package/lib/{evm-DFNbMHoa.js → evm-tXmzU9Xp.js} +2 -2
- package/lib/executor.js +1 -1
- package/lib/executor.mjs +145 -138
- package/lib/hosted.js +1 -1
- package/lib/hosted.mjs +1 -1
- package/lib/{index-Cwo5AKUC.mjs → index-1rCCpdwd.mjs} +5 -5
- package/lib/{index-DBCa3k0j.mjs → index-3HvzWPL7.mjs} +9 -9
- package/lib/{index-MOwE6ses.mjs → index-B7ztYPhr.mjs} +21 -22
- package/lib/index-BM-0SeYB.js +1 -0
- package/lib/{index-DiQ8Ytrt.mjs → index-BTnpftLz.mjs} +1 -1
- package/lib/{index-BiCMaXJS.js → index-BWQMi6Rj.js} +1 -1
- package/lib/index-BbgKw2pu.js +1 -0
- package/lib/index-BblcpkoK.js +1 -0
- package/lib/index-Bfblsmud.js +1 -0
- package/lib/{index-C_0yAOSX.mjs → index-BfkFXEnG.mjs} +25082 -24072
- package/lib/{index-fi1sh8vr.mjs → index-BijBPDRn.mjs} +2 -2
- package/lib/index-BoquY9R2.js +337 -0
- package/lib/index-C2NtsO9Q.js +1 -0
- package/lib/{index-CNuk-XLX.mjs → index-C4JmrizV.mjs} +4 -4
- package/lib/index-C8TtXpOf.js +1 -0
- package/lib/index-CB8kOyIP.js +1 -0
- package/lib/index-CInVjUCW.js +1 -0
- package/lib/{index-BF11RebI.mjs → index-CLTklDbp.mjs} +1 -1
- package/lib/index-CQvgeH_r.js +1 -0
- package/lib/{index-DzYjoSJp.mjs → index-CUnOYRFQ.mjs} +23 -24
- package/lib/{index-DGh9LzN1.mjs → index-CWe_BTdo.mjs} +31 -31
- package/lib/{index-2Bz1Np4K.mjs → index-CZ91lJ9M.mjs} +5 -5
- package/lib/{index-Dgy1FO7C.js → index-CgyVnj6U.js} +1 -1
- package/lib/{index-BzJcFdt_.mjs → index-Clr2JjoJ.mjs} +44 -44
- package/lib/index-CnnCCv6Q.js +1 -0
- package/lib/{index-CJnRWlFf.mjs → index-CwxGLNEk.mjs} +48 -49
- package/lib/index-D7BLfz05.js +1 -0
- package/lib/index-DM7C-wvQ.js +3 -0
- package/lib/{index-DhIh3xiW.mjs → index-DNy_sNGr.mjs} +8 -8
- package/lib/{index-BZaRg0yd.mjs → index-DVcaDWmz.mjs} +1 -1
- package/lib/{index-CsAigASU.mjs → index-DWOP9OBp.mjs} +17 -17
- package/lib/{index-CTLz8Fz0.mjs → index-Dda5qc2t.mjs} +13 -14
- package/lib/{index-CLBXF_zH.mjs → index-DeaiBvpG.mjs} +16 -16
- package/lib/index-HOuGP-7b.js +1 -0
- package/lib/{index-Dt2uNp-N.mjs → index-KZve3tYJ.mjs} +4 -4
- package/lib/{index-CJDBidKv.mjs → index-SIyXqCAN.mjs} +41 -41
- package/lib/index-WhVYPMUr.js +1 -0
- package/lib/index-hmjT4xa7.js +1 -0
- package/lib/index-ledagFNU.js +1 -0
- package/lib/index-pbRVlgcN.js +1 -0
- package/lib/{index-BpQXUhR4.mjs → index-qK7AyMAk.mjs} +23 -27
- package/lib/index-ttZu99PZ.js +1 -0
- package/lib/{index.es-BqRBGIq6.mjs → index.es-BXRQf6Oi.mjs} +25 -26
- package/lib/index.es-BjGaOok5.js +11 -0
- package/lib/index.es-D6S74vhi.js +27 -0
- package/lib/{index.es-DgCZuUzB.mjs → index.es-cOw8juwf.mjs} +741 -737
- package/lib/index.js +1 -1
- package/lib/index.mjs +17 -16
- package/lib/mayan.js +3 -3
- package/lib/mayan.mjs +918 -891
- package/lib/mint-CL36R6ED.js +1 -0
- package/lib/{mint-Dc-VsiAn.mjs → mint-DunEG1jV.mjs} +32 -33
- package/lib/ntt.js +1 -1
- package/lib/ntt.mjs +2332 -2373
- package/lib/platform-7vCWzCny.js +1 -0
- package/lib/platform-BKhoO9So.js +1 -0
- package/lib/{platform-B95L0Vxv.mjs → platform-BN6LFtXE.mjs} +16 -16
- package/lib/{platform-DnP_1wGA.mjs → platform-BYLu9SzP.mjs} +4 -4
- package/lib/platform-Bbe26nx7.js +1 -0
- package/lib/{platform-DiG7WY9Z.mjs → platform-DCgWqmh1.mjs} +4 -4
- package/lib/{provider-jsonrpc-CRABh2gN.mjs → provider-jsonrpc-Bmgnrmpy.mjs} +155 -155
- package/lib/provider-jsonrpc-CbtP2Ffg.js +1 -0
- package/lib/{secp256k1-zHHDNAlH.mjs → secp256k1-BDQEvyHq.mjs} +1 -1
- package/lib/{secp256k1-obBDPYM-.mjs → secp256k1-C77Oh9AA.mjs} +1 -1
- package/lib/{secp256k1-2hq3Jk4g.mjs → secp256k1-CCn2vlXj.mjs} +1 -1
- package/lib/{secp256k1-B94G4gyy.js → secp256k1-CHAR40au.js} +1 -1
- package/lib/{secp256k1-DCcAh19h.js → secp256k1-D-DmPYcJ.js} +1 -1
- package/lib/{secp256k1-CjndBUS7.js → secp256k1-DYWDlveU.js} +1 -1
- package/lib/{signer-N_ccpPOz.mjs → signer-BIcn81N5.mjs} +18 -18
- package/lib/signer-H7atraks.js +1 -0
- package/lib/{solana-_Ha4YgiP.mjs → solana-B0QSg7B3.mjs} +30 -30
- package/lib/solana-Cs5VyB20.js +900 -0
- package/lib/solana-uvHG8JV5.js +1 -0
- package/lib/solana-zyfOlbhb.mjs +18 -0
- package/lib/{solanaEmbed.esm-DK5RIquB.mjs → solanaEmbed.esm-BqdznDuW.mjs} +623 -622
- package/lib/solanaEmbed.esm-D8vtESE6.js +10 -0
- package/lib/src/AppRouter.d.ts.map +1 -1
- package/lib/src/config/mainnet/tokens.d.ts.map +1 -1
- package/lib/src/config/testnet/tokens.d.ts.map +1 -1
- package/lib/src/config/tokens.d.ts +1 -1
- package/lib/src/config/tokens.d.ts.map +1 -1
- package/lib/src/exports/index.d.ts +2 -2
- package/lib/src/exports/index.d.ts.map +1 -1
- package/lib/src/hooks/useFetchQuotes.d.ts.map +1 -1
- package/lib/src/icons/Chains/PLUME.d.ts.map +1 -1
- package/lib/src/icons/PoweredBy.d.ts.map +1 -1
- package/lib/src/icons/Routing.d.ts +5 -0
- package/lib/src/icons/Routing.d.ts.map +1 -0
- package/lib/src/icons/Tokens/PLUME.d.ts.map +1 -1
- package/lib/src/store/transferInput.d.ts +1 -1
- package/lib/src/store/transferInput.d.ts.map +1 -1
- package/lib/src/utils/coingecko.d.ts.map +1 -1
- package/lib/src/utils/formatNumber.d.ts +23 -0
- package/lib/src/utils/formatNumber.d.ts.map +1 -0
- package/lib/src/utils/index.d.ts +3 -1
- package/lib/src/utils/index.d.ts.map +1 -1
- package/lib/src/utils/routes.d.ts +12 -0
- package/lib/src/utils/routes.d.ts.map +1 -0
- package/lib/src/views/v2/Bridge/AmountInput/index.d.ts.map +1 -1
- package/lib/src/views/v2/Bridge/AssetPicker/TokenItem.d.ts.map +1 -1
- package/lib/src/views/v2/Bridge/Routes/SingleRoute.d.ts.map +1 -1
- package/lib/src/views/v2/Redeem/TransactionDetails/index.d.ts.map +1 -1
- package/lib/src/views/v3/Bridge/AmountInput/index.d.ts.map +1 -1
- package/lib/src/views/v3/Bridge/AssetPicker/TokenItem.d.ts.map +1 -1
- package/lib/src/views/v3/Bridge/AssetPicker/index.d.ts.map +1 -1
- package/lib/src/views/v3/Bridge/GasSlider/index.d.ts.map +1 -1
- package/lib/src/views/v3/Bridge/Routes/Eta.d.ts +6 -0
- package/lib/src/views/v3/Bridge/Routes/Eta.d.ts.map +1 -0
- package/lib/src/views/v3/Bridge/Routes/RouteBadge.d.ts.map +1 -1
- package/lib/src/views/v3/Bridge/Routes/RoutesBottomSheet.d.ts +7 -6
- package/lib/src/views/v3/Bridge/Routes/RoutesBottomSheet.d.ts.map +1 -1
- package/lib/src/views/v3/Bridge/Routes/RoutesLink.d.ts +7 -0
- package/lib/src/views/v3/Bridge/Routes/RoutesLink.d.ts.map +1 -0
- package/lib/src/views/v3/Bridge/Routes/RoutesList.d.ts +2 -1
- package/lib/src/views/v3/Bridge/Routes/RoutesList.d.ts.map +1 -1
- package/lib/src/views/v3/Bridge/Routes/RoutesLoader.d.ts +4 -0
- package/lib/src/views/v3/Bridge/Routes/RoutesLoader.d.ts.map +1 -0
- package/lib/src/views/v3/Bridge/Routes/RoutesModal.d.ts +6 -5
- package/lib/src/views/v3/Bridge/Routes/RoutesModal.d.ts.map +1 -1
- package/lib/src/views/v3/Bridge/Routes/SingleRoute.d.ts +1 -0
- package/lib/src/views/v3/Bridge/Routes/SingleRoute.d.ts.map +1 -1
- package/lib/src/views/v3/Bridge/Routes/index.d.ts.map +1 -1
- package/lib/src/views/v3/Redeem/TransactionDetails/index.d.ts.map +1 -1
- package/lib/{sui-CQcQ6w_P.mjs → sui-B38DyOqM.mjs} +44 -44
- package/lib/{sui-BplKFZQu.mjs → sui-BpfnZR4f.mjs} +3 -3
- package/lib/sui-CT9MWY38.js +1 -0
- package/lib/{sui-_hvmCvD8.js → sui-DXQAMRQJ.js} +1 -1
- package/lib/{tokens-DNv0ZNvU.js → tokens-CmINcwKk.js} +31 -31
- package/lib/{tokens-Dl4YwW18.mjs → tokens-YxAPPVy3.mjs} +1726 -1724
- package/lib/transfer-BQ72fByU.js +1 -0
- package/lib/transfer-bTW0j9yh.mjs +58 -0
- package/lib/units-Ckije3Qv.js +1 -0
- package/lib/{units-DPWUSE6J.mjs → units-CtyvuzxQ.mjs} +13 -13
- package/lib/unsignedTransaction-C6Qp42VS.js +1 -0
- package/lib/{unsignedTransaction-DwcUilyN.mjs → unsignedTransaction-CXB-QCUC.mjs} +18 -18
- package/lib/{w3m-modal-BJILsxDp.mjs → w3m-modal-B7LUHLWC.mjs} +2 -2
- package/lib/{w3m-modal-D4CpFxO2.mjs → w3m-modal-BOTzBqbc.mjs} +2 -2
- package/lib/{w3m-modal-CrfHWSrF.js → w3m-modal-BTb03-7B.js} +1 -1
- package/lib/{w3m-modal-CBG2MSPp.js → w3m-modal-xmdf4r6V.js} +1 -1
- package/lib/web3-COTIsLs8.js +22 -0
- package/lib/{address-B-XN4tFw.mjs → web3-DYVeiqSa.mjs} +6599 -6576
- package/package.json +32 -32
- package/dist/assets/index-BWPgrXHs.js +0 -1
- package/lib/account-cRt2xMoW.js +0 -1
- package/lib/address-BGujeWtN.js +0 -22
- package/lib/address-C7DIAk4M.js +0 -1
- package/lib/address-KNhRm6oe.js +0 -1
- package/lib/aptos-f5TqmvqV.js +0 -2
- package/lib/blake2b-B-MRXUPb.js +0 -1
- package/lib/browser-ponyfill-CE6vRkjp.js +0 -2
- package/lib/chain-Hsn22HAP.js +0 -1
- package/lib/chunk-KJH4KKG6-CoyI75Ig.js +0 -470
- package/lib/contract-D2fTrJgn.js +0 -1
- package/lib/core-v0G9f7LX.js +0 -889
- package/lib/create-DoZZ7ciL.js +0 -1
- package/lib/index-B8-KKWD-.js +0 -1
- package/lib/index-BHbvgOMD.js +0 -1
- package/lib/index-BHfUgvSV.js +0 -1
- package/lib/index-BTKC7Hou.js +0 -1
- package/lib/index-BWXglAWd.js +0 -1
- package/lib/index-Bpp8C4u8.js +0 -1
- package/lib/index-CF2fHBHJ.js +0 -3
- package/lib/index-CTPz98nv.js +0 -1
- package/lib/index-ClMoiji-.js +0 -1
- package/lib/index-ClsVcH6F.js +0 -1
- package/lib/index-CqOI6LVu.js +0 -1
- package/lib/index-DCz_4mcz.js +0 -1
- package/lib/index-DKksdvND.js +0 -335
- package/lib/index-DRv3ZpVL.js +0 -1
- package/lib/index-DYqo8IhM.js +0 -1
- package/lib/index-DZubce9o.js +0 -1
- package/lib/index-DprM_IpB.js +0 -1
- package/lib/index-DshEQYMA.js +0 -1
- package/lib/index-JrM783SN.js +0 -1
- package/lib/index.es-C6YhioMN.js +0 -27
- package/lib/index.es-D3Xxxr8I.js +0 -11
- package/lib/mint-DlXC3sGi.js +0 -1
- package/lib/platform-B1XoDKoN.js +0 -1
- package/lib/platform-COuZC5Zc.js +0 -1
- package/lib/platform-NG3efAb2.js +0 -1
- package/lib/provider-jsonrpc-pXNHQF7n.js +0 -1
- package/lib/signer-CCa6npZ3.js +0 -1
- package/lib/solana-BJ3aReZw.mjs +0 -18
- package/lib/solana-BwyVgP30.js +0 -1
- package/lib/solana-CanFuMgA.js +0 -900
- package/lib/solanaEmbed.esm-C--1F7Lx.js +0 -10
- package/lib/sui-Bs83Gy5Z.js +0 -1
- package/lib/units-BvcKDiAx.js +0 -1
- package/lib/unsignedTransaction-dN_5EJf5.js +0 -1
- package/lib/web3-Bu_6UejS.mjs +0 -67
- package/lib/web3-Doz_0RHD.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/solanaEmbed.esm-BKA1kzuW.js","main.js","main.css","assets/index-VWaDGczM.js","assets/secp256k1-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/solanaEmbed.esm-BKA1kzuW.js","main.js","main.css","assets/index-VWaDGczM.js","assets/secp256k1-DwTU3j1N.js","assets/util-C_16CLeU.js","assets/wallets-B2cUxj0w.js","assets/signer-CDzv4nqH.js","assets/chain-DoGROKtK.js","assets/index.es-GwBHo_TA.js","assets/lit-element-CtNM2Rln.js","assets/http-B-zgidyQ.js","assets/secp256k1-0LtSM2L1.js","assets/basic-PUjrTVXb.js","assets/class-map-HYQXoBBZ.js","assets/index-1lzfHdT2.js","assets/ref-T9--LDvW.js","assets/w3m-modal-DD9Jgepz.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var Fv=Object.defineProperty;var qv=(s,e,t)=>e in s?Fv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var $t=(s,e,t)=>qv(s,typeof e!="symbol"?e+"":e,t);import{O as Bv,P as di,f as T,a0 as Zo,a3 as Hv,c as ja,l as Wv,d as us,a4 as Qn,V as vc,a5 as Ic,W as Vv,a6 as pd,Y as gd,_ as Ra,a7 as aw,a8 as wl,a2 as dh,a1 as Ti,a9 as Kv,aa as Gv,C as ph,ab as Yv}from"../main.js";import{a as Qv}from"./util-C_16CLeU.js";import{g as Zv}from"./wallets-B2cUxj0w.js";import{i as ac,d as Jv,a as Xv}from"./signer-CDzv4nqH.js";import{I as js,g as cw,f as et,t as $e,c as N,C as lw,a as rr,b as qc,d as hw,e as uw,s as Bn,h as Un,k as Di,A as yu,E as Me,i as dw,j as pw,y as Ye,l as cs,r as fi,O as Zn,o as tt,m as gw,n as Jn,p as Xn,q as nr,P as Ec,Q as fw,u as ww,v as yw,w as Ac,x as Ds,z as Bc,B as Ct,D as gt,F as Gt,G as lt}from"./index.es-GwBHo_TA.js";import{B as po,p as ct,s as hs,a as Ns,b as Jo,r as $r,c as e0,f as fd,d as zs,i as Ln}from"./lit-element-CtNM2Rln.js";import{f as t0,x as yl,t as wd}from"./http-B-zgidyQ.js";class Ft extends Error{constructor(e,t){super(e),this.error=t}}class or extends Ft{constructor(){super(...arguments),this.name="WalletNotReadyError"}}class s0 extends Ft{constructor(){super(...arguments),this.name="WalletLoadError"}}class xn extends Ft{constructor(){super(...arguments),this.name="WalletConfigError"}}class Hc extends Ft{constructor(){super(...arguments),this.name="WalletConnectionError"}}class mw extends Ft{constructor(){super(...arguments),this.name="WalletDisconnectedError"}}class ha extends Ft{constructor(){super(...arguments),this.name="WalletDisconnectionError"}}class ks extends Ft{constructor(){super(...arguments),this.name="WalletAccountError"}}class Ur extends Ft{constructor(){super(...arguments),this.name="WalletPublicKeyError"}}class Ge extends Ft{constructor(){super(...arguments),this.name="WalletNotConnectedError"}}class _r extends Ft{constructor(){super(...arguments),this.name="WalletSendTransactionError"}}class at extends Ft{constructor(){super(...arguments),this.name="WalletSignTransactionError"}}class ua extends Ft{constructor(){super(...arguments),this.name="WalletSignMessageError"}}class yd extends Ft{constructor(){super(...arguments),this.name="WalletSignInError"}}class i0 extends Ft{constructor(){super(...arguments),this.name="WalletWindowClosedError"}}var de;(function(s){s.Installed="Installed",s.NotDetected="NotDetected",s.Loadable="Loadable",s.Unsupported="Unsupported"})(de||(de={}));class bw extends Bv{get connected(){return!!this.publicKey}async autoConnect(){await this.connect()}async prepareTransaction(e,t,i={}){const r=this.publicKey;if(!r)throw new Ge;return e.feePayer=e.feePayer||r,e.recentBlockhash=e.recentBlockhash||(await t.getLatestBlockhash({commitment:i.preflightCommitment,minContextSlot:i.minContextSlot})).blockhash,e}}function da(s){if(typeof window>"u"||typeof document>"u")return;const e=[];function t(){if(s())for(const n of e)n()}const i=setInterval(t,1e3);e.push(()=>clearInterval(i)),document.readyState==="loading"&&(document.addEventListener("DOMContentLoaded",t,{once:!0}),e.push(()=>document.removeEventListener("DOMContentLoaded",t))),document.readyState!=="complete"&&(window.addEventListener("load",t,{once:!0}),e.push(()=>window.removeEventListener("load",t))),t()}function $i(s){return"version"in s}class mu extends bw{async sendTransaction(e,t,i={}){let r=!0;try{if($i(e)){if(!this.supportedTransactionVersions)throw new _r("Sending versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(e.version))throw new _r(`Sending transaction version ${e.version} isn't supported by this wallet`);try{e=await this.signTransaction(e);const n=e.serialize();return await t.sendRawTransaction(n,i)}catch(n){throw n instanceof at?(r=!1,n):new _r(n==null?void 0:n.message,n)}}else try{const{signers:n,...o}=i;e=await this.prepareTransaction(e,t,o),n!=null&&n.length&&e.partialSign(...n),e=await this.signTransaction(e);const a=e.serialize();return await t.sendRawTransaction(a,o)}catch(n){throw n instanceof at?(r=!1,n):new _r(n==null?void 0:n.message,n)}}catch(n){throw r&&this.emit("error",n),n}}async signAllTransactions(e){for(const i of e)if($i(i)){if(!this.supportedTransactionVersions)throw new at("Signing versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(i.version))throw new at(`Signing transaction version ${i.version} isn't supported by this wallet`)}const t=[];for(const i of e)t.push(await this.signTransaction(i));return t}}class pa extends mu{}const Gi="solana:signAndSendTransaction",ml="solana:signIn",go="solana:signMessage",Rt="solana:signTransaction",vw="standard:connect",md="standard:disconnect",Iw="standard:events";function r0(s){return vw in s.features&&Iw in s.features&&(Gi in s.features||Rt in s.features)}var Xo;(function(s){s.Mainnet="mainnet-beta",s.Testnet="testnet",s.Devnet="devnet"})(Xo||(Xo={}));const n0="Bitget";class o0 extends pa{constructor(e={}){super(),this.name=n0,this.url="https://web3.bitget.com",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgdmlld0JveD0iMCAwIDUxMiA1MTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiBmaWxsPSIjMDAxRjI5Ii8+CjxwYXRoIGQ9Ik0yMTkuOTQ4IDk1LjcwMjJDMjAxLjYyMyA5NS42OTI5IDE4My4zMyA5NS42ODM1IDE2NC45NDEgOTUuNzExNkMxNTMuODIyIDk1LjcxMTYgMTQ5LjY1MSAxMDkuNjcxIDE1Ny45MjEgMTE3LjkzOUwyODMuMDk4IDI0My4xMTdDMjg3LjAwNCAyNDYuNjkgMjg5LjQ0MSAyNTAuNTc0IDI4OS41MyAyNTUuNjkzQzI4OS40NDEgMjYwLjgxMiAyODcuMDA0IDI2NC42OTYgMjgzLjA5OCAyNjguMjY5TDE1Ny45MjEgMzkzLjQ0NkMxNDkuNjUxIDQwMS43MTUgMTUzLjgyMiA0MTUuNjc0IDE2NC45NDEgNDE1LjY3NEMxODMuMzMgNDE1LjcwMiAyMDEuNjIzIDQxNS42OTMgMjE5Ljk0OCA0MTUuNjgzQzIyOS4xMjIgNDE1LjY3OSAyMzguMzA1IDQxNS42NzQgMjQ3LjUxMSA0MTUuNjc0QzI1OS41NTUgNDE1LjY3NCAyNjYuNzIgNDA5LjI0IDI3My4xNTQgNDAyLjgwNUwzODYuMDQ3IDI4OS45MTJDMzk1LjA1NyAyODAuOTAyIDQwMy4xMTkgMjY4LjkzOSA0MDMuMDA5IDI1NS42OTNDNDAzLjExOSAyNDIuNDQ3IDM5NS4wNTcgMjMwLjQ4NCAzODYuMDQ3IDIyMS40NzRMMjczLjE1NCAxMDguNThDMjY2LjcyIDEwMi4xNDYgMjU5LjU1NSA5NS43MTE2IDI0Ny41MTEgOTUuNzExNkMyMzguMzA1IDk1LjcxMTYgMjI5LjEyMiA5NS43MDY5IDIxOS45NDggOTUuNzAyMloiIGZpbGw9IiMwMEYwRkYiLz4KPC9zdmc+Cg==",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?de.Unsupported:de.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==de.Unsupported&&da(()=>{var t,i;return(i=(t=window.bitkeep)==null?void 0:t.solana)!=null&&i.isBitKeep?(this._readyState=de.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==de.Installed)throw new or;this._connecting=!0;const e=window.bitkeep.solana;let t;try{t=await e.getAccount()}catch(r){throw new ks(r==null?void 0:r.message,r)}let i;try{i=new di(t)}catch(r){throw new Ur(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch(t){this.emit("error",new ha(t==null?void 0:t.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)||e}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)||e}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{const{signature:i}=await t.signMessage(e);return i}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const a0="Clover";class c0 extends pa{constructor(e={}){super(),this.name=a0,this.url="https://clv.org",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDgiIGhlaWdodD0iNDgiIHZpZXdCb3g9IjAgMCA0OCA0OCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTM2LjQ4IDBIMTEuNTJDNS4xNTc2OCAwIDAgNS4xNTc2OCAwIDExLjUyVjM2LjQ4QzAgNDIuODQyMyA1LjE1NzY4IDQ4IDExLjUyIDQ4SDM2LjQ4QzQyLjg0MjMgNDggNDggNDIuODQyMyA0OCAzNi40OFYxMS41MkM0OCA1LjE1NzY4IDQyLjg0MjMgMCAzNi40OCAwWiIgZmlsbD0idXJsKCNwYWludDBfbGluZWFyXzc5MTBfMTYzMzUxKSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTI0LjAwMDYgMzkuMzYwNkMzMi40ODM3IDM5LjM2MDYgMzkuMzYwNiAzMi40ODM3IDM5LjM2MDYgMjQuMDAwNkMzOS4zNjA2IDE1LjUxNzUgMzIuNDgzNyA4LjY0MDYyIDI0LjAwMDYgOC42NDA2MkMxNS41MTc1IDguNjQwNjIgOC42NDA2MiAxNS41MTc1IDguNjQwNjIgMjQuMDAwNkM4LjY0MDYyIDMyLjQ4MzcgMTUuNTE3NSAzOS4zNjA2IDI0LjAwMDYgMzkuMzYwNlpNMjEuMjg5OSAxNS44Njg4SDI2LjcxMVYyMS4zNDdIMjEuMjkwNFYyNi42NTRIMjYuNzExVjMyLjEzMjJIMjEuMjg5OVYyNi44MjUySDE1Ljg2OTNWMjEuMzQ3SDIxLjI4OTlWMTUuODY4OFpNMjYuNzEyIDIxLjM0N0gzMi4xMzMxVjI2LjgyNTJIMjYuNzEyVjIxLjM0N1oiIGZpbGw9ImJsYWNrIi8+CjxkZWZzPgo8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfNzkxMF8xNjMzNTEiIHgxPSI0OCIgeTE9Ii0xLjQzMDUxZS0wNiIgeDI9IjEuNDMwNTFlLTA2IiB5Mj0iNDgiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KPHN0b3Agc3RvcC1jb2xvcj0iI0E5RkZFMCIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM4NkQ1RkYiLz4KPC9saW5lYXJHcmFkaWVudD4KPC9kZWZzPgo8L3N2Zz4=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?de.Unsupported:de.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==de.Unsupported&&da(()=>{var t;return(t=window.clover_solana)!=null&&t.isCloverWallet?(this._readyState=de.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==de.Installed)throw new or;this._connecting=!0;const e=window.clover_solana;let t;try{t=await e.getAccount()}catch(r){throw new ks(r==null?void 0:r.message,r)}let i;try{i=new di(t)}catch(r){throw new Ur(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){this._wallet&&(this._wallet=null,this._publicKey=null),this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)||e}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)||e}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{const{signature:i}=await t.signMessage(e);return Uint8Array.from(i)}catch(i){throw new ua(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}function l0(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const h=s.charAt(l),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let h=0,u=0,d=0;const g=l.length;for(;d!==g&&l[d]===0;)d++,h++;const p=(g-d)*n+1>>>0,f=new Uint8Array(p);for(;d!==g;){let w=l[d],E=0;for(let A=p-1;(w!==0||E<u)&&A!==-1;A--,E++)w+=256*f[A]>>>0,f[A]=w%t>>>0,w=w/t>>>0;if(w!==0)throw new Error("Non-zero carry");u=E,d++}let b=p-u;for(;b!==p&&f[b]===0;)b++;let m=i.repeat(h);for(;b<p;++b)m+=s.charAt(f[b]);return m}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;l[h]===i;)u++,h++;const g=(l.length-h)*r+1>>>0,p=new Uint8Array(g);for(;h<l.length;){const w=l.charCodeAt(h);if(w>255)return;let E=e[w];if(E===255)return;let A=0;for(let _=g-1;(E!==0||A<d)&&_!==-1;_--,A++)E+=t*p[_]>>>0,p[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=A,h++}let f=g-d;for(;f!==g&&p[f]===0;)f++;const b=new Uint8Array(u+(g-f));let m=u;for(;f!==g;)b[m++]=p[f++];return b}function c(l){const h=a(l);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var h0="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const bl=l0(h0),u0="Coin98";class d0 extends pa{constructor(e={}){super(),this.name=u0,this.url="https://coin98.com",this.icon="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA3NiA3NSI+CiAgPGRlZnM+CiAgICA8bGluZWFyR3JhZGllbnQgaWQ9ImEiIHgxPSIxMDEuNjgxJSIgeDI9Ii0xLjU1NyUiIHkxPSIxNS4yNjglIiB5Mj0iODQuOTE3JSI+CiAgICAgIDxzdG9wIG9mZnNldD0iMCUiIHN0b3AtY29sb3I9IiNGMUQ5NjEiLz4KICAgICAgPHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjQ0RBMTQ2Ii8+CiAgICA8L2xpbmVhckdyYWRpZW50PgogIDwvZGVmcz4KICA8ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgPHJlY3Qgd2lkdGg9Ijc1IiBoZWlnaHQ9Ijc1IiBmaWxsPSIjMDAwIiByeD0iMTYiLz4KICAgIDxwYXRoIGZpbGw9InVybCgjYSkiIGZpbGwtcnVsZT0ibm9uemVybyIgZD0iTTYxLjQ0IDBhMTMuNzE0IDEzLjcxNCAwIDAgMSA5LjY4IDQuMDEgMTMuNjYxIDEzLjY2MSAwIDAgMSA0LjAwOCA5LjY2OHY0Ny42NDZhMTMuNjYgMTMuNjYgMCAwIDEtNC4wMDcgOS42NjZBMTMuNzEzIDEzLjcxMyAwIDAgMSA2MS40NCA3NUgxMy42ODZhMTMuNzEzIDEzLjcxMyAwIDAgMS05LjY4LTQuMDFBMTMuNjYgMTMuNjYgMCAwIDEgMCA2MS4zMjRWMTMuNjc4YzAtMy42MjUgMS40NC03LjEwMiA0LjAwNy05LjY2N0ExMy43MTQgMTMuNzE0IDAgMCAxIDEzLjY4NyAwWk0yMC4wNjMgNDYuMjMxaC00LjgyNWExMC4wMzIgMTAuMDMyIDAgMCAwIDIuOTQ2IDcuMDg2IDEwLjA3IDEwLjA3IDAgMCAwIDcuMSAyLjk0MiAxMC4wNjUgMTAuMDY1IDAgMCAwIDcuMTA4LTIuOTM1IDEwLjAzIDEwLjAzIDAgMCAwIDIuOTQ2LTcuMDkzaC00LjgyNGE1LjIwNyA1LjIwNyAwIDAgMS0xLjUzIDMuNjg4IDUuMjI1IDUuMjI1IDAgMCAxLTMuNjk2IDEuNTI4IDUuMjM0IDUuMjM0IDAgMCAxLTMuNjk1LTEuNTI4IDUuMjEzIDUuMjEzIDAgMCAxLTEuNTMtMy42ODhaTTU0LjMzIDMzLjcxNmExMS43NjMgMTEuNzYzIDAgMCAwLTEyLjc5OSAyLjUzOEExMS42OTcgMTEuNjk3IDAgMCAwIDM4Ljk5IDQ5LjAzYTExLjcyMyAxMS43MjMgMCAwIDAgNC4zMjggNS4yNTkgMTEuNzU3IDExLjc1NyAwIDAgMCA2LjUyNiAxLjk3IDExLjc2NiAxMS43NjYgMCAwIDAgOC4yOS0zLjQzNSAxMS43MiAxMS43MiAwIDAgMCAzLjQ0Mi04LjI3NCAxMS43MDIgMTEuNzAyIDAgMCAwLTEuOTc1LTYuNTE0IDExLjczNiAxMS43MzYgMCAwIDAtNS4yNjktNC4zMlptLTQuNDg4IDMuOTJhNi45MzcgNi45MzcgMCAwIDEgNC45IDIuMDI1IDYuOTEgNi45MSAwIDAgMSAyLjAyOCA0Ljg5MiA2Ljg5NyA2Ljg5NyAwIDAgMS0xLjE3IDMuODM0IDYuOTMyIDYuOTMyIDAgMCAxLTEwLjY0MyAxLjA0MiA2LjkwMiA2LjkwMiAwIDAgMS0xLjUtNy41MjIgNi45MDkgNi45MDkgMCAwIDEgMi41NDQtMy4xIDYuOTI4IDYuOTI4IDAgMCAxIDMuODQxLTEuMTY3Wm0uMTcgNC41NTJhMi40MzEgMi40MzEgMCAwIDAtMi4yNDEgMS4xNTQgMi40MTggMi40MTggMCAwIDAtLjM1NiAxLjI1NyAyLjM5NSAyLjM5NSAwIDAgMCAxLjYxOSAyLjI5djEuNzUzaDEuNjE4di0xLjc1NGEyLjQyNyAyLjQyNyAwIDAgMCAxLjU5NC0xLjk1IDIuNDE4IDIuNDE4IDAgMCAwLTEtMi4zMSAyLjQzMSAyLjQzMSAwIDAgMC0xLjIzNC0uNDRabS0yMC4yMi0yMi41NTJhMTEuNzYyIDExLjc2MiAwIDAgMC0xMi43OTYgMi41MzEgMTEuNjk3IDExLjY5NyAwIDAgMC0yLjU1NCAxMi43NjkgMTEuNzIzIDExLjcyMyAwIDAgMCA0LjMyIDUuMjYyIDExLjc1NyAxMS43NTcgMCAwIDAgMTQuODI1LTEuNDQ2IDExLjcxNyAxMS43MTcgMCAwIDAgMy40NDUtOC4yODQgMTEuNzAzIDExLjcwMyAwIDAgMC0xLjk3NC02LjUxMiAxMS43MzYgMTEuNzM2IDAgMCAwLTUuMjY2LTQuMzJabS00LjUxIDMuOTE3YTYuOTQ1IDYuOTQ1IDAgMCAxIDQuODk3IDIuMDI5IDYuOTE4IDYuOTE4IDAgMCAxIDIuMDMyIDQuODg2IDYuOTA2IDYuOTA2IDAgMCAxLTEuMTY4IDMuODQyIDYuOTQgNi45NCAwIDAgMS0xMC42NiAxLjA0OCA2LjkxMSA2LjkxMSAwIDAgMS0xLjUtNy41MzYgNi45MTggNi45MTggMCAwIDEgMi41NS0zLjEwMyA2LjkzNyA2LjkzNyAwIDAgMSAzLjg1LTEuMTY2Wm0yNC41Ni00LjgxYTEwLjA1OSAxMC4wNTkgMCAwIDAtNy4xMDMgMi45NCAxMC4wMiAxMC4wMiAwIDAgMC0yLjk0IDcuMDkgOS45IDkuOSAwIDAgMCAxLjIzIDQuNzk1IDEzLjU3NSAxMy41NzUgMCAwIDEgNC4yMTQtMi4zMjIgNS4wODIgNS4wODIgMCAwIDEtLjYyNS0yLjQ3NyA1LjIwNiA1LjIwNiAwIDAgMSAxLjUwMy0zLjczNiA1LjIyMyA1LjIyMyAwIDAgMSAzLjcyMi0xLjU1NCA1LjIzNCA1LjIzNCAwIDAgMSAzLjcyIDEuNTU0IDUuMjEzIDUuMjEzIDAgMCAxIDEuNTA1IDMuNzM2IDUuMjc5IDUuMjc5IDAgMCAxLS42MjMgMi40NzMgMTMuNTc0IDEzLjU3NCAwIDAgMSA0LjIxMyAyLjMyMiA5LjkwMyA5LjkwMyAwIDAgMCAxLjIzLTQuNzk1IDEwLjAzMiAxMC4wMzIgMCAwIDAtMi45NDYtNy4wODYgMTAuMDcgMTAuMDcgMCAwIDAtNy4xLTIuOTRabS0yMy43NSA3Ljk5aC0xLjYxN3YxLjc1YTIuNDE5IDIuNDE5IDAgMCAwLTEuNTgyIDIuNjg3IDIuNDE0IDIuNDE0IDAgMCAwIDIuMzkgMi4wMDYgMi40NSAyLjQ1IDAgMCAwIDEuNTU1LS41NzQgMi40MTQgMi40MTQgMCAwIDAtLjc0Ni00LjExOXYtMS43NVoiLz4KICA8L2c+Cjwvc3ZnPgo=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?de.Unsupported:de.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==de.Unsupported&&da(()=>{var t;return(t=window.coin98)!=null&&t.sol?(this._readyState=de.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){var e;return!!((e=this._wallet)!=null&&e.isConnected())}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==de.Installed)throw new or;this._connecting=!0;const e=window.coin98.sol;let t;try{t=(await e.connect())[0]}catch(r){throw new ks(r==null?void 0:r.message,r)}let i;try{i=new di(t)}catch(r){throw new Ur(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch(t){this.emit("error",new ha(t==null?void 0:t.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{const i=await t.request({method:"sol_sign",params:[e]}),r=new di(i.publicKey),n=bl.decode(i.signature);return e.addSignature(r,T.Buffer.from(n)),e}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{const i=await t.request({method:"sol_signAllTransactions",params:[e]}),r=new di(i.publicKey),n=i.signatures;return e.map((o,a)=>{const c=bl.decode(n[a]);return o.addSignature(r,T.Buffer.from(c)),o})}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{const i=await t.request({method:"sol_signMessage",params:[e]});return bl.decode(i.signature)}catch(i){throw new ua(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const p0="Nightly";class bd extends pa{constructor(){super(),this.name=p0,this.url="https://nightly.app",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iOTYiIGhlaWdodD0iOTYiIHZpZXdCb3g9IjAgMCA5NiA5NiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQ4IDk2Qzc0LjUwOTcgOTYgOTYgNzQuNTA5NyA5NiA0OEM5NiAyMS40OTAzIDc0LjUwOTcgMCA0OCAwQzIxLjQ5MDMgMCAwIDIxLjQ5MDMgMCA0OEMwIDc0LjUwOTcgMjEuNDkwMyA5NiA0OCA5NloiIGZpbGw9IiM2RDczRjgiLz4KPHBhdGggZD0iTTQ4IDg1LjYzNTZDNDggODUuNjM1NiA1Mi40NTMzIDg1LjYzNTYgNTUuNDQgODIuNTg2N0M1OC45MTU1IDc5LjI4MDEgNTcuMzUxMSA3NS40MzEyIDYyLjI3NTUgNzEuNDMxMkM2Ni45ODY2IDY3LjY0NDUgNzIuOTI0NCA3MC4zMzc5IDcyLjkyNDQgNzAuMzM3OUM3Ny4wMjIyIDYyLjEyNDUgNzQuNzkxMSA1Mi41NjkgNzQuNzkxMSA1Mi41NjlDODEuNzY4OCAzNC4yNTc5IDc1Ljk2NDQgMjEuMTU1NyA3NC40NDQ0IDE3LjM2MDFDNjkuNDQ4OCAyNC4zMzc5IDYzLjE5MTEgMjkuMTczNCA1NS43OTU1IDMyLjQwOUM1My4yMjY2IDMxLjcwNjggNTAuNTk1NSAzMS4zMzM0IDQ4IDMxLjM2MDFDNDUuNDEzMyAzMS4zMzM0IDQyLjc3MzMgMzEuNzA2OCA0MC4yMDQ0IDMyLjQwOUMzMi44MTc3IDI5LjE2NDUgMjYuNTUxMSAyNC4zMzc5IDIxLjU1NTUgMTcuMzYwMUMyMC4wMzU1IDIxLjE1NTcgMTQuMjMxMSAzNC4yNTc5IDIxLjIwODkgNTIuNTY5QzIxLjIwODkgNTIuNTY5IDE4Ljk3NzggNjIuMTI0NSAyMy4wNzU1IDcwLjMzNzlDMjMuMDc1NSA3MC4zMzc5IDI5LjAxMzMgNjcuNjQ0NSAzMy43MjQ0IDcxLjQzMTJDMzguNjU3NyA3NS40MzEyIDM3LjA4NDQgNzkuMjgwMSA0MC41NiA4Mi41ODY3QzQzLjU0NjYgODUuNjM1NiA0OCA4NS42MzU2IDQ4IDg1LjYzNTZaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNNDIuNDc5OSA2NS4yOThDNDIuMjkzMyA1OS4yMTggMzYuMzAyMSA1Ny4yNjI0IDMyLjIxMzMgNTkuODIyNEMzMi4yMTMzIDU5LjgyMjQgMzIuODUzMyA2Mi40MzU4IDM1LjgzOTkgNjMuNzUxM0MzOC4yNzU1IDY0LjgyNjkgMzkuMzI0NCA2My4zODY5IDQyLjQ3OTkgNjUuMjk4WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNMjIuNDk3NyAyMy4wOTM1QzIwLjA4ODggMzEuNTQ2OCAyMS4xMjg4IDQyLjI0MDIgMjQuOTMzMyA1MC4wMjY5QzI4LjgyNjYgNDcuMjcxMyAzMi45MTU1IDQzLjAxMzUgMzUuMDkzMyAzOC41MDY5QzI5Ljk2NDQgMzQuNzExMyAyNS42NjIyIDMxLjEwMjQgMjIuNDk3NyAyMy4wOTM1WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNTMuNTE5OSA2NS4yOThDNTMuNzA2NiA1OS4yMTggNTkuNjk3NyA1Ny4yNjI0IDYzLjc4NjYgNTkuODIyNEM2My43ODY2IDU5LjgyMjQgNjMuMTQ2NiA2Mi40MzU4IDYwLjE1OTkgNjMuNzUxM0M1Ny43MjQzIDY0LjgyNjkgNTYuNjc1NSA2My4zODY5IDUzLjUxOTkgNjUuMjk4WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNzMuNTAyMiAyMy4wOTM1Qzc1LjkxMTEgMzEuNTQ2OCA3NC44NzExIDQyLjI0MDIgNzEuMDY2NiA1MC4wMjY5QzY3LjE3MzMgNDcuMjcxMyA2My4wODQ0IDQzLjAxMzUgNjAuOTA2NiAzOC41MDY5QzY2LjAzNTUgMzQuNzExMyA3MC4zMzc3IDMxLjEwMjQgNzMuNTAyMiAyMy4wOTM1WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNDcuOTk5OSA4NS4zMDY5QzUwLjE0MDQgODUuMzA2OSA1MS44NzU1IDgzLjc3ODcgNTEuODc1NSA4MS44OTM2QzUxLjg3NTUgODAuMDA4NCA1MC4xNDA0IDc4LjQ4MDIgNDcuOTk5OSA3OC40ODAyQzQ1Ljg1OTUgNzguNDgwMiA0NC4xMjQ0IDgwLjAwODQgNDQuMTI0NCA4MS44OTM2QzQ0LjEyNDQgODMuNzc4NyA0NS44NTk1IDg1LjMwNjkgNDcuOTk5OSA4NS4zMDY5WiIgZmlsbD0iIzdCODFGOSIvPgo8L3N2Zz4K",this.supportedTransactionVersions=new Set(["legacy",0]),this._readyState=typeof window>"u"||typeof document>"u"?de.Unsupported:de.NotDetected,this._connecting=!1,this._publicKey=null,this._wallet=null,this._readyState!==de.Unsupported&&da(()=>{var e;return(e=window==null?void 0:window.nightly)!=null&&e.solana?(this._readyState=de.Installed,this.emit("readyStateChange",this._readyState),!0):!1})}get connecting(){return this._connecting}get readyState(){return this._readyState}get publicKey(){return this._publicKey}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==de.Installed)throw new or;this._connecting=!0;const e=window.nightly.solana;try{await e.connect()}catch(i){throw new Hc(i==null?void 0:i.message,i)}if(e.publicKey.toString()==="11111111111111111111111111111111")throw new ks;let t;try{t=new di(e.publicKey.toBytes())}catch(i){throw new Ur(i==null?void 0:i.message,i)}this._wallet=e,this._publicKey=t,this.emit("connect",t)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch{this.emit("error",new mw)}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{return t.signMessage(new TextDecoder().decode(e))}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const vd="solana:mainnet",g0="solana:devnet",f0="solana:testnet",w0="solana:localnet",y0="Solong";class m0 extends mu{constructor(e={}){super(),this.name=y0,this.url="https://solongwallet.io",this.icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAGlklEQVR4Ae3bA5DsyhfH8TNr49r2/du2bdu2bdu2zcdNrm3b9toz533rvctUn3Umk9p01WfdvVW/6nROBxJVS1rSkpa0pCUtaUlLWtKSpl4VXos3GJ4sujQFuUKfWl+qT730arzB8Ex9YksKcgXjFOCVeIPhBYydB8mawQ+yiGC8n0EN6zAVcgXhpQjoq1DDdsyDAAB9Pwo1HMC9INk0FIM8Bt1Qh9WohQQCvD+BtEMdtmC8I7y5aIE67MV0SBwDvB3qsE/UHwMJIpC/QB1OYiLEEeCPoQ7nMRcSwwDrao3Zl8aTIEGEUYlL0IAMXuQOr66UvsegDm+ExDJAPNiafSg0AlyIbmjAWX1aQzEkiH6T0QkNaEdpnAN8NNRhPcSF9e9el2ebBhyAuNBvGtLQgIuQOAd4D6jDMRQbM3AmOqEBDfq0xjJIEP3GohkakEFVjAP0y401sAsLnAE+pb6EsC5AA9J4sHsG+kX0PQR1eFJ8AwTWQh0+DjFm4a1Qh2/AOoz/BHX4ZdwD/CDU4aioX2GUMW+AOnB2bqiBBDHe86EOTYw5GRKJwQ/ijUM91OGTxgysxSmowzeNw7j08m5DHX4l7Igg2TY0g9hbLBZ+f7oxC98CdWjDvYzD+MVQh07GfEQsZyDgVWA71OGvorfnQQCAcqaYUFZDHW6j/itAoB70GcergzqsEa0rhGTTEA7mP0koK4xdyeOMmvBBhJU2zsjPMw7lu9O3zShpXheHk4hhcZ4w26AOG4RSxDiUfwZ12KdPqy+FBDHeV6EOZxizIg6HsMGbiQ5jdjzBXRfeefGg3tgbv9BYC0fhZE7sjUMY9Pf9rdcI5XtQh39BjBA/C3VYnM0zcgiDek+GOhzh93mQoMs7kIxze/eMhnxIEOPNM9bcFtTEeAb6I419axu/m2CsgxU4Aw1A/UxIUM/bO/9+cVkDDd5x42x8N1iH8Taow0NhHcZLoQ5Pi/MMzDMW+DTu7g6vIY9AdkAdHmaUMyn6roA6PD22AeLB6DbWplHG7LubfY+kfiIkiH5T0AJ1uFtMA1xUzOc1UIclzvCeXF+o7DygDlvds29RgVVzYj+K4xhgEX4NdcjgecE++rSL+ZdLmIxRB77Ose7l4XPIQB3eF8M60C/n8++ghltE/QLIFfqUiyUE8kOoYSW7jmLIFXeN4X0NaajDDlG/NG6XswrxKdxu+G/weh27j3wCej9uN9zEOjc3sObl4S243XBLhDfWE0mAMQjwZfhxDng7pG/8Sj4/ER/Gd/BdfBhPRGW2A/wxNAfcBOnFCHwZZ6GGs/gqapMAb/QEnIT20Uk8IQkQeB7aof3UihcM9wDvhyboANHXv1+IdWBOB2hsIftto+iSPEif8aGPcjrA50GHyPMiOIT9B/N5apaMgQT8D2poxMdwt8s+hkao4X9ZDxBTIdHwy/h8AeqQxhMhAU9BB9ThPMqHTYCYjU6owy3uPstSfL4Z6uZPC+Mk8gOomz8DEg3vXshAHb4MMXwZarhXGDPwa739w2j48623BPAniOFPUMPsMAL8INTw9AgDrLZOCmjFPEjA3WD1aUJVGAG+CGr4ECRCy6GGg3iyaF0+n/PwFByEGpaJ+qkw1sB7QA3/hUTozdBetFymvXhTWGVMOc7bp36/FhKRamNW9dcxZmpZiI+32ad+vAQSoWejGzpAXXh22Fek3wY1rDD2kVnijR3ExYQMPgkJOUB/nFW0Is3vnw6JhlHX9a4N70Iq/ACBv0MNu7J9WxHw7jaA2deFOtw32zeVHtHLWvMN0dtSkOzwS3spYy7iH1hx2d/wYdyTvnkR3BdeQjjerVBDN14JyZIfQWH5RC7e1rw32npZV54LCc+SPD5/HgqYD3WW5+gTqt6X+rA4v0701hRkKF0+bL+HTM9Hgv/MHH60wyvHWigsafwA1ZAhMguLoL34kbDcQEI1uAH8mcbuxPHImf8i5EMGxqvER9EI7cUqVMTl0Y6HoxHaBzvxNkyC9EEe7oEv4Sy0D/YQ+IS4ver1JNT38z7sWnwbb8TT8Cg8Gs/Gu/Ar7EEXtI/2ud7Ni0GAYCbiJDQiazA57k9nTcdqaJb9UtSvitXbmjavCJ9AMzRkJ/B80boUJBLhDe7Nw1/QCR1i9fgKRg6HByzvjZ/hInQQMjiCT2PSMHxC1a/l8wvwGxyG9kEaW/EtPI4xiiE5JcLrd6PxcLwM78SH8EG8Fc/H/UUXVUByGh8SSYBJgEmASYCJJMAkwBi6A3xCqZhiBz8+AAAAAElFTkSuQmCC",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?de.Unsupported:de.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==de.Unsupported&&da(()=>window.solong?(this._readyState=de.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){var e;return!!((e=this._wallet)!=null&&e.currentAccount)}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==de.Installed)throw new or;this._connecting=!0;const e=window.solong;let t;try{t=await e.selectAccount()}catch(r){throw new ks(r==null?void 0:r.message,r)}let i;try{i=new di(t)}catch(r){throw new Ur(r==null?void 0:r.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){this._wallet&&(this._wallet=null,this._publicKey=null),this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)||e}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const b0="Torus";class v0 extends pa{constructor({params:e={showTorusButton:!1}}={params:{showTorusButton:!1}}){super(),this.name=b0,this.url="https://tor.us",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzMiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMyAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYuNSIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzAzNjRGRiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTExLjIxODYgOS40OTIxOUMxMC40NTM5IDkuNDkyMTkgOS44MzM5OCAxMC4xMTIxIDkuODMzOTggMTAuODc2OFYxMi40ODk4QzkuODMzOTggMTMuMjU0NSAxMC40NTM5IDEzLjg3NDQgMTEuMjE4NiAxMy44NzQ0SDEzLjY2ODRWMjIuODk3NkMxMy42Njg0IDIzLjY2MjMgMTQuMjg4MyAyNC4yODIyIDE1LjA1MyAyNC4yODIySDE2LjY2NkMxNy40MzA3IDI0LjI4MjIgMTguMDUwNiAyMy42NjIzIDE4LjA1MDYgMjIuODk3NlYxMi41MDE1QzE4LjA1MDYgMTIuNDk3NiAxOC4wNTA2IDEyLjQ5MzcgMTguMDUwNiAxMi40ODk4VjEwLjg3NjhDMTguMDUwNiAxMC4xMTIxIDE3LjQzMDcgOS40OTIxOSAxNi42NjYgOS40OTIxOUgxNS4wNTNIMTEuMjE4NloiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0yMS4zMzc2IDEzLjg3NDRDMjIuNTQ3NyAxMy44NzQ0IDIzLjUyODcgMTIuODkzNCAyMy41Mjg3IDExLjY4MzNDMjMuNTI4NyAxMC40NzMyIDIyLjU0NzcgOS40OTIxOSAyMS4zMzc2IDkuNDkyMTlDMjAuMTI3NSA5LjQ5MjE5IDE5LjE0NjUgMTAuNDczMiAxOS4xNDY1IDExLjY4MzNDMTkuMTQ2NSAxMi44OTM0IDIwLjEyNzUgMTMuODc0NCAyMS4zMzc2IDEzLjg3NDRaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?de.Unsupported:de.Loadable,this._connecting=!1,this._wallet=null,this._publicKey=null,this._params=e}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){var e;return!!((e=this._wallet)!=null&&e.isLoggedIn)}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==de.Loadable)throw new or;this._connecting=!0;let e;try{e=(await Zo(async()=>{const{default:n}=await import("./solanaEmbed.esm-BKA1kzuW.js");return{default:n}},__vite__mapDeps([0,1,2,3]))).default}catch(n){throw new s0(n==null?void 0:n.message,n)}let t;try{t=window.torus||new e}catch(n){throw new xn(n==null?void 0:n.message,n)}if(!t.isInitialized)try{await t.init(this._params)}catch(n){throw new Hc(n==null?void 0:n.message,n)}let i;try{i=await t.login()}catch(n){throw new ks(n==null?void 0:n.message,n)}let r;try{r=new di(i[0])}catch(n){throw new Ur(n==null?void 0:n.message,n)}this._wallet=t,this._publicKey=r,this.emit("connect",r)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{e.isLoggedIn&&await e.cleanUp()}catch(t){this.emit("error",new ha(t==null?void 0:t.message,t))}}this.emit("disconnect")}async sendTransaction(e,t,i={}){try{const r=this._wallet;if(!r)throw new Ge;try{const{signers:n,...o}=i;e=await this.prepareTransaction(e,t,o),n!=null&&n.length&&e.partialSign(...n),o.preflightCommitment=o.preflightCommitment||t.commitment;const{signature:a}=await r.signAndSendTransaction(e,o);return a}catch(n){throw n instanceof Ft?n:new _r(n==null?void 0:n.message,n)}}catch(r){throw this.emit("error",r),r}}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)||e}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)||e}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signMessage(e)}catch(i){throw new ua(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}function vl(s){switch(s){case"processed":case"confirmed":case"finalized":case void 0:return s;case"recent":return"processed";case"single":case"singleGossip":return"confirmed";case"max":case"root":return"finalized";default:return}}const I0="https://api.mainnet-beta.solana.com";function E0(s){return s.includes(I0)?vd:/\bdevnet\b/i.test(s)?g0:/\btestnet\b/i.test(s)?f0:/\blocalhost\b/i.test(s)||/\b127\.0\.0\.1\b/.test(s)?w0:vd}var Nc;(function(s){s.Mainnet="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",s.Devnet="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",s.Deprecated_Mainnet="solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",s.Deprecated_Devnet="solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"})(Nc||(Nc={}));var xs;(function(s){s.signTransaction="solana_signTransaction",s.signMessage="solana_signMessage",s.signAndSendTransaction="solana_signAndSendTransaction",s.signAndSendAllTransactions="solana_signAndSendAllTransactions",s.signAllTransactions="solana_signAllTransactions"})(xs||(xs={}));const vt={Mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Deprecated_Mainnet:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",Deprecated_Devnet:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"};var A0=Object.defineProperty,N0=(s,e,t)=>e in s?A0(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Id=(s,e,t)=>N0(s,typeof e!="symbol"?e+"":e,t);let _0=class extends js{constructor(e){super(),this.opts=e,Id(this,"protocol","wc"),Id(this,"version",2)}};var C0=Object.defineProperty,S0=(s,e,t)=>e in s?C0(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,T0=(s,e,t)=>S0(s,e+"",t);let P0=class extends js{constructor(e,t){super(),this.core=e,this.logger=t,T0(this,"records",new Map)}},$0=class{constructor(e,t){this.logger=e,this.core=t}},M0=class extends js{constructor(e,t){super(),this.relayer=e,this.logger=t}},O0=class extends js{constructor(e){super()}},x0=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},D0=class extends js{constructor(e,t){super(),this.relayer=e,this.logger=t}},k0=class extends js{constructor(e,t){super(),this.core=e,this.logger=t}},j0=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},R0=class{constructor(e,t){this.projectId=e,this.logger=t}},U0=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};function ea(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function Ed(s){return ea(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const Ew="2.23.2";let fo={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${Ew}`},Wc=class gh extends Error{constructor(e,t={}){var a;const i=(()=>{var c;return t.cause instanceof gh?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),r=t.cause instanceof gh&&t.cause.docsPath||t.docsPath,n=(a=fo.getDocsUrl)==null?void 0:a.call(fo,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...fo.version?[`Version: ${fo.version}`]:[]].join(`
|
|
3
|
-
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Ew}walk(e){return Aw(this,e)}};function Aw(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?Aw(s.cause,e):e?null:s}let Nw=class extends Wc{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}};function eo(s,{dir:e,size:t=32}={}){return typeof s=="string"?L0(s,{dir:e,size:t}):z0(s,{dir:e,size:t})}function L0(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new Nw({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function z0(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new Nw({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}let F0=class extends Wc{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}},q0=class extends Wc{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function to(s,{size:e}){if(Ed(s)>e)throw new q0({givenSize:Ed(s),maxSize:e})}function fh(s,e={}){const{signed:t}=e;e.size&&to(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function B0(s,e={}){return Number(fh(s,e))}const H0=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function wh(s,e={}){return typeof s=="number"||typeof s=="bigint"?Cw(s,e):typeof s=="string"?K0(s,e):typeof s=="boolean"?W0(s,e):_w(s,e)}function W0(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(to(t,{size:e.size}),eo(t,{size:e.size})):t}function _w(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=H0[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(to(i,{size:e.size}),eo(i,{dir:"right",size:e.size})):i}function Cw(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof s=="bigint"?"n":"";throw new F0({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${s}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?eo(a,{size:i}):a}const V0=new TextEncoder;function K0(s,e={}){const t=V0.encode(s);return _w(t,e)}const G0=new TextEncoder;function Y0(s,e={}){return typeof s=="number"||typeof s=="bigint"?Z0(s,e):typeof s=="boolean"?Q0(s,e):ea(s)?Sw(s,e):Tw(s,e)}function Q0(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(to(t,{size:e.size}),eo(t,{size:e.size})):t}const bi={zero:48,nine:57,A:65,F:70,a:97,f:102};function Ad(s){if(s>=bi.zero&&s<=bi.nine)return s-bi.zero;if(s>=bi.A&&s<=bi.F)return s-(bi.A-10);if(s>=bi.a&&s<=bi.f)return s-(bi.a-10)}function Sw(s,e={}){let t=s;e.size&&(to(t,{size:e.size}),t=eo(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=Ad(i.charCodeAt(a++)),l=Ad(i.charCodeAt(a++));if(c===void 0||l===void 0)throw new Wc(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function Z0(s,e){const t=Cw(s,e);return Sw(t)}function Tw(s,e={}){const t=G0.encode(s);return typeof e.size=="number"?(to(t,{size:e.size}),eo(t,{dir:"right",size:e.size})):t}function _c(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function J0(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Vc(s,...e){if(!J0(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function h6(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");_c(s.outputLen),_c(s.blockLen)}function Nd(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function X0(s,e){Vc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Ua=BigInt(2**32-1),_d=BigInt(32);function eI(s,e=!1){return e?{h:Number(s&Ua),l:Number(s>>_d&Ua)}:{h:Number(s>>_d&Ua)|0,l:Number(s&Ua)|0}}function tI(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=eI(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const sI=(s,e,t)=>s<<t|e>>>32-t,iI=(s,e,t)=>e<<t|s>>>32-t,rI=(s,e,t)=>e<<t-32|s>>>64-t,nI=(s,e,t)=>s<<t-32|e>>>64-t,Vr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function oI(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function u6(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function d6(s,e){return s<<32-e|s>>>e}const Cd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function aI(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Sd(s){for(let e=0;e<s.length;e++)s[e]=aI(s[e])}function cI(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Pw(s){return typeof s=="string"&&(s=cI(s)),Vc(s),s}function p6(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Vc(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}let lI=class{clone(){return this._cloneInto()}};function hI(s){const e=i=>s().update(Pw(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function f6(s=32){if(Vr&&typeof Vr.getRandomValues=="function")return Vr.getRandomValues(new Uint8Array(s));if(Vr&&typeof Vr.randomBytes=="function")return Vr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const $w=[],Mw=[],Ow=[],uI=BigInt(0),wo=BigInt(1),dI=BigInt(2),pI=BigInt(7),gI=BigInt(256),fI=BigInt(113);for(let s=0,e=wo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],$w.push(2*(5*i+t)),Mw.push((s+1)*(s+2)/2%64);let r=uI;for(let n=0;n<7;n++)e=(e<<wo^(e>>pI)*fI)%gI,e&dI&&(r^=wo<<(wo<<BigInt(n))-wo);Ow.push(r)}const[wI,yI]=tI(Ow,!0),Td=(s,e,t)=>t>32?rI(s,e,t):sI(s,e,t),Pd=(s,e,t)=>t>32?nI(s,e,t):iI(s,e,t);function mI(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],h=t[c+1],u=Td(l,h,1)^t[a],d=Pd(l,h,1)^t[a+1];for(let g=0;g<50;g+=10)s[o+g]^=u,s[o+g+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Mw[o],c=Td(r,n,a),l=Pd(r,n,a),h=$w[o];r=s[h],n=s[h+1],s[h]=c,s[h+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=wI[i],s[1]^=yI[i]}t.fill(0)}let bI=class xw extends lI{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,_c(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=oI(this.state)}keccak(){Cd||Sd(this.state32),mI(this.state32,this.rounds),Cd||Sd(this.state32),this.posOut=0,this.pos=0}update(e){Nd(this);const{blockLen:t,state:i}=this;e=Pw(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Nd(this,!1),Vc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return _c(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(X0(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new xw(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const vI=(s,e,t)=>hI(()=>new bI(e,s,t)),II=vI(1,136,256/8);function Dw(s,e){const t=e||"hex",i=II(ea(s,{strict:!1})?Y0(s):s);return t==="bytes"?i:wh(i)}let EI=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}};const Il=new EI(8192);function AI(s,e){if(Il.has(`${s}.${e}`))return Il.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=Dw(Tw(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Il.set(`${s}.${e}`,n),n}function NI(s){const e=Dw(`0x${s.substring(4)}`).substring(26);return AI(`0x${e}`)}async function _I({hash:s,signature:e}){const t=ea(s)?s:wh(s),{secp256k1:i}=await Zo(async()=>{const{secp256k1:o}=await import("./secp256k1-BQBOR8e3.js");return{secp256k1:o}},__vite__mapDeps([4,1,2,5,6,7,8,9,10,11]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:h,v:u,yParity:d}=e,g=Number(d??u),p=$d(g);return new i.Signature(fh(l),fh(h)).addRecoveryBit(p)}const o=ea(e)?e:wh(e),a=B0(`0x${o.slice(130)}`),c=$d(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function $d(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function CI({hash:s,signature:e}){return NI(await _I({hash:s,signature:e}))}var kw=Hv(),SI={};const jw=":";function zn(s){const[e,t]=s.split(jw);return{namespace:e,reference:t}}function TI(s){const[e,t,i]=s.split(jw);return{namespace:e,reference:t,address:i}}function Rw(s,e){return s.includes(":")?[s]:e.chains||[]}const PI="ReactNative",vs={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},$I="js";function Cc(){return typeof T.process<"u"&&typeof T.process.versions<"u"&&typeof T.process.versions.node<"u"}function ar(){return!rr()&&!!qc()&&navigator.product===PI}function MI(){return ar()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"&&(T.global==null?void 0:T.global.Platform.OS)==="android"}function OI(){return ar()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"&&(T.global==null?void 0:T.global.Platform.OS)==="ios"}function ga(){return!Cc()&&!!qc()&&!!rr()}function fa(){return ar()?vs.reactNative:Cc()?vs.node:ga()?vs.browser:vs.unknown}function Md(){var s;try{return ar()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Application)<"u"?(s=T.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function xI(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function Uw(){return cw()||{name:"",description:"",url:"",icons:[""]}}function DI(){if(fa()===vs.reactNative&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"){const{OS:t,Version:i}=T.global.Platform;return[t,i].join("-")}const s=hw();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function kI(){var s;const e=fa();return e===vs.browser?[e,((s=uw())==null?void 0:s.host)||"unknown"].join(":"):e}function Lw(s,e,t){const i=DI(),r=kI();return[[s,e].join("-"),[$I,t].join("-"),i,r].join("/")}function jI({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=t.split("?"),h=Lw(s,e,i),u={auth:r,ua:h,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=xI(l[1]||"",u);return l[0]+"?"+d}function Cr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function zw(s){return Object.fromEntries(s.entries())}function Fw(s){return new Map(Object.entries(s))}function mr(s=N.FIVE_MINUTES,e){const t=N.toMiliseconds(s||N.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},t),i=a,r=c})}}function Yi(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function qw(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${s}`)}function RI(s){return qw("topic",s)}function UI(s){return qw("id",s)}function Bw(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function mt(s,e){return N.fromMiliseconds(Date.now()+N.toMiliseconds(s))}function Wi(s){return Date.now()>=N.toMiliseconds(s)}function Te(s,e){return`${s}${e?`:${e}`:""}`}function cc(s=[],e=[]){return[...new Set([...s,...e])]}async function LI({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=zI(n,s,e),a=fa();if(a===vs.browser){if(!((i=rr())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}FI(o)}else a===vs.reactNative&&typeof(T.global==null?void 0:T.global.Linking)<"u"&&await T.global.Linking.openURL(o)}catch(r){console.error(r)}}function zI(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${WI(i,!0)}`}else r=`${r}/wc?${i}`;return r}function FI(s){let e="_self";HI()?e="_top":(BI()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function qI(s,e){let t="";try{if(ga()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Od(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function xd(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function bu(){return typeof T.process<"u"&&SI.IS_VITEST==="true"}function BI(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function HI(){try{return window.self!==window.top}catch{return!1}}function WI(s,e=!1){const t=T.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Hw(s){return T.Buffer.from(s,"base64").toString("utf-8")}function VI(s){return new Promise(e=>setTimeout(e,s))}function ta(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function KI(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Kc(s,...e){if(!KI(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function vu(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ta(s.outputLen),ta(s.blockLen)}function Hn(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ww(s,e){Kc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const La=BigInt(2**32-1),Dd=BigInt(32);function GI(s,e=!1){return e?{h:Number(s&La),l:Number(s>>Dd&La)}:{h:Number(s>>Dd&La)|0,l:Number(s&La)|0}}function YI(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=GI(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const QI=(s,e,t)=>s<<t|e>>>32-t,ZI=(s,e,t)=>e<<t|s>>>32-t,JI=(s,e,t)=>e<<t-32|s>>>64-t,XI=(s,e,t)=>s<<t-32|e>>>64-t,Kr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function e1(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function El(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function ti(s,e){return s<<32-e|s>>>e}const kd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function t1(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function jd(s){for(let e=0;e<s.length;e++)s[e]=t1(s[e])}function s1(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Wn(s){return typeof s=="string"&&(s=s1(s)),Kc(s),s}let Iu=class{clone(){return this._cloneInto()}};function Vw(s){const e=i=>s().update(Wn(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function wa(s=32){if(Kr&&typeof Kr.getRandomValues=="function")return Kr.getRandomValues(new Uint8Array(s));if(Kr&&typeof Kr.randomBytes=="function")return Kr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Kw=[],Gw=[],Yw=[],i1=BigInt(0),yo=BigInt(1),r1=BigInt(2),n1=BigInt(7),o1=BigInt(256),a1=BigInt(113);for(let s=0,e=yo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Kw.push(2*(5*i+t)),Gw.push((s+1)*(s+2)/2%64);let r=i1;for(let n=0;n<7;n++)e=(e<<yo^(e>>n1)*a1)%o1,e&r1&&(r^=yo<<(yo<<BigInt(n))-yo);Yw.push(r)}const[c1,l1]=YI(Yw,!0),Rd=(s,e,t)=>t>32?JI(s,e,t):QI(s,e,t),Ud=(s,e,t)=>t>32?XI(s,e,t):ZI(s,e,t);function h1(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],h=t[c+1],u=Rd(l,h,1)^t[a],d=Ud(l,h,1)^t[a+1];for(let g=0;g<50;g+=10)s[o+g]^=u,s[o+g+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Gw[o],c=Rd(r,n,a),l=Ud(r,n,a),h=Kw[o];r=s[h],n=s[h+1],s[h]=c,s[h+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=c1[i],s[1]^=l1[i]}t.fill(0)}let u1=class Qw extends Iu{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ta(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=e1(this.state)}keccak(){kd||jd(this.state32),h1(this.state32,this.rounds),kd||jd(this.state32),this.posOut=0,this.pos=0}update(e){Hn(this);const{blockLen:t,state:i}=this;e=Wn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Hn(this,!1),Kc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ta(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ww(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Qw(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const d1=(s,e,t)=>Vw(()=>new u1(e,s,t)),p1=d1(1,136,256/8),g1="https://rpc.walletconnect.org/v1";function Zw(s){const e=`Ethereum Signed Message:
|
|
3
|
+
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Ew}walk(e){return Aw(this,e)}};function Aw(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?Aw(s.cause,e):e?null:s}let Nw=class extends Wc{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}};function eo(s,{dir:e,size:t=32}={}){return typeof s=="string"?L0(s,{dir:e,size:t}):z0(s,{dir:e,size:t})}function L0(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new Nw({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function z0(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new Nw({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}let F0=class extends Wc{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}},q0=class extends Wc{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function to(s,{size:e}){if(Ed(s)>e)throw new q0({givenSize:Ed(s),maxSize:e})}function fh(s,e={}){const{signed:t}=e;e.size&&to(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function B0(s,e={}){return Number(fh(s,e))}const H0=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function wh(s,e={}){return typeof s=="number"||typeof s=="bigint"?Cw(s,e):typeof s=="string"?K0(s,e):typeof s=="boolean"?W0(s,e):_w(s,e)}function W0(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(to(t,{size:e.size}),eo(t,{size:e.size})):t}function _w(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=H0[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(to(i,{size:e.size}),eo(i,{dir:"right",size:e.size})):i}function Cw(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof s=="bigint"?"n":"";throw new F0({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${s}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?eo(a,{size:i}):a}const V0=new TextEncoder;function K0(s,e={}){const t=V0.encode(s);return _w(t,e)}const G0=new TextEncoder;function Y0(s,e={}){return typeof s=="number"||typeof s=="bigint"?Z0(s,e):typeof s=="boolean"?Q0(s,e):ea(s)?Sw(s,e):Tw(s,e)}function Q0(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(to(t,{size:e.size}),eo(t,{size:e.size})):t}const bi={zero:48,nine:57,A:65,F:70,a:97,f:102};function Ad(s){if(s>=bi.zero&&s<=bi.nine)return s-bi.zero;if(s>=bi.A&&s<=bi.F)return s-(bi.A-10);if(s>=bi.a&&s<=bi.f)return s-(bi.a-10)}function Sw(s,e={}){let t=s;e.size&&(to(t,{size:e.size}),t=eo(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=Ad(i.charCodeAt(a++)),l=Ad(i.charCodeAt(a++));if(c===void 0||l===void 0)throw new Wc(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function Z0(s,e){const t=Cw(s,e);return Sw(t)}function Tw(s,e={}){const t=G0.encode(s);return typeof e.size=="number"?(to(t,{size:e.size}),eo(t,{dir:"right",size:e.size})):t}function _c(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function J0(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Vc(s,...e){if(!J0(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function h6(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");_c(s.outputLen),_c(s.blockLen)}function Nd(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function X0(s,e){Vc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Ua=BigInt(2**32-1),_d=BigInt(32);function eI(s,e=!1){return e?{h:Number(s&Ua),l:Number(s>>_d&Ua)}:{h:Number(s>>_d&Ua)|0,l:Number(s&Ua)|0}}function tI(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=eI(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const sI=(s,e,t)=>s<<t|e>>>32-t,iI=(s,e,t)=>e<<t|s>>>32-t,rI=(s,e,t)=>e<<t-32|s>>>64-t,nI=(s,e,t)=>s<<t-32|e>>>64-t,Vr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function oI(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function u6(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function d6(s,e){return s<<32-e|s>>>e}const Cd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function aI(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Sd(s){for(let e=0;e<s.length;e++)s[e]=aI(s[e])}function cI(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Pw(s){return typeof s=="string"&&(s=cI(s)),Vc(s),s}function p6(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Vc(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}let lI=class{clone(){return this._cloneInto()}};function hI(s){const e=i=>s().update(Pw(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function f6(s=32){if(Vr&&typeof Vr.getRandomValues=="function")return Vr.getRandomValues(new Uint8Array(s));if(Vr&&typeof Vr.randomBytes=="function")return Vr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const $w=[],Mw=[],Ow=[],uI=BigInt(0),wo=BigInt(1),dI=BigInt(2),pI=BigInt(7),gI=BigInt(256),fI=BigInt(113);for(let s=0,e=wo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],$w.push(2*(5*i+t)),Mw.push((s+1)*(s+2)/2%64);let r=uI;for(let n=0;n<7;n++)e=(e<<wo^(e>>pI)*fI)%gI,e&dI&&(r^=wo<<(wo<<BigInt(n))-wo);Ow.push(r)}const[wI,yI]=tI(Ow,!0),Td=(s,e,t)=>t>32?rI(s,e,t):sI(s,e,t),Pd=(s,e,t)=>t>32?nI(s,e,t):iI(s,e,t);function mI(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],h=t[c+1],u=Td(l,h,1)^t[a],d=Pd(l,h,1)^t[a+1];for(let g=0;g<50;g+=10)s[o+g]^=u,s[o+g+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Mw[o],c=Td(r,n,a),l=Pd(r,n,a),h=$w[o];r=s[h],n=s[h+1],s[h]=c,s[h+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=wI[i],s[1]^=yI[i]}t.fill(0)}let bI=class xw extends lI{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,_c(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=oI(this.state)}keccak(){Cd||Sd(this.state32),mI(this.state32,this.rounds),Cd||Sd(this.state32),this.posOut=0,this.pos=0}update(e){Nd(this);const{blockLen:t,state:i}=this;e=Pw(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Nd(this,!1),Vc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return _c(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(X0(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new xw(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const vI=(s,e,t)=>hI(()=>new bI(e,s,t)),II=vI(1,136,256/8);function Dw(s,e){const t=e||"hex",i=II(ea(s,{strict:!1})?Y0(s):s);return t==="bytes"?i:wh(i)}let EI=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}};const Il=new EI(8192);function AI(s,e){if(Il.has(`${s}.${e}`))return Il.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=Dw(Tw(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Il.set(`${s}.${e}`,n),n}function NI(s){const e=Dw(`0x${s.substring(4)}`).substring(26);return AI(`0x${e}`)}async function _I({hash:s,signature:e}){const t=ea(s)?s:wh(s),{secp256k1:i}=await Zo(async()=>{const{secp256k1:o}=await import("./secp256k1-DwTU3j1N.js");return{secp256k1:o}},__vite__mapDeps([4,1,2,5,6,7,8,9,10,11]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:h,v:u,yParity:d}=e,g=Number(d??u),p=$d(g);return new i.Signature(fh(l),fh(h)).addRecoveryBit(p)}const o=ea(e)?e:wh(e),a=B0(`0x${o.slice(130)}`),c=$d(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function $d(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function CI({hash:s,signature:e}){return NI(await _I({hash:s,signature:e}))}var kw=Hv(),SI={};const jw=":";function zn(s){const[e,t]=s.split(jw);return{namespace:e,reference:t}}function TI(s){const[e,t,i]=s.split(jw);return{namespace:e,reference:t,address:i}}function Rw(s,e){return s.includes(":")?[s]:e.chains||[]}const PI="ReactNative",vs={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},$I="js";function Cc(){return typeof T.process<"u"&&typeof T.process.versions<"u"&&typeof T.process.versions.node<"u"}function ar(){return!rr()&&!!qc()&&navigator.product===PI}function MI(){return ar()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"&&(T.global==null?void 0:T.global.Platform.OS)==="android"}function OI(){return ar()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"&&(T.global==null?void 0:T.global.Platform.OS)==="ios"}function ga(){return!Cc()&&!!qc()&&!!rr()}function fa(){return ar()?vs.reactNative:Cc()?vs.node:ga()?vs.browser:vs.unknown}function Md(){var s;try{return ar()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Application)<"u"?(s=T.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function xI(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function Uw(){return cw()||{name:"",description:"",url:"",icons:[""]}}function DI(){if(fa()===vs.reactNative&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"){const{OS:t,Version:i}=T.global.Platform;return[t,i].join("-")}const s=hw();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function kI(){var s;const e=fa();return e===vs.browser?[e,((s=uw())==null?void 0:s.host)||"unknown"].join(":"):e}function Lw(s,e,t){const i=DI(),r=kI();return[[s,e].join("-"),[$I,t].join("-"),i,r].join("/")}function jI({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=t.split("?"),h=Lw(s,e,i),u={auth:r,ua:h,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=xI(l[1]||"",u);return l[0]+"?"+d}function Cr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function zw(s){return Object.fromEntries(s.entries())}function Fw(s){return new Map(Object.entries(s))}function mr(s=N.FIVE_MINUTES,e){const t=N.toMiliseconds(s||N.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},t),i=a,r=c})}}function Yi(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function qw(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${s}`)}function RI(s){return qw("topic",s)}function UI(s){return qw("id",s)}function Bw(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function mt(s,e){return N.fromMiliseconds(Date.now()+N.toMiliseconds(s))}function Wi(s){return Date.now()>=N.toMiliseconds(s)}function Te(s,e){return`${s}${e?`:${e}`:""}`}function cc(s=[],e=[]){return[...new Set([...s,...e])]}async function LI({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=zI(n,s,e),a=fa();if(a===vs.browser){if(!((i=rr())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}FI(o)}else a===vs.reactNative&&typeof(T.global==null?void 0:T.global.Linking)<"u"&&await T.global.Linking.openURL(o)}catch(r){console.error(r)}}function zI(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${WI(i,!0)}`}else r=`${r}/wc?${i}`;return r}function FI(s){let e="_self";HI()?e="_top":(BI()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function qI(s,e){let t="";try{if(ga()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Od(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function xd(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function bu(){return typeof T.process<"u"&&SI.IS_VITEST==="true"}function BI(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function HI(){try{return window.self!==window.top}catch{return!1}}function WI(s,e=!1){const t=T.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Hw(s){return T.Buffer.from(s,"base64").toString("utf-8")}function VI(s){return new Promise(e=>setTimeout(e,s))}function ta(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function KI(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Kc(s,...e){if(!KI(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function vu(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ta(s.outputLen),ta(s.blockLen)}function Hn(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ww(s,e){Kc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const La=BigInt(2**32-1),Dd=BigInt(32);function GI(s,e=!1){return e?{h:Number(s&La),l:Number(s>>Dd&La)}:{h:Number(s>>Dd&La)|0,l:Number(s&La)|0}}function YI(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=GI(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const QI=(s,e,t)=>s<<t|e>>>32-t,ZI=(s,e,t)=>e<<t|s>>>32-t,JI=(s,e,t)=>e<<t-32|s>>>64-t,XI=(s,e,t)=>s<<t-32|e>>>64-t,Kr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function e1(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function El(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function ti(s,e){return s<<32-e|s>>>e}const kd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function t1(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function jd(s){for(let e=0;e<s.length;e++)s[e]=t1(s[e])}function s1(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Wn(s){return typeof s=="string"&&(s=s1(s)),Kc(s),s}let Iu=class{clone(){return this._cloneInto()}};function Vw(s){const e=i=>s().update(Wn(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function wa(s=32){if(Kr&&typeof Kr.getRandomValues=="function")return Kr.getRandomValues(new Uint8Array(s));if(Kr&&typeof Kr.randomBytes=="function")return Kr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Kw=[],Gw=[],Yw=[],i1=BigInt(0),yo=BigInt(1),r1=BigInt(2),n1=BigInt(7),o1=BigInt(256),a1=BigInt(113);for(let s=0,e=yo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Kw.push(2*(5*i+t)),Gw.push((s+1)*(s+2)/2%64);let r=i1;for(let n=0;n<7;n++)e=(e<<yo^(e>>n1)*a1)%o1,e&r1&&(r^=yo<<(yo<<BigInt(n))-yo);Yw.push(r)}const[c1,l1]=YI(Yw,!0),Rd=(s,e,t)=>t>32?JI(s,e,t):QI(s,e,t),Ud=(s,e,t)=>t>32?XI(s,e,t):ZI(s,e,t);function h1(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],h=t[c+1],u=Rd(l,h,1)^t[a],d=Ud(l,h,1)^t[a+1];for(let g=0;g<50;g+=10)s[o+g]^=u,s[o+g+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Gw[o],c=Rd(r,n,a),l=Ud(r,n,a),h=Kw[o];r=s[h],n=s[h+1],s[h]=c,s[h+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=c1[i],s[1]^=l1[i]}t.fill(0)}let u1=class Qw extends Iu{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ta(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=e1(this.state)}keccak(){kd||jd(this.state32),h1(this.state32,this.rounds),kd||jd(this.state32),this.posOut=0,this.pos=0}update(e){Hn(this);const{blockLen:t,state:i}=this;e=Wn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Hn(this,!1),Kc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ta(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ww(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Qw(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const d1=(s,e,t)=>Vw(()=>new u1(e,s,t)),p1=d1(1,136,256/8),g1="https://rpc.walletconnect.org/v1";function Zw(s){const e=`Ethereum Signed Message:
|
|
4
4
|
${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+T.Buffer.from(p1(t)).toString("hex")}async function f1(s,e,t,i,r,n){switch(t.t){case"eip191":return await w1(s,e,t.s);case"eip1271":return await y1(s,e,t.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function w1(s,e,t){return(await CI({hash:Zw(e),signature:t})).toLowerCase()===s.toLowerCase()}async function y1(s,e,t,i,r,n){const o=zn(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l="0000000000000000000000000000000000000000000000000000000000000041",h=t.substring(2),u=Zw(e).substring(2),d=a+u+c+l+h,g=await fetch(`${n||g1}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:m1(),jsonrpc:"2.0",method:"eth_call",params:[{to:s,data:d},"latest"]})}),{result:p}=await g.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function m1(){return Date.now()+Math.floor(Math.random()*1e3)}var b1=Object.defineProperty,v1=Object.defineProperties,I1=Object.getOwnPropertyDescriptors,Ld=Object.getOwnPropertySymbols,E1=Object.prototype.hasOwnProperty,A1=Object.prototype.propertyIsEnumerable,zd=(s,e,t)=>e in s?b1(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,N1=(s,e)=>{for(var t in e||(e={}))E1.call(e,t)&&zd(s,t,e[t]);if(Ld)for(var t of Ld(e))A1.call(e,t)&&zd(s,t,e[t]);return s},_1=(s,e)=>v1(s,I1(e));const C1="did:pkh:",Eu=s=>s==null?void 0:s.split(":"),S1=s=>{const e=s&&Eu(s);if(e)return s.includes(C1)?e[3]:e[1]},yh=s=>{const e=s&&Eu(s);if(e)return e[2]+":"+e[3]},Sc=s=>{const e=s&&Eu(s);if(e)return e.pop()};async function Fd(s){const{cacao:e,projectId:t}=s,{s:i,p:r}=e,n=Jw(r,r.iss),o=Sc(r.iss);return await f1(o,n,i,yh(r.iss),t)}const Jw=(s,e)=>{const t=`${s.domain} wants you to sign in with your Ethereum account:`,i=Sc(e);if(!s.aud&&!s.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=s.statement||void 0;const n=`URI: ${s.aud||s.uri}`,o=`Version: ${s.version}`,a=`Chain ID: ${S1(e)}`,c=`Nonce: ${s.nonce}`,l=`Issued At: ${s.iat}`,h=s.exp?`Expiration Time: ${s.exp}`:void 0,u=s.nbf?`Not Before: ${s.nbf}`:void 0,d=s.requestId?`Request ID: ${s.requestId}`:void 0,g=s.resources?`Resources:${s.resources.map(f=>`
|
|
5
5
|
- ${f}`).join("")}`:void 0,p=lc(s.resources);if(p){const f=sa(p);r=j1(r,f)}return[t,i,"",r,"",n,o,a,c,l,h,u,d,g].filter(f=>f!=null).join(`
|
|
6
6
|
`)};function T1(s){return T.Buffer.from(JSON.stringify(s)).toString("base64")}function P1(s){return JSON.parse(T.Buffer.from(s,"base64").toString("utf-8"))}function Mr(s){if(!s)throw new Error("No recap provided, value is undefined");if(!s.att)throw new Error("No `att` property found");const e=Object.keys(s.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=s.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(r=>{const n=i[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function $1(s,e,t,i={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[s]:M1(e,t,i)}}}function M1(s,e,t={}){e=e==null?void 0:e.sort((r,n)=>r.localeCompare(n));const i=e.map(r=>({[`${s}/${r}`]:[t]}));return Object.assign({},...i)}function Xw(s){return Mr(s),`urn:recap:${T1(s).replace(/=/g,"")}`}function sa(s){const e=P1(s.replace("urn:recap:",""));return Mr(e),e}function O1(s,e,t){const i=$1(s,e,t);return Xw(i)}function x1(s){return s&&s.includes("urn:recap:")}function D1(s,e){const t=sa(s),i=sa(e),r=k1(t,i);return Xw(r)}function k1(s,e){Mr(s),Mr(e);const t=Object.keys(s.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),i={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=s.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;i.att[r]=_1(N1({},i.att[r]),{[a]:((c=s.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),i}function j1(s="",e){Mr(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(s.includes(t))return s;const i=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,d)=>u.action.localeCompare(d.action));const l={};c.forEach(u=>{l[u.ability]||(l[u.ability]=[]),l[u.ability].push(u.action)});const h=Object.keys(l).map(u=>(r++,`(${r}) '${u}': '${l[u].join("', '")}' for '${a}'.`));i.push(h.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${s?s+" ":""}${o}`}function qd(s){var e;const t=sa(s);Mr(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function Bd(s){const e=sa(s);Mr(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(r=>{var n;(n=r==null?void 0:r[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function lc(s){if(!s)return;const e=s==null?void 0:s[s.length-1];return x1(e)?e:void 0}function Al(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function ey(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ms(s,...e){if(!ey(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Hd(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function R1(s,e){ms(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Wd(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}const er=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),U1=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),L1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!L1)throw new Error("Non little-endian hardware is not supported");function z1(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function mh(s){if(typeof s=="string")s=z1(s);else if(ey(s))s=bh(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function F1(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function q1(s,e){if(s.length!==e.length)return!1;let t=0;for(let i=0;i<s.length;i++)t|=s[i]^e[i];return t===0}const B1=(s,e)=>{function t(i,...r){if(ms(i),s.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");s.varSizeNonce?ms(l):ms(l,s.nonceLength)}const n=s.tagLength;n&&r[1]!==void 0&&ms(r[1]);const o=e(i,...r),a=(l,h)=>{if(h!==void 0){if(l!==2)throw new Error("cipher output not supported");ms(h)}};let c=!1;return{encrypt(l,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ms(l),a(o.encrypt.length,h),o.encrypt(l,h)},decrypt(l,h){if(ms(l),n&&l.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,h),o.decrypt(l,h)}}}return Object.assign(t,s),t};function Vd(s,e,t=!0){if(e===void 0)return new Uint8Array(s);if(e.length!==s)throw new Error("invalid output length, expected "+s+", got: "+e.length);if(t&&!H1(e))throw new Error("invalid output, must be aligned");return e}function Kd(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);s.setUint32(e+4,o,i),s.setUint32(e+0,a,i)}function H1(s){return s.byteOffset%4===0}function bh(s){return Uint8Array.from(s)}function Vn(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}const ty=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),W1=ty("expand 16-byte k"),V1=ty("expand 32-byte k"),K1=er(W1),G1=er(V1);function ve(s,e){return s<<e|s>>>32-e}function vh(s){return s.byteOffset%4===0}const za=64,Y1=16,sy=2**32-1,Gd=new Uint32Array;function Q1(s,e,t,i,r,n,o,a){const c=r.length,l=new Uint8Array(za),h=er(l),u=vh(r)&&vh(n),d=u?er(r):Gd,g=u?er(n):Gd;for(let p=0;p<c;o++){if(s(e,t,i,h,o,a),o>=sy)throw new Error("arx: counter overflow");const f=Math.min(za,c-p);if(u&&f===za){const b=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let m=0,w;m<Y1;m++)w=b+m,g[w]=d[w]^h[m];p+=za;continue}for(let b=0,m;b<f;b++)m=p+b,n[m]=r[m]^l[b];p+=f}}function Z1(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=F1({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return Al(r),Al(o),Wd(n),Wd(t),(a,c,l,h,u=0)=>{ms(a),ms(c),ms(l);const d=l.length;if(h===void 0&&(h=new Uint8Array(d)),ms(h),Al(u),u<0||u>=sy)throw new Error("arx: counter overflow");if(h.length<d)throw new Error(`arx: output (${h.length}) is shorter than data (${d})`);const g=[];let p=a.length,f,b;if(p===32)g.push(f=bh(a)),b=G1;else if(p===16&&t)f=new Uint8Array(32),f.set(a),f.set(a,16),b=K1,g.push(f);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);vh(c)||g.push(c=bh(c));const m=er(f);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(b,m,er(c.subarray(0,16)),m),c=c.subarray(16)}const w=16-r;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){const A=new Uint8Array(12);A.set(c,n?0:12-c.length),c=A,g.push(c)}const E=er(c);return Q1(s,b,m,E,l,h,u,o),Vn(...g),h}}const Mt=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let J1=class{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=mh(e),ms(e,32);const t=Mt(e,0),i=Mt(e,2),r=Mt(e,4),n=Mt(e,6),o=Mt(e,8),a=Mt(e,10),c=Mt(e,12),l=Mt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|r<<6)&7939,this.r[3]=(r>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let h=0;h<8;h++)this.pad[h]=Mt(e,16+2*h)}process(e,t,i=!1){const r=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],l=o[2],h=o[3],u=o[4],d=o[5],g=o[6],p=o[7],f=o[8],b=o[9],m=Mt(e,t+0),w=Mt(e,t+2),E=Mt(e,t+4),A=Mt(e,t+6),_=Mt(e,t+8),S=Mt(e,t+10),P=Mt(e,t+12),x=Mt(e,t+14);let $=n[0]+(m&8191),F=n[1]+((m>>>13|w<<3)&8191),k=n[2]+((w>>>10|E<<6)&8191),K=n[3]+((E>>>7|A<<9)&8191),q=n[4]+((A>>>4|_<<12)&8191),H=n[5]+(_>>>1&8191),W=n[6]+((_>>>14|S<<2)&8191),B=n[7]+((S>>>11|P<<5)&8191),V=n[8]+((P>>>8|x<<8)&8191),Y=n[9]+(x>>>5|r),C=0,L=C+$*a+F*(5*b)+k*(5*f)+K*(5*p)+q*(5*g);C=L>>>13,L&=8191,L+=H*(5*d)+W*(5*u)+B*(5*h)+V*(5*l)+Y*(5*c),C+=L>>>13,L&=8191;let X=C+$*c+F*a+k*(5*b)+K*(5*f)+q*(5*p);C=X>>>13,X&=8191,X+=H*(5*g)+W*(5*d)+B*(5*u)+V*(5*h)+Y*(5*l),C+=X>>>13,X&=8191;let Q=C+$*l+F*c+k*a+K*(5*b)+q*(5*f);C=Q>>>13,Q&=8191,Q+=H*(5*p)+W*(5*g)+B*(5*d)+V*(5*u)+Y*(5*h),C+=Q>>>13,Q&=8191;let me=C+$*h+F*l+k*c+K*a+q*(5*b);C=me>>>13,me&=8191,me+=H*(5*f)+W*(5*p)+B*(5*g)+V*(5*d)+Y*(5*u),C+=me>>>13,me&=8191;let ue=C+$*u+F*h+k*l+K*c+q*a;C=ue>>>13,ue&=8191,ue+=H*(5*b)+W*(5*f)+B*(5*p)+V*(5*g)+Y*(5*d),C+=ue>>>13,ue&=8191;let ee=C+$*d+F*u+k*h+K*l+q*c;C=ee>>>13,ee&=8191,ee+=H*a+W*(5*b)+B*(5*f)+V*(5*p)+Y*(5*g),C+=ee>>>13,ee&=8191;let nt=C+$*g+F*d+k*u+K*h+q*l;C=nt>>>13,nt&=8191,nt+=H*c+W*a+B*(5*b)+V*(5*f)+Y*(5*p),C+=nt>>>13,nt&=8191;let Le=C+$*p+F*g+k*d+K*u+q*h;C=Le>>>13,Le&=8191,Le+=H*l+W*c+B*a+V*(5*b)+Y*(5*f),C+=Le>>>13,Le&=8191;let be=C+$*f+F*p+k*g+K*d+q*u;C=be>>>13,be&=8191,be+=H*h+W*l+B*c+V*a+Y*(5*b),C+=be>>>13,be&=8191;let ke=C+$*b+F*f+k*p+K*g+q*d;C=ke>>>13,ke&=8191,ke+=H*u+W*h+B*l+V*c+Y*a,C+=ke>>>13,ke&=8191,C=(C<<2)+C|0,C=C+L|0,L=C&8191,C=C>>>13,X+=C,n[0]=L,n[1]=X,n[2]=Q,n[3]=me,n[4]=ue,n[5]=ee,n[6]=nt,n[7]=Le,n[8]=be,n[9]=ke}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,i[0]=e[0]+5,r=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+r,r=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;Vn(i)}update(e){Hd(this);const{buffer:t,blockLen:i}=this;e=mh(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){for(;i<=r-n;n+=i)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Vn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Hd(this),R1(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}};function X1(s){const e=(i,r)=>s(r).update(mh(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const eE=X1(s=>new J1(s));function tE(s,e,t,i,r,n=20){let o=s[0],a=s[1],c=s[2],l=s[3],h=e[0],u=e[1],d=e[2],g=e[3],p=e[4],f=e[5],b=e[6],m=e[7],w=r,E=t[0],A=t[1],_=t[2],S=o,P=a,x=c,$=l,F=h,k=u,K=d,q=g,H=p,W=f,B=b,V=m,Y=w,C=E,L=A,X=_;for(let me=0;me<n;me+=2)S=S+F|0,Y=ve(Y^S,16),H=H+Y|0,F=ve(F^H,12),S=S+F|0,Y=ve(Y^S,8),H=H+Y|0,F=ve(F^H,7),P=P+k|0,C=ve(C^P,16),W=W+C|0,k=ve(k^W,12),P=P+k|0,C=ve(C^P,8),W=W+C|0,k=ve(k^W,7),x=x+K|0,L=ve(L^x,16),B=B+L|0,K=ve(K^B,12),x=x+K|0,L=ve(L^x,8),B=B+L|0,K=ve(K^B,7),$=$+q|0,X=ve(X^$,16),V=V+X|0,q=ve(q^V,12),$=$+q|0,X=ve(X^$,8),V=V+X|0,q=ve(q^V,7),S=S+k|0,X=ve(X^S,16),B=B+X|0,k=ve(k^B,12),S=S+k|0,X=ve(X^S,8),B=B+X|0,k=ve(k^B,7),P=P+K|0,Y=ve(Y^P,16),V=V+Y|0,K=ve(K^V,12),P=P+K|0,Y=ve(Y^P,8),V=V+Y|0,K=ve(K^V,7),x=x+q|0,C=ve(C^x,16),H=H+C|0,q=ve(q^H,12),x=x+q|0,C=ve(C^x,8),H=H+C|0,q=ve(q^H,7),$=$+F|0,L=ve(L^$,16),W=W+L|0,F=ve(F^W,12),$=$+F|0,L=ve(L^$,8),W=W+L|0,F=ve(F^W,7);let Q=0;i[Q++]=o+S|0,i[Q++]=a+P|0,i[Q++]=c+x|0,i[Q++]=l+$|0,i[Q++]=h+F|0,i[Q++]=u+k|0,i[Q++]=d+K|0,i[Q++]=g+q|0,i[Q++]=p+H|0,i[Q++]=f+W|0,i[Q++]=b+B|0,i[Q++]=m+V|0,i[Q++]=w+Y|0,i[Q++]=E+C|0,i[Q++]=A+L|0,i[Q++]=_+X|0}const sE=Z1(tE,{counterRight:!1,counterLength:4,allowShortKeys:!1}),iE=new Uint8Array(16),Yd=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(iE.subarray(t))},rE=new Uint8Array(32);function Qd(s,e,t,i,r){const n=s(e,t,rE),o=eE.create(n);r&&Yd(o,r),Yd(o,i);const a=new Uint8Array(16),c=U1(a);Kd(c,0,BigInt(r?r.length:0),!0),Kd(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return Vn(n,a),l}const nE=s=>(e,t,i)=>({encrypt(r,n){const o=r.length;n=Vd(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);s(e,t,a,a,1);const c=Qd(s,e,t,a,i);return n.set(c,o),Vn(c),n},decrypt(r,n){n=Vd(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Qd(s,e,t,o,i);if(!q1(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),Vn(c),n}}),iy=B1({blockSize:64,nonceLength:12,tagLength:16},nE(sE));let ry=class extends Iu{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,vu(e);const i=Wn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return Hn(this),this.iHash.update(e),this}digestInto(e){Hn(this),Kc(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:i,finished:r,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Au=(s,e,t)=>new ry(s,e).update(t).digest();Au.create=(s,e)=>new ry(s,e);function oE(s,e,t){return vu(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Au(s,Wn(t),Wn(e))}const Nl=new Uint8Array([0]),Zd=new Uint8Array;function aE(s,e,t,i=32){if(vu(s),ta(i),i>255*s.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/s.outputLen);t===void 0&&(t=Zd);const n=new Uint8Array(r*s.outputLen),o=Au.create(s,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)Nl[0]=l+1,a.update(l===0?Zd:c).update(t).update(Nl).digestInto(c),n.set(c,s.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Nl.fill(0),n.slice(0,i)}const cE=(s,e,t,i,r)=>aE(s,oE(s,e,t),i,r);function lE(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=i?4:0,l=i?0:4;s.setUint32(e+c,o,i),s.setUint32(e+l,a,i)}function hE(s,e,t){return s&e^~s&t}function uE(s,e,t){return s&e^s&t^e&t}let dE=class extends Iu{constructor(e,t,i,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=El(this.buffer)}update(e){Hn(this);const{view:t,buffer:i,blockLen:r}=this;e=Wn(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const c=El(e);for(;r<=n-o;o+=r)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Hn(this),Ww(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(i,0),o=0);for(let u=o;u<r;u++)t[u]=0;lE(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=El(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,h[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:r,finished:n,destroyed:o,pos:a}=this;return e.length=r,e.pos=a,e.finished=n,e.destroyed=o,r%t&&e.buffer.set(i),e}};const pE=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]),Ui=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Li=new Uint32Array(64);let gE=class extends dE{constructor(){super(64,32,8,!1),this.A=Ui[0]|0,this.B=Ui[1]|0,this.C=Ui[2]|0,this.D=Ui[3]|0,this.E=Ui[4]|0,this.F=Ui[5]|0,this.G=Ui[6]|0,this.H=Ui[7]|0}get(){const{A:e,B:t,C:i,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,i,r,n,o,a,c]}set(e,t,i,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=i|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Li[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const d=Li[u-15],g=Li[u-2],p=ti(d,7)^ti(d,18)^d>>>3,f=ti(g,17)^ti(g,19)^g>>>10;Li[u]=f+Li[u-7]+p+Li[u-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:c,G:l,H:h}=this;for(let u=0;u<64;u++){const d=ti(a,6)^ti(a,11)^ti(a,25),g=h+d+hE(a,c,l)+pE[u]+Li[u]|0,p=(ti(i,2)^ti(i,13)^ti(i,22))+uE(i,r,n)|0;h=l,l=c,c=a,a=o+g|0,o=n,n=r,r=i,i=g+p|0}i=i+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(i,r,n,o,a,c,l,h)}roundClean(){Li.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const Gc=Vw(()=>new gE);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ny=BigInt(0);function Nu(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function oy(s){if(!Nu(s))throw new Error("Uint8Array expected")}const fE=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function wE(s){oy(s);let e="";for(let t=0;t<s.length;t++)e+=fE[s[t]];return e}function yE(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?ny:BigInt("0x"+s)}const vi={_0:48,_9:57,A:65,F:70,a:97,f:102};function Jd(s){if(s>=vi._0&&s<=vi._9)return s-vi._0;if(s>=vi.A&&s<=vi.F)return s-(vi.A-10);if(s>=vi.a&&s<=vi.f)return s-(vi.a-10)}function ay(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=Jd(s.charCodeAt(n)),a=Jd(s.charCodeAt(n+1));if(o===void 0||a===void 0){const c=s[n]+s[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[r]=o*16+a}return i}function Xd(s){return oy(s),yE(wE(Uint8Array.from(s).reverse()))}function mE(s,e){return ay(s.toString(16).padStart(e*2,"0"))}function bE(s,e){return mE(s,e).reverse()}function ep(s,e,t){let i;if(typeof e=="string")try{i=ay(e)}catch(n){throw new Error(s+" must be hex string or Uint8Array, cause: "+n)}else if(Nu(e))i=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");const r=i.length;if(typeof t=="number"&&r!==t)throw new Error(s+" of length "+t+" expected, got "+r);return i}const _l=s=>typeof s=="bigint"&&ny<=s;function vE(s,e,t){return _l(s)&&_l(e)&&_l(t)&&e<=s&&s<t}function tp(s,e,t,i){if(!vE(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const IE={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||Nu(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function EE(s,e,t={}){const i=(r,n,o)=>{const a=IE[n];if(typeof a!="function")throw new Error("invalid validator function");const c=s[r];if(!(o&&c===void 0)&&!a(c,s))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))i(r,n,!1);for(const[r,n]of Object.entries(t))i(r,n,!0);return s}const Dn=BigInt(0),Fa=BigInt(1);function cy(s,e){const t=s%e;return t>=Dn?t:e+t}function AE(s,e,t){if(e<Dn)throw new Error("invalid exponent, negatives unsupported");if(t<=Dn)throw new Error("invalid modulus");if(t===Fa)return Dn;let i=Fa;for(;e>Dn;)e&Fa&&(i=i*s%t),s=s*s%t,e>>=Fa;return i}function Gs(s,e,t){let i=s;for(;e-- >Dn;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Gr=BigInt(0),Cl=BigInt(1);function NE(s){return EE(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function _E(s){const e=NE(s),{P:t}=e,i=w=>cy(w,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(w=>w),c=e.powPminus2||(w=>AE(w,t-BigInt(2),t));function l(w,E,A){const _=i(w*(E-A));return E=i(E-_),A=i(A+_),[E,A]}const h=(e.a-BigInt(2))/BigInt(4);function u(w,E){tp("u",w,Gr,t),tp("scalar",E,Gr,t);const A=E,_=w;let S=Cl,P=Gr,x=w,$=Cl,F=Gr,k;for(let q=BigInt(r-1);q>=Gr;q--){const H=A>>q&Cl;F^=H,k=l(F,S,x),S=k[0],x=k[1],k=l(F,P,$),P=k[0],$=k[1],F=H;const W=S+P,B=i(W*W),V=S-P,Y=i(V*V),C=B-Y,L=x+$,X=x-$,Q=i(X*W),me=i(L*V),ue=Q+me,ee=Q-me;x=i(ue*ue),$=i(_*i(ee*ee)),S=i(B*Y),P=i(C*(B+i(h*C)))}k=l(F,S,x),S=k[0],x=k[1],k=l(F,P,$),P=k[0],$=k[1];const K=c(P);return i(S*K)}function d(w){return bE(i(w),n)}function g(w){const E=ep("u coordinate",w,n);return o===32&&(E[31]&=127),Xd(E)}function p(w){const E=ep("scalar",w),A=E.length;if(A!==n&&A!==o){let _=""+n+" or "+o;throw new Error("invalid scalar, expected "+_+" bytes, got "+A)}return Xd(a(E))}function f(w,E){const A=g(E),_=p(w),S=u(A,_);if(S===Gr)throw new Error("invalid private or public key received");return d(S)}const b=d(e.Gu);function m(w){return f(w,b)}return{scalarMult:f,scalarMultBase:m,getSharedSecret:(w,E)=>f(w,E),getPublicKey:w=>m(w),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:b}}const Ih=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const CE=BigInt(1),sp=BigInt(2),SE=BigInt(3),TE=BigInt(5);BigInt(8);function PE(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=Ih,o=s*s%n*s%n,a=Gs(o,sp,n)*o%n,c=Gs(a,CE,n)*s%n,l=Gs(c,TE,n)*c%n,h=Gs(l,e,n)*l%n,u=Gs(h,t,n)*h%n,d=Gs(u,i,n)*u%n,g=Gs(d,r,n)*d%n,p=Gs(g,r,n)*d%n,f=Gs(p,e,n)*l%n;return{pow_p_5_8:Gs(f,sp,n)*s%n,b2:o}}function $E(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const Eh=_E({P:Ih,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=Ih,{pow_p_5_8:t,b2:i}=PE(s);return cy(Gs(t,SE,e)*i,e)},adjustScalarBytes:$E,randomBytes:wa}),ly="base10",Yt="base16",Qi="base64pad",mo="base64url",ya="utf8",hy=0,Mi=1,ma=2,ME=0,ip=1,Bo=12,_u=32;function OE(){const s=Eh.utils.randomPrivateKey(),e=Eh.getPublicKey(s);return{privateKey:$e(s,Yt),publicKey:$e(e,Yt)}}function Ah(){const s=wa(_u);return $e(s,Yt)}function xE(s,e){const t=Eh.getSharedSecret(et(s,Yt),et(e,Yt)),i=cE(Gc,t,void 0,void 0,_u);return $e(i,Yt)}function hc(s){const e=Gc(et(s,Yt));return $e(e,Yt)}function Pi(s){const e=Gc(et(s,ya));return $e(e,Yt)}function uy(s){return et(`${s}`,ly)}function Or(s){return Number($e(s,ly))}function DE(s){const e=uy(typeof s.type<"u"?s.type:hy);if(Or(e)===Mi&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?et(s.senderPublicKey,Yt):void 0,i=typeof s.iv<"u"?et(s.iv,Yt):wa(Bo),r=et(s.symKey,Yt),n=iy(r,i).encrypt(et(s.message,ya));return dy({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function kE(s){const e=et(s.symKey,Yt),{sealed:t,iv:i}=ia(s),r=iy(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return $e(r,ya)}function jE(s,e){const t=uy(ma),i=wa(Bo),r=et(s,ya);return dy({type:t,sealed:r,iv:i,encoding:e})}function RE(s,e){const{sealed:t}=ia({encoded:s,encoding:e});return $e(t,ya)}function dy(s){const{encoding:e=Qi}=s;if(Or(s.type)===ma)return $e(Un([s.type,s.sealed]),e);if(Or(s.type)===Mi){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return $e(Un([s.type,s.senderPublicKey,s.iv,s.sealed]),e)}return $e(Un([s.type,s.iv,s.sealed]),e)}function ia(s){const{encoded:e,encoding:t=Qi}=s,i=et(e,t),r=i.slice(ME,ip),n=ip;if(Or(r)===Mi){const l=n+_u,h=l+Bo,u=i.slice(n,l),d=i.slice(l,h),g=i.slice(h);return{type:r,sealed:g,iv:d,senderPublicKey:u}}if(Or(r)===ma){const l=i.slice(n),h=wa(Bo);return{type:r,sealed:l,iv:h}}const o=n+Bo,a=i.slice(n,o),c=i.slice(o);return{type:r,sealed:c,iv:a}}function UE(s,e){const t=ia({encoded:s,encoding:e==null?void 0:e.encoding});return py({type:Or(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?$e(t.senderPublicKey,Yt):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function py(s){const e=(s==null?void 0:s.type)||hy;if(e===Mi){if(typeof(s==null?void 0:s.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(s==null?void 0:s.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:s==null?void 0:s.senderPublicKey,receiverPublicKey:s==null?void 0:s.receiverPublicKey}}function rp(s){return s.type===Mi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function np(s){return s.type===ma}function LE(s){return new kw.ec("p256").keyFromPublic({x:T.Buffer.from(s.x,"base64").toString("hex"),y:T.Buffer.from(s.y,"base64").toString("hex")},"hex")}function zE(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function FE(s){return T.Buffer.from(zE(s),"base64")}function qE(s,e){const[t,i,r]=s.split("."),n=FE(r);if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32).toString("hex"),a=n.slice(32,64).toString("hex"),c=`${t}.${i}`,l=Gc(c),h=LE(e),u=$e(l,Yt);if(!h.verify(u,{r:o,s:a}))throw new Error("Invalid signature");return Bn(s).payload}const BE="irn";function Tc(s){return(s==null?void 0:s.relay)||{protocol:BE}}function jo(s){const e=lw[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function HE(s,e="-"){const t={},i="relay"+e;return Object.keys(s).forEach(r=>{if(r.startsWith(i)){const n=r.replace(i,""),o=s[r];t[n]=o}}),t}function op(s){if(!s.includes("wc:")){const l=Hw(s);l!=null&&l.includes("wc:")&&(s=l)}s=s.includes("wc://")?s.replace("wc://",""):s,s=s.includes("wc:")?s.replace("wc:",""):s;const e=s.indexOf(":"),t=s.indexOf("?")!==-1?s.indexOf("?"):void 0,i=s.substring(0,e),r=s.substring(e+1,t).split("@"),n=typeof t<"u"?s.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((l,h)=>{a[h]=l});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:WE(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:HE(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function WE(s){return s.startsWith("//")?s.substring(2):s}function VE(s,e="-"){const t="relay",i={};return Object.keys(s).forEach(r=>{const n=r,o=t+e+n;s[n]&&(i[o]=s[n])}),i}function ap(s){const e=new URLSearchParams,t=VE(s.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",s.symKey),s.expiryTimestamp&&e.set("expiryTimestamp",s.expiryTimestamp.toString()),s.methods&&e.set("methods",s.methods.join(","));const i=e.toString();return`${s.protocol}:${s.topic}@${s.version}?${i}`}function qa(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function so(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function KE(s){const e=[];return Object.values(s).forEach(t=>{e.push(...so(t.accounts))}),e}function GE(s,e){const t=[];return Object.values(s).forEach(i=>{so(i.accounts).includes(e)&&t.push(...i.methods)}),t}function YE(s,e){const t=[];return Object.values(s).forEach(i=>{so(i.accounts).includes(e)&&t.push(...i.events)}),t}function Cu(s){return s.includes(":")}function Ro(s){return Cu(s)?s.split(":")[0]:s}function QE(s){const e={};return s==null||s.forEach(t=>{var i;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(i=e[r].chains)==null||i.push(`${r}:${n}`)}),e}function cp(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=QE(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=cc(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const ZE={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}},JE={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 R(s,e){const{message:t,code:i}=JE[s];return{message:e?`${t} ${e}`:t,code:i}}function Re(s,e){const{message:t,code:i}=ZE[s];return{message:e?`${t} ${e}`:t,code:i}}function xr(s,e){return!!Array.isArray(s)}function ra(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function Xt(s){return typeof s>"u"}function ht(s,e){return e&&Xt(s)?!0:typeof s=="string"&&!!s.trim().length}function Su(s,e){return e&&Xt(s)?!0:typeof s=="number"&&!isNaN(s)}function XE(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return Cr(r,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=s.namespaces[o],h=so(a),u=t[o];(!Cr(Rw(o,u),h)||!Cr(u.methods,c)||!Cr(u.events,l))&&(n=!1)}),n):!1}function Pc(s){return ht(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function eA(s){if(ht(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Pc(t)}}return!1}function tA(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(ht(s,!1)){if(e(s))return!0;const t=Hw(s);return e(t)}}catch{}return!1}function sA(s){var e;return(e=s==null?void 0:s.proposer)==null?void 0:e.publicKey}function iA(s){return s==null?void 0:s.topic}function rA(s,e){let t=null;return ht(s==null?void 0:s.publicKey,!1)||(t=R("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function lp(s){let e=!0;return xr(s)?s.length&&(e=s.every(t=>ht(t,!1))):e=!1,e}function nA(s,e,t){let i=null;return xr(e)&&e.length?e.forEach(r=>{i||Pc(r)||(i=Re("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Pc(s)||(i=Re("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function oA(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=nA(r,Rw(r,n),`${e} ${t}`);o&&(i=o)}),i}function aA(s,e){let t=null;return xr(s)?s.forEach(i=>{t||eA(i)||(t=Re("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Re("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function cA(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=aA(i==null?void 0:i.accounts,`${e} namespace`);r&&(t=r)}),t}function lA(s,e){let t=null;return lp(s==null?void 0:s.methods)?lp(s==null?void 0:s.events)||(t=Re("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Re("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function gy(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=lA(i,`${e}, namespace`);r&&(t=r)}),t}function hA(s,e,t){let i=null;if(s&&ra(s)){const r=gy(s,e);r&&(i=r);const n=oA(s,e,t);n&&(i=n)}else i=R("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function Sl(s,e){let t=null;if(s&&ra(s)){const i=gy(s,e);i&&(t=i);const r=cA(s,e);r&&(t=r)}else t=R("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function fy(s){return ht(s.protocol,!0)}function uA(s,e){let t=!1;return s?s&&xr(s)&&s.length&&s.forEach(i=>{t=fy(i)}):t=!0,t}function dA(s){return typeof s=="number"}function ns(s){return typeof s<"u"&&typeof s!==null}function pA(s){return!(!s||typeof s!="object"||!s.code||!Su(s.code,!1)||!s.message||!ht(s.message,!1))}function gA(s){return!(Xt(s)||!ht(s.method,!1))}function fA(s){return!(Xt(s)||Xt(s.result)&&Xt(s.error)||!Su(s.id,!1)||!ht(s.jsonrpc,!1))}function wA(s){return!(Xt(s)||!ht(s.name,!1))}function hp(s,e){return!(!Pc(e)||!KE(s).includes(e))}function yA(s,e,t){return ht(t,!1)?GE(s,e).includes(t):!1}function mA(s,e,t){return ht(t,!1)?YE(s,e).includes(t):!1}function up(s,e,t){let i=null;const r=bA(s),n=vA(e),o=Object.keys(r),a=Object.keys(n),c=dp(Object.keys(s)),l=dp(Object.keys(e)),h=c.filter(u=>!l.includes(u));return h.length&&(i=R("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
|
|
@@ -10,7 +10,7 @@ ${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+T.Buffer.from(p1(t)).toS
|
|
|
10
10
|
Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||i)return;const d=so(e[u].accounts);d.includes(u)||(i=R("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${u}
|
|
11
11
|
Required: ${u}
|
|
12
12
|
Approved: ${d.toString()}`))}),o.forEach(u=>{i||(Cr(r[u].methods,n[u].methods)?Cr(r[u].events,n[u].events)||(i=R("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):i=R("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),i}function bA(s){const e={};return Object.keys(s).forEach(t=>{var i;t.includes(":")?e[t]=s[t]:(i=s[t].chains)==null||i.forEach(r=>{e[r]={methods:s[t].methods,events:s[t].events}})}),e}function dp(s){return[...new Set(s.map(e=>e.includes(":")?e.split(":")[0]:e))]}function vA(s){const e={};return Object.keys(s).forEach(t=>{if(t.includes(":"))e[t]=s[t];else{const i=so(s[t].accounts);i==null||i.forEach(r=>{e[r]={accounts:s[t].accounts.filter(n=>n.includes(`${r}:`)),methods:s[t].methods,events:s[t].events}})}}),e}function IA(s,e){return Su(s,!1)&&s<=e.max&&s>=e.min}function pp(){const s=fa();return new Promise(e=>{switch(s){case vs.browser:e(EA());break;case vs.reactNative:e(AA());break;case vs.node:e(NA());break;default:e(!0)}})}function EA(){return ga()&&(navigator==null?void 0:navigator.onLine)}async function AA(){if(ar()&&typeof T.global<"u"&&T.global!=null&&T.global.NetInfo){const s=await(T.global==null?void 0:T.global.NetInfo.fetch());return s==null?void 0:s.isConnected}return!0}function NA(){return!0}function _A(s){switch(fa()){case vs.browser:CA(s);break;case vs.reactNative:SA(s);break}}function CA(s){!ar()&&ga()&&(window.addEventListener("online",()=>s(!0)),window.addEventListener("offline",()=>s(!1)))}function SA(s){var e;ar()&&typeof T.global<"u"&&T.global!=null&&T.global.NetInfo&&((e=T.global)==null||e.NetInfo.addEventListener(t=>s(t==null?void 0:t.isConnected)))}const Tl={};let bo=class{static get(e){return Tl[e]}static set(e,t){Tl[e]=t}static delete(e){delete Tl[e]}};var $c={exports:{}};$c.exports;(function(s,e){var t=200,i="__lodash_hash_undefined__",r=1,n=2,o=9007199254740991,a="[object Arguments]",c="[object Array]",l="[object AsyncFunction]",h="[object Boolean]",u="[object Date]",d="[object Error]",g="[object Function]",p="[object GeneratorFunction]",f="[object Map]",b="[object Number]",m="[object Null]",w="[object Object]",E="[object Promise]",A="[object Proxy]",_="[object RegExp]",S="[object Set]",P="[object String]",x="[object Symbol]",$="[object Undefined]",F="[object WeakMap]",k="[object ArrayBuffer]",K="[object DataView]",q="[object Float32Array]",H="[object Float64Array]",W="[object Int8Array]",B="[object Int16Array]",V="[object Int32Array]",Y="[object Uint8Array]",C="[object Uint8ClampedArray]",L="[object Uint16Array]",X="[object Uint32Array]",Q=/[\\^$.*+?()[\]{}|]/g,me=/^\[object .+?Constructor\]$/,ue=/^(?:0|[1-9]\d*)$/,ee={};ee[q]=ee[H]=ee[W]=ee[B]=ee[V]=ee[Y]=ee[C]=ee[L]=ee[X]=!0,ee[a]=ee[c]=ee[k]=ee[h]=ee[K]=ee[u]=ee[d]=ee[g]=ee[f]=ee[b]=ee[w]=ee[_]=ee[S]=ee[P]=ee[F]=!1;var nt=typeof ja=="object"&&ja&&ja.Object===Object&&ja,Le=typeof self=="object"&&self&&self.Object===Object&&self,be=nt||Le||Function("return this")(),ke=e&&!e.nodeType&&e,Zs=ke&&!0&&s&&!s.nodeType&&s,Js=Zs&&Zs.exports===ke,wi=Js&&nt.process,Hr=function(){try{return wi&&wi.binding&&wi.binding("util")}catch{}}(),Xs=Hr&&Hr.isTypedArray;function ao(y,I){for(var M=-1,G=y==null?0:y.length,Qe=0,ne=[];++M<G;){var ot=y[M];I(ot,M,y)&&(ne[Qe++]=ot)}return ne}function Ob(y,I){for(var M=-1,G=I.length,Qe=y.length;++M<G;)y[Qe+M]=I[M];return y}function xb(y,I){for(var M=-1,G=y==null?0:y.length;++M<G;)if(I(y[M],M,y))return!0;return!1}function Db(y,I){for(var M=-1,G=Array(y);++M<y;)G[M]=I(M);return G}function kb(y){return function(I){return y(I)}}function jb(y,I){return y.has(I)}function Rb(y,I){return y==null?void 0:y[I]}function Ub(y){var I=-1,M=Array(y.size);return y.forEach(function(G,Qe){M[++I]=[Qe,G]}),M}function Lb(y,I){return function(M){return y(I(M))}}function zb(y){var I=-1,M=Array(y.size);return y.forEach(function(G){M[++I]=G}),M}var Fb=Array.prototype,qb=Function.prototype,Ta=Object.prototype,ll=be["__core-js_shared__"],Yu=qb.toString,ei=Ta.hasOwnProperty,Qu=function(){var y=/[^.]+$/.exec(ll&&ll.keys&&ll.keys.IE_PROTO||"");return y?"Symbol(src)_1."+y:""}(),Zu=Ta.toString,Bb=RegExp("^"+Yu.call(ei).replace(Q,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ju=Js?be.Buffer:void 0,Pa=be.Symbol,Xu=be.Uint8Array,ed=Ta.propertyIsEnumerable,Hb=Fb.splice,lr=Pa?Pa.toStringTag:void 0,td=Object.getOwnPropertySymbols,Wb=Ju?Ju.isBuffer:void 0,Vb=Lb(Object.keys,Object),hl=Wr(be,"DataView"),co=Wr(be,"Map"),ul=Wr(be,"Promise"),dl=Wr(be,"Set"),pl=Wr(be,"WeakMap"),lo=Wr(Object,"create"),Kb=dr(hl),Gb=dr(co),Yb=dr(ul),Qb=dr(dl),Zb=dr(pl),sd=Pa?Pa.prototype:void 0,gl=sd?sd.valueOf:void 0;function hr(y){var I=-1,M=y==null?0:y.length;for(this.clear();++I<M;){var G=y[I];this.set(G[0],G[1])}}function Jb(){this.__data__=lo?lo(null):{},this.size=0}function Xb(y){var I=this.has(y)&&delete this.__data__[y];return this.size-=I?1:0,I}function ev(y){var I=this.__data__;if(lo){var M=I[y];return M===i?void 0:M}return ei.call(I,y)?I[y]:void 0}function tv(y){var I=this.__data__;return lo?I[y]!==void 0:ei.call(I,y)}function sv(y,I){var M=this.__data__;return this.size+=this.has(y)?0:1,M[y]=lo&&I===void 0?i:I,this}hr.prototype.clear=Jb,hr.prototype.delete=Xb,hr.prototype.get=ev,hr.prototype.has=tv,hr.prototype.set=sv;function yi(y){var I=-1,M=y==null?0:y.length;for(this.clear();++I<M;){var G=y[I];this.set(G[0],G[1])}}function iv(){this.__data__=[],this.size=0}function rv(y){var I=this.__data__,M=Ma(I,y);if(M<0)return!1;var G=I.length-1;return M==G?I.pop():Hb.call(I,M,1),--this.size,!0}function nv(y){var I=this.__data__,M=Ma(I,y);return M<0?void 0:I[M][1]}function ov(y){return Ma(this.__data__,y)>-1}function av(y,I){var M=this.__data__,G=Ma(M,y);return G<0?(++this.size,M.push([y,I])):M[G][1]=I,this}yi.prototype.clear=iv,yi.prototype.delete=rv,yi.prototype.get=nv,yi.prototype.has=ov,yi.prototype.set=av;function ur(y){var I=-1,M=y==null?0:y.length;for(this.clear();++I<M;){var G=y[I];this.set(G[0],G[1])}}function cv(){this.size=0,this.__data__={hash:new hr,map:new(co||yi),string:new hr}}function lv(y){var I=Oa(this,y).delete(y);return this.size-=I?1:0,I}function hv(y){return Oa(this,y).get(y)}function uv(y){return Oa(this,y).has(y)}function dv(y,I){var M=Oa(this,y),G=M.size;return M.set(y,I),this.size+=M.size==G?0:1,this}ur.prototype.clear=cv,ur.prototype.delete=lv,ur.prototype.get=hv,ur.prototype.has=uv,ur.prototype.set=dv;function $a(y){var I=-1,M=y==null?0:y.length;for(this.__data__=new ur;++I<M;)this.add(y[I])}function pv(y){return this.__data__.set(y,i),this}function gv(y){return this.__data__.has(y)}$a.prototype.add=$a.prototype.push=pv,$a.prototype.has=gv;function ki(y){var I=this.__data__=new yi(y);this.size=I.size}function fv(){this.__data__=new yi,this.size=0}function wv(y){var I=this.__data__,M=I.delete(y);return this.size=I.size,M}function yv(y){return this.__data__.get(y)}function mv(y){return this.__data__.has(y)}function bv(y,I){var M=this.__data__;if(M instanceof yi){var G=M.__data__;if(!co||G.length<t-1)return G.push([y,I]),this.size=++M.size,this;M=this.__data__=new ur(G)}return M.set(y,I),this.size=M.size,this}ki.prototype.clear=fv,ki.prototype.delete=wv,ki.prototype.get=yv,ki.prototype.has=mv,ki.prototype.set=bv;function vv(y,I){var M=xa(y),G=!M&&kv(y),Qe=!M&&!G&&fl(y),ne=!M&&!G&&!Qe&&ud(y),ot=M||G||Qe||ne,It=ot?Db(y.length,String):[],Pt=It.length;for(var st in y)ei.call(y,st)&&!(ot&&(st=="length"||Qe&&(st=="offset"||st=="parent")||ne&&(st=="buffer"||st=="byteLength"||st=="byteOffset")||$v(st,Pt)))&&It.push(st);return It}function Ma(y,I){for(var M=y.length;M--;)if(ad(y[M][0],I))return M;return-1}function Iv(y,I,M){var G=I(y);return xa(y)?G:Ob(G,M(y))}function ho(y){return y==null?y===void 0?$:m:lr&&lr in Object(y)?Tv(y):Dv(y)}function id(y){return uo(y)&&ho(y)==a}function rd(y,I,M,G,Qe){return y===I?!0:y==null||I==null||!uo(y)&&!uo(I)?y!==y&&I!==I:Ev(y,I,M,G,rd,Qe)}function Ev(y,I,M,G,Qe,ne){var ot=xa(y),It=xa(I),Pt=ot?c:ji(y),st=It?c:ji(I);Pt=Pt==a?w:Pt,st=st==a?w:st;var ds=Pt==w,Ls=st==w,Ht=Pt==st;if(Ht&&fl(y)){if(!fl(I))return!1;ot=!0,ds=!1}if(Ht&&!ds)return ne||(ne=new ki),ot||ud(y)?nd(y,I,M,G,Qe,ne):Cv(y,I,Pt,M,G,Qe,ne);if(!(M&r)){var _s=ds&&ei.call(y,"__wrapped__"),Cs=Ls&&ei.call(I,"__wrapped__");if(_s||Cs){var Ri=_s?y.value():y,mi=Cs?I.value():I;return ne||(ne=new ki),Qe(Ri,mi,M,G,ne)}}return Ht?(ne||(ne=new ki),Sv(y,I,M,G,Qe,ne)):!1}function Av(y){if(!hd(y)||Ov(y))return!1;var I=cd(y)?Bb:me;return I.test(dr(y))}function Nv(y){return uo(y)&&ld(y.length)&&!!ee[ho(y)]}function _v(y){if(!xv(y))return Vb(y);var I=[];for(var M in Object(y))ei.call(y,M)&&M!="constructor"&&I.push(M);return I}function nd(y,I,M,G,Qe,ne){var ot=M&r,It=y.length,Pt=I.length;if(It!=Pt&&!(ot&&Pt>It))return!1;var st=ne.get(y);if(st&&ne.get(I))return st==I;var ds=-1,Ls=!0,Ht=M&n?new $a:void 0;for(ne.set(y,I),ne.set(I,y);++ds<It;){var _s=y[ds],Cs=I[ds];if(G)var Ri=ot?G(Cs,_s,ds,I,y,ne):G(_s,Cs,ds,y,I,ne);if(Ri!==void 0){if(Ri)continue;Ls=!1;break}if(Ht){if(!xb(I,function(mi,pr){if(!jb(Ht,pr)&&(_s===mi||Qe(_s,mi,M,G,ne)))return Ht.push(pr)})){Ls=!1;break}}else if(!(_s===Cs||Qe(_s,Cs,M,G,ne))){Ls=!1;break}}return ne.delete(y),ne.delete(I),Ls}function Cv(y,I,M,G,Qe,ne,ot){switch(M){case K:if(y.byteLength!=I.byteLength||y.byteOffset!=I.byteOffset)return!1;y=y.buffer,I=I.buffer;case k:return!(y.byteLength!=I.byteLength||!ne(new Xu(y),new Xu(I)));case h:case u:case b:return ad(+y,+I);case d:return y.name==I.name&&y.message==I.message;case _:case P:return y==I+"";case f:var It=Ub;case S:var Pt=G&r;if(It||(It=zb),y.size!=I.size&&!Pt)return!1;var st=ot.get(y);if(st)return st==I;G|=n,ot.set(y,I);var ds=nd(It(y),It(I),G,Qe,ne,ot);return ot.delete(y),ds;case x:if(gl)return gl.call(y)==gl.call(I)}return!1}function Sv(y,I,M,G,Qe,ne){var ot=M&r,It=od(y),Pt=It.length,st=od(I),ds=st.length;if(Pt!=ds&&!ot)return!1;for(var Ls=Pt;Ls--;){var Ht=It[Ls];if(!(ot?Ht in I:ei.call(I,Ht)))return!1}var _s=ne.get(y);if(_s&&ne.get(I))return _s==I;var Cs=!0;ne.set(y,I),ne.set(I,y);for(var Ri=ot;++Ls<Pt;){Ht=It[Ls];var mi=y[Ht],pr=I[Ht];if(G)var dd=ot?G(pr,mi,Ht,I,y,ne):G(mi,pr,Ht,y,I,ne);if(!(dd===void 0?mi===pr||Qe(mi,pr,M,G,ne):dd)){Cs=!1;break}Ri||(Ri=Ht=="constructor")}if(Cs&&!Ri){var Da=y.constructor,ka=I.constructor;Da!=ka&&"constructor"in y&&"constructor"in I&&!(typeof Da=="function"&&Da instanceof Da&&typeof ka=="function"&&ka instanceof ka)&&(Cs=!1)}return ne.delete(y),ne.delete(I),Cs}function od(y){return Iv(y,Uv,Pv)}function Oa(y,I){var M=y.__data__;return Mv(I)?M[typeof I=="string"?"string":"hash"]:M.map}function Wr(y,I){var M=Rb(y,I);return Av(M)?M:void 0}function Tv(y){var I=ei.call(y,lr),M=y[lr];try{y[lr]=void 0;var G=!0}catch{}var Qe=Zu.call(y);return G&&(I?y[lr]=M:delete y[lr]),Qe}var Pv=td?function(y){return y==null?[]:(y=Object(y),ao(td(y),function(I){return ed.call(y,I)}))}:Lv,ji=ho;(hl&&ji(new hl(new ArrayBuffer(1)))!=K||co&&ji(new co)!=f||ul&&ji(ul.resolve())!=E||dl&&ji(new dl)!=S||pl&&ji(new pl)!=F)&&(ji=function(y){var I=ho(y),M=I==w?y.constructor:void 0,G=M?dr(M):"";if(G)switch(G){case Kb:return K;case Gb:return f;case Yb:return E;case Qb:return S;case Zb:return F}return I});function $v(y,I){return I=I??o,!!I&&(typeof y=="number"||ue.test(y))&&y>-1&&y%1==0&&y<I}function Mv(y){var I=typeof y;return I=="string"||I=="number"||I=="symbol"||I=="boolean"?y!=="__proto__":y===null}function Ov(y){return!!Qu&&Qu in y}function xv(y){var I=y&&y.constructor,M=typeof I=="function"&&I.prototype||Ta;return y===M}function Dv(y){return Zu.call(y)}function dr(y){if(y!=null){try{return Yu.call(y)}catch{}try{return y+""}catch{}}return""}function ad(y,I){return y===I||y!==y&&I!==I}var kv=id(function(){return arguments}())?id:function(y){return uo(y)&&ei.call(y,"callee")&&!ed.call(y,"callee")},xa=Array.isArray;function jv(y){return y!=null&&ld(y.length)&&!cd(y)}var fl=Wb||zv;function Rv(y,I){return rd(y,I)}function cd(y){if(!hd(y))return!1;var I=ho(y);return I==g||I==p||I==l||I==A}function ld(y){return typeof y=="number"&&y>-1&&y%1==0&&y<=o}function hd(y){var I=typeof y;return y!=null&&(I=="object"||I=="function")}function uo(y){return y!=null&&typeof y=="object"}var ud=Xs?kb(Xs):Nv;function Uv(y){return jv(y)?vv(y):_v(y)}function Lv(){return[]}function zv(){return!1}s.exports=Rv})($c,$c.exports);var TA=$c.exports;const PA=Wv(TA),wy="wc",yy=2,Nh="core",pi=`${wy}@2:${Nh}:`,$A={logger:"error"},MA={database:":memory:"},OA="crypto",gp="client_ed25519_seed",xA=N.ONE_DAY,DA="keychain",kA="0.3",jA="messages",RA="0.3",fp=N.SIX_HOURS,UA="publisher",my="irn",LA="error",by="wss://relay.walletconnect.org",zA="relayer",St={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"},FA="_subscription",Ss={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},qA=.1,_h="2.19.0",Je={link_mode:"link_mode",relay:"relay"},BA="0.3",HA="WALLETCONNECT_CLIENT_ID",wp="WALLETCONNECT_LINK_MODE_APPS",ws={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},WA="subscription",VA="0.3",KA=N.FIVE_SECONDS*1e3,GA="pairing",YA="0.3",vo={wc_pairingDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:N.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:N.ONE_DAY,prompt:!1,tag:0},res:{ttl:N.ONE_DAY,prompt:!1,tag:0}}},Er={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Fs={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},QA="history",ZA="0.3",JA="expirer",Ms={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},XA="0.3",eN="verify-api",tN="https://verify.walletconnect.com",vy="https://verify.walletconnect.org",Ho=vy,sN=`${Ho}/v3`,iN=[tN,vy],rN="echo",nN="https://echo.walletconnect.com",li={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"},_i={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"},qs={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"},gr={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"},fr={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"},Io={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"},oN=.1,aN="event-client",cN=86400,lN="https://pulse.walletconnect.org/batch";function hN(s,e){if(s.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var r=0;r<s.length;r++){var n=s.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=s.length,c=s.charAt(0),l=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var f=0,b=0,m=0,w=p.length;m!==w&&p[m]===0;)m++,f++;for(var E=(w-m)*h+1>>>0,A=new Uint8Array(E);m!==w;){for(var _=p[m],S=0,P=E-1;(_!==0||S<b)&&P!==-1;P--,S++)_+=256*A[P]>>>0,A[P]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");b=S,m++}for(var x=E-b;x!==E&&A[x]===0;)x++;for(var $=c.repeat(f);x<E;++x)$+=s.charAt(A[x]);return $}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var f=0;if(p[f]!==" "){for(var b=0,m=0;p[f]===c;)b++,f++;for(var w=(p.length-f)*l+1>>>0,E=new Uint8Array(w);p[f];){var A=t[p.charCodeAt(f)];if(A===255)return;for(var _=0,S=w-1;(A!==0||_<m)&&S!==-1;S--,_++)A+=a*E[S]>>>0,E[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");m=_,f++}if(p[f]!==" "){for(var P=w-m;P!==w&&E[P]===0;)P++;for(var x=new Uint8Array(b+(w-P)),$=b;P!==w;)x[$++]=E[P++];return x}}}function g(p){var f=d(p);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:g}}var uN=hN,dN=uN;const Iy=s=>{if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);throw new Error("Unknown type, must be binary type")},pN=s=>new TextEncoder().encode(s),gN=s=>new TextDecoder().decode(s);let fN=class{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},wN=class{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ey(this,e)}},yN=class{constructor(e){this.decoders=e}or(e){return Ey(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Ey=(s,e)=>new yN({...s.decoders||{[s.prefix]:s},...e.decoders||{[e.prefix]:e}});let mN=class{constructor(e,t,i,r){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=r,this.encoder=new fN(e,t,i),this.decoder=new wN(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Yc=({name:s,prefix:e,encode:t,decode:i})=>new mN(s,e,t,i),ba=({prefix:s,name:e,alphabet:t})=>{const{encode:i,decode:r}=dN(t,e);return Yc({prefix:s,name:e,encode:i,decode:n=>Iy(r(n))})},bN=(s,e,t,i)=>{const r={};for(let h=0;h<e.length;++h)r[e[h]]=h;let n=s.length;for(;s[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,l=0;for(let h=0;h<n;++h){const u=r[s[h]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},vN=(s,e,t)=>{const i=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<s.length;++c)for(a=a<<8|s[c],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},qt=({name:s,prefix:e,bitsPerChar:t,alphabet:i})=>Yc({prefix:e,name:s,encode(r){return vN(r,i,t)},decode(r){return bN(r,i,t,s)}}),IN=Yc({prefix:"\0",name:"identity",encode:s=>gN(s),decode:s=>pN(s)});var EN=Object.freeze({__proto__:null,identity:IN});const AN=qt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var NN=Object.freeze({__proto__:null,base2:AN});const _N=qt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var CN=Object.freeze({__proto__:null,base8:_N});const SN=ba({prefix:"9",name:"base10",alphabet:"0123456789"});var TN=Object.freeze({__proto__:null,base10:SN});const PN=qt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$N=qt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var MN=Object.freeze({__proto__:null,base16:PN,base16upper:$N});const ON=qt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xN=qt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),DN=qt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),kN=qt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jN=qt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),RN=qt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),UN=qt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),LN=qt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),zN=qt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var FN=Object.freeze({__proto__:null,base32:ON,base32upper:xN,base32pad:DN,base32padupper:kN,base32hex:jN,base32hexupper:RN,base32hexpad:UN,base32hexpadupper:LN,base32z:zN});const qN=ba({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),BN=ba({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var HN=Object.freeze({__proto__:null,base36:qN,base36upper:BN});const WN=ba({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),VN=ba({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var KN=Object.freeze({__proto__:null,base58btc:WN,base58flickr:VN});const GN=qt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),YN=qt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),QN=qt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ZN=qt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var JN=Object.freeze({__proto__:null,base64:GN,base64pad:YN,base64url:QN,base64urlpad:ZN});const Ay=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),XN=Ay.reduce((s,e,t)=>(s[t]=e,s),[]),e_=Ay.reduce((s,e,t)=>(s[e.codePointAt(0)]=t,s),[]);function t_(s){return s.reduce((e,t)=>(e+=XN[t],e),"")}function s_(s){const e=[];for(const t of s){const i=e_[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const i_=Yc({prefix:"🚀",name:"base256emoji",encode:t_,decode:s_});var r_=Object.freeze({__proto__:null,base256emoji:i_}),n_=Ny,yp=128,o_=-128,a_=Math.pow(2,31);function Ny(s,e,t){e=e||[],t=t||0;for(var i=t;s>=a_;)e[t++]=s&255|yp,s/=128;for(;s&o_;)e[t++]=s&255|yp,s>>>=7;return e[t]=s|0,Ny.bytes=t-i+1,e}var c_=Ch,l_=128,mp=127;function Ch(s,i){var t=0,i=i||0,r=0,n=i,o,a=s.length;do{if(n>=a)throw Ch.bytes=0,new RangeError("Could not decode varint");o=s[n++],t+=r<28?(o&mp)<<r:(o&mp)*Math.pow(2,r),r+=7}while(o>=l_);return Ch.bytes=n-i,t}var h_=Math.pow(2,7),u_=Math.pow(2,14),d_=Math.pow(2,21),p_=Math.pow(2,28),g_=Math.pow(2,35),f_=Math.pow(2,42),w_=Math.pow(2,49),y_=Math.pow(2,56),m_=Math.pow(2,63),b_=function(s){return s<h_?1:s<u_?2:s<d_?3:s<p_?4:s<g_?5:s<f_?6:s<w_?7:s<y_?8:s<m_?9:10},v_={encode:n_,decode:c_,encodingLength:b_},_y=v_;const bp=(s,e,t=0)=>(_y.encode(s,e,t),e),vp=s=>_y.encodingLength(s),Sh=(s,e)=>{const t=e.byteLength,i=vp(s),r=i+vp(t),n=new Uint8Array(r+t);return bp(s,n,0),bp(t,n,i),n.set(e,r),new I_(s,t,e,n)};let I_=class{constructor(e,t,i,r){this.code=e,this.size=t,this.digest=i,this.bytes=r}};const Cy=({name:s,code:e,encode:t})=>new E_(s,e,t);let E_=class{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Sh(this.code,t):t.then(i=>Sh(this.code,i))}else throw Error("Unknown type, must be binary type")}};const Sy=s=>async e=>new Uint8Array(await crypto.subtle.digest(s,e)),A_=Cy({name:"sha2-256",code:18,encode:Sy("SHA-256")}),N_=Cy({name:"sha2-512",code:19,encode:Sy("SHA-512")});var __=Object.freeze({__proto__:null,sha256:A_,sha512:N_});const Ty=0,C_="identity",Py=Iy,S_=s=>Sh(Ty,Py(s)),T_={code:Ty,name:C_,encode:Py,digest:S_};var P_=Object.freeze({__proto__:null,identity:T_});new TextEncoder,new TextDecoder;const Ip={...EN,...NN,...CN,...TN,...MN,...FN,...HN,...KN,...JN,...r_};({...__,...P_});function $_(s=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(s):new Uint8Array(s)}function $y(s,e,t,i){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:i}}}const Ep=$y("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),Pl=$y("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);const e=$_(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),M_={utf8:Ep,"utf-8":Ep,hex:Ip.base16,latin1:Pl,ascii:Pl,binary:Pl,...Ip};function O_(s,e="utf8"){const t=M_[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(s,"utf8"):t.decoder.decode(`${t.prefix}${s}`)}var x_=Object.defineProperty,D_=(s,e,t)=>e in s?x_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,si=(s,e,t)=>D_(s,typeof e!="symbol"?e+"":e,t);let k_=class{constructor(e,t){this.core=e,this.logger=t,si(this,"keychain",new Map),si(this,"name",DA),si(this,"version",kA),si(this,"initialized",!1),si(this,"storagePrefix",pi),si(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),si(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),si(this,"set",async(i,r)=>{this.isInitialized(),this.keychain.set(i,r),await this.persist()}),si(this,"get",i=>{this.isInitialized();const r=this.keychain.get(i);if(typeof r>"u"){const{message:n}=R("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return r}),si(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Me(t,this.name)}get context(){return Ye(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,zw(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fw(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}};var j_=Object.defineProperty,R_=(s,e,t)=>e in s?j_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ot=(s,e,t)=>R_(s,typeof e!="symbol"?e+"":e,t);let U_=class{constructor(e,t,i){this.core=e,this.logger=t,Ot(this,"name",OA),Ot(this,"keychain"),Ot(this,"randomSessionIdentifier",Ah()),Ot(this,"initialized",!1),Ot(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ot(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ot(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=Ec(r);return fw(n.publicKey)}),Ot(this,"generateKeyPair",()=>{this.isInitialized();const r=OE();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ot(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=Ec(n),a=this.randomSessionIdentifier;return await ww(a,r,xA,o)}),Ot(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=xE(a,n);return this.setSymKey(c,o)}),Ot(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||hc(r);return await this.keychain.set(o,r),o}),Ot(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ot(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ot(this,"encode",async(r,n,o)=>{this.isInitialized();const a=py(o),c=yw(n);if(np(a))return jE(c,o==null?void 0:o.encoding);if(rp(a)){const d=a.senderPublicKey,g=a.receiverPublicKey;r=await this.generateSharedKey(d,g)}const l=this.getSymKey(r),{type:h,senderPublicKey:u}=a;return DE({type:h,symKey:l,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Ot(this,"decode",async(r,n,o)=>{this.isInitialized();const a=UE(n,o);if(np(a)){const c=RE(n,o==null?void 0:o.encoding);return Ac(c)}if(rp(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=kE({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return Ac(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ot(this,"getPayloadType",(r,n=Qi)=>{const o=ia({encoded:r,encoding:n});return Or(o.type)}),Ot(this,"getPayloadSenderPublicKey",(r,n=Qi)=>{const o=ia({encoded:r,encoding:n});return o.senderPublicKey?$e(o.senderPublicKey,Yt):void 0}),this.core=e,this.logger=Me(t,this.name),this.keychain=i||new k_(this.core,this.logger)}get context(){return Ye(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(gp)}catch{e=Ah(),await this.keychain.set(gp,e)}return O_(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}};var L_=Object.defineProperty,z_=(s,e,t)=>e in s?L_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ii=(s,e,t)=>z_(s,typeof e!="symbol"?e+"":e,t);let F_=class extends $0{constructor(e,t){super(e,t),this.logger=e,this.core=t,ii(this,"messages",new Map),ii(this,"name",jA),ii(this,"version",RA),ii(this,"initialized",!1),ii(this,"storagePrefix",pi),ii(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ii(this,"set",async(i,r)=>{this.isInitialized();const n=Pi(r);let o=this.messages.get(i);return typeof o>"u"&&(o={}),typeof o[n]<"u"||(o[n]=r,this.messages.set(i,o),await this.persist()),n}),ii(this,"get",i=>{this.isInitialized();let r=this.messages.get(i);return typeof r>"u"&&(r={}),r}),ii(this,"has",(i,r)=>{this.isInitialized();const n=this.get(i),o=Pi(r);return typeof n[o]<"u"}),ii(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()}),this.logger=Me(e,this.name),this.core=t}get context(){return Ye(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,zw(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fw(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}};var q_=Object.defineProperty,B_=Object.defineProperties,H_=Object.getOwnPropertyDescriptors,Ap=Object.getOwnPropertySymbols,W_=Object.prototype.hasOwnProperty,V_=Object.prototype.propertyIsEnumerable,Th=(s,e,t)=>e in s?q_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ba=(s,e)=>{for(var t in e||(e={}))W_.call(e,t)&&Th(s,t,e[t]);if(Ap)for(var t of Ap(e))V_.call(e,t)&&Th(s,t,e[t]);return s},$l=(s,e)=>B_(s,H_(e)),Bs=(s,e,t)=>Th(s,typeof e!="symbol"?e+"":e,t);let K_=class extends M0{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Bs(this,"events",new us.EventEmitter),Bs(this,"name",UA),Bs(this,"queue",new Map),Bs(this,"publishTimeout",N.toMiliseconds(N.ONE_MINUTE)),Bs(this,"initialPublishTimeout",N.toMiliseconds(N.ONE_SECOND*15)),Bs(this,"needsTransportRestart",!1),Bs(this,"publish",async(i,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:r,opts:n}});const a=(n==null?void 0:n.ttl)||fp,c=Tc(n),l=(n==null?void 0:n.prompt)||!1,h=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||Ds().toString(),d={topic:i,message:r,opts:{ttl:a,relay:c,prompt:l,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},g=`Failed to publish payload, please try again. id:${u} tag:${h}`;try{const p=new Promise(async f=>{const b=({id:w})=>{d.opts.id===w&&(this.removeRequestFromQueue(w),this.relayer.events.removeListener(St.publish,b),f(d))};this.relayer.events.on(St.publish,b);const m=Yi(new Promise((w,E)=>{this.rpcPublish({topic:i,message:r,ttl:a,prompt:l,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(w).catch(A=>{this.logger.warn(A,A==null?void 0:A.message),E(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${h}`);try{await m,this.events.removeListener(St.publish,b)}catch(w){this.queue.set(u,$l(Ba({},d),{attempt:1})),this.logger.warn(w,w==null?void 0:w.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:i,message:r,opts:n}}),await Yi(p,this.publishTimeout,g)}catch(p){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(p),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw p}finally{this.queue.delete(u)}}),Bs(this,"on",(i,r)=>{this.events.on(i,r)}),Bs(this,"once",(i,r)=>{this.events.once(i,r)}),Bs(this,"off",(i,r)=>{this.events.off(i,r)}),Bs(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.relayer=e,this.logger=Me(t,this.name),this.registerEventListeners()}get context(){return Ye(this.logger)}async rpcPublish(e){var t,i,r,n;const{topic:o,message:a,ttl:c=fp,prompt:l,tag:h,id:u,attestation:d,tvf:g}=e,p={method:jo(Tc().protocol).publish,params:Ba({topic:o,message:a,ttl:c,prompt:l,tag:h,attestation:d},g),id:u};Xt((t=p.params)==null?void 0:t.prompt)&&((i=p.params)==null||delete i.prompt),Xt((r=p.params)==null?void 0:r.tag)&&((n=p.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:p});const f=await this.relayer.request(p);return this.relayer.events.emit(St.publish,e),this.logger.debug("Successfully Published Payload"),f}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,$l(Ba({},e),{attempt:i}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish($l(Ba({},e),{topic:r,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(fi.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(St.connection_stalled);return}this.checkQueue()}),this.relayer.on(St.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}};var G_=Object.defineProperty,Y_=(s,e,t)=>e in s?G_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Yr=(s,e,t)=>Y_(s,typeof e!="symbol"?e+"":e,t);let Q_=class{constructor(){Yr(this,"map",new Map),Yr(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),Yr(this,"get",e=>this.map.get(e)||[]),Yr(this,"exists",(e,t)=>this.get(e).includes(t)),Yr(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const r=i.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),Yr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}};var Z_=Object.defineProperty,J_=Object.defineProperties,X_=Object.getOwnPropertyDescriptors,Np=Object.getOwnPropertySymbols,eC=Object.prototype.hasOwnProperty,tC=Object.prototype.propertyIsEnumerable,Ph=(s,e,t)=>e in s?Z_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Eo=(s,e)=>{for(var t in e||(e={}))eC.call(e,t)&&Ph(s,t,e[t]);if(Np)for(var t of Np(e))tC.call(e,t)&&Ph(s,t,e[t]);return s},Ml=(s,e)=>J_(s,X_(e)),je=(s,e,t)=>Ph(s,typeof e!="symbol"?e+"":e,t);let sC=class extends D0{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,je(this,"subscriptions",new Map),je(this,"topicMap",new Q_),je(this,"events",new us.EventEmitter),je(this,"name",WA),je(this,"version",VA),je(this,"pending",new Map),je(this,"cached",[]),je(this,"initialized",!1),je(this,"pendingSubscriptionWatchLabel","pending_sub_watch_label"),je(this,"pollingInterval",20),je(this,"storagePrefix",pi),je(this,"subscribeTimeout",N.toMiliseconds(N.ONE_MINUTE)),je(this,"initialSubscribeTimeout",N.toMiliseconds(N.ONE_SECOND*15)),je(this,"clientId"),je(this,"batchSubscribeTopicsLimit",500),je(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),je(this,"subscribe",async(i,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}});try{const n=Tc(r),o={topic:i,relay:n,transportType:r==null?void 0:r.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,r);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),je(this,"unsubscribe",async(i,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(i,r.id,r):await this.unsubscribeByTopic(i,r)}),je(this,"isSubscribed",async i=>{if(this.topics.includes(i))return!0;const r=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((n,o)=>{const a=new N.Watch;a.start(r);const c=setInterval(()=>{(!this.pending.has(i)&&this.topics.includes(i)||this.cached.some(l=>l.topic===i))&&(clearInterval(c),a.stop(r),n(!0)),a.elapsed(r)>=KA&&(clearInterval(c),a.stop(r),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)}),je(this,"on",(i,r)=>{this.events.on(i,r)}),je(this,"once",(i,r)=>{this.events.once(i,r)}),je(this,"off",(i,r)=>{this.events.off(i,r)}),je(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),je(this,"start",async()=>{await this.onConnect()}),je(this,"stop",async()=>{await this.onDisconnect()}),je(this,"restart",async()=>{await this.restore(),await this.onRestart()}),je(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(r=>{i.push(r)}),await this.batchSubscribe(i)}),je(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(fi.pulse,async()=>{await this.checkPending()}),this.events.on(ws.created,async i=>{const r=ws.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()}),this.events.on(ws.deleted,async i=>{const r=ws.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()})}),this.relayer=e,this.logger=Me(t,this.name),this.clientId=""}get context(){return Ye(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const r=Tc(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Re("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,i){var r;(!i||(i==null?void 0:i.transportType)===Je.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:jo(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=i==null?void 0:i.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===Je.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(h=>this.logger.warn(h))},N.toMiliseconds(N.ONE_SECOND)),a;const c=new Promise(async h=>{const u=d=>{d.topic===e&&(this.events.removeListener(ws.created,u),h(d.id))};this.events.on(ws.created,u);try{const d=await Yi(new Promise((g,p)=>{this.relayer.request(n).catch(f=>{this.logger.warn(f,f==null?void 0:f.message),p(f)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(ws.created,u),h(d)}catch{}}),l=await Yi(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(St.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:jo(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Yi(new Promise(r=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(St.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:jo(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let r;try{r=await await Yi(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(St.connection_stalled)}return r}rpcUnsubscribe(e,t,i){const r={method:jo(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,Ml(Eo({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Eo({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,Eo({},t)),this.topicMap.set(t.topic,e),this.events.emit(ws.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(ws.deleted,Ml(Eo({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ws.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(ws.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async t=>Ml(Eo({},t),{id:await this.getSubscriptionId(t.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await VI(N.toMiliseconds(N.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=R("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 Pi(e+await this.getClientId())}};var iC=Object.defineProperty,_p=Object.getOwnPropertySymbols,rC=Object.prototype.hasOwnProperty,nC=Object.prototype.propertyIsEnumerable,$h=(s,e,t)=>e in s?iC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Cp=(s,e)=>{for(var t in e||(e={}))rC.call(e,t)&&$h(s,t,e[t]);if(_p)for(var t of _p(e))nC.call(e,t)&&$h(s,t,e[t]);return s},Ie=(s,e,t)=>$h(s,typeof e!="symbol"?e+"":e,t);let oC=class extends O0{constructor(e){super(e),Ie(this,"protocol","wc"),Ie(this,"version",2),Ie(this,"core"),Ie(this,"logger"),Ie(this,"events",new us.EventEmitter),Ie(this,"provider"),Ie(this,"messages"),Ie(this,"subscriber"),Ie(this,"publisher"),Ie(this,"name",zA),Ie(this,"transportExplicitlyClosed",!1),Ie(this,"initialized",!1),Ie(this,"connectionAttemptInProgress",!1),Ie(this,"relayUrl"),Ie(this,"projectId"),Ie(this,"packageName"),Ie(this,"bundleId"),Ie(this,"hasExperiencedNetworkDisruption",!1),Ie(this,"pingTimeout"),Ie(this,"heartBeatTimeout",N.toMiliseconds(N.THIRTY_SECONDS+N.FIVE_SECONDS)),Ie(this,"reconnectTimeout"),Ie(this,"connectPromise"),Ie(this,"reconnectInProgress",!1),Ie(this,"requestsInFlight",[]),Ie(this,"connectTimeout",N.toMiliseconds(N.ONE_SECOND*15)),Ie(this,"request",async t=>{var i,r;this.logger.debug("Publishing Request Payload");const n=t.id||Ds().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((r=t.params)==null?void 0:r.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),Ie(this,"resetPingTimeout",()=>{if(Cc())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,r;this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(r=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null||r.terminate()},this.heartBeatTimeout)}catch(t){this.logger.warn(t,t==null?void 0:t.message)}}),Ie(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),Ie(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(St.connect)}),Ie(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ie(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(St.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ie(this,"registerProviderListeners",()=>{this.provider.on(Ss.payload,this.onPayloadHandler),this.provider.on(Ss.connect,this.onConnectHandler),this.provider.on(Ss.disconnect,this.onDisconnectHandler),this.provider.on(Ss.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Me(e.logger,this.name):Zn(Di({level:e.logger||LA})),this.messages=new F_(this.logger,e.core),this.subscriber=new sC(this,this.logger),this.publisher=new K_(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||by,this.projectId=e.projectId,MI()?this.packageName=Md():OI()&&(this.bundleId=Md()),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 Ye(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Je.relay})}async subscribe(e,t){var i,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=t==null?void 0:t.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(r=t==null?void 0:t.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=h=>{h.topic===e&&(this.subscriber.off(ws.created,l),c())};return await Promise.all([new Promise(h=>{c=h,this.subscriber.on(ws.created,l)}),new Promise(async(h,u)=>{a=await this.subscriber.subscribe(e,Cp({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&u(d)})||a,h()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Yi(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,i)=>{await this.connect(e).then(t).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await pp())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,r)=>i.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+(r==null?void 0:r.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const r=mt(N.FIVE_MINUTES),n={topic:i,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(St.message,e),await this.recordMessageEvent(e)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ss.disconnect,n),await Yi(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off(Ss.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(Ss.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Ss.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const r=i;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(i=>setTimeout(i,N.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,r,n;if(Cc())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(i=this.provider)==null?void 0:i.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new tt(new gw(jI({sdkVersion:_h,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.warn(`Ignoring message for non-subscribed topic ${t}`),!0;const r=this.messages.has(t,i);return r&&this.logger.warn(`Ignoring duplicate message: ${i}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Jn(e)){if(!e.method.endsWith(FA))return;const t=e.params,{topic:i,message:r,publishedAt:n,attestation:o}=t.data,a={topic:i,message:r,publishedAt:n,transportType:Je.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Cp({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Xn(e)&&this.events.emit(St.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(St.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=nr(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Ss.payload,this.onPayloadHandler),this.provider.off(Ss.connect,this.onConnectHandler),this.provider.off(Ss.disconnect,this.onDisconnectHandler),this.provider.off(Ss.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await pp();_A(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(St.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},N.toMiliseconds(qA)))))}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}};var aC=Object.defineProperty,Sp=Object.getOwnPropertySymbols,cC=Object.prototype.hasOwnProperty,lC=Object.prototype.propertyIsEnumerable,Mh=(s,e,t)=>e in s?aC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Tp=(s,e)=>{for(var t in e||(e={}))cC.call(e,t)&&Mh(s,t,e[t]);if(Sp)for(var t of Sp(e))lC.call(e,t)&&Mh(s,t,e[t]);return s},es=(s,e,t)=>Mh(s,typeof e!="symbol"?e+"":e,t);let Lr=class extends x0{constructor(e,t,i,r=pi,n=void 0){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,es(this,"map",new Map),es(this,"version",BA),es(this,"cached",[]),es(this,"initialized",!1),es(this,"getKey"),es(this,"storagePrefix",pi),es(this,"recentlyDeleted",[]),es(this,"recentlyDeletedLimit",200),es(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Xt(o)?this.map.set(this.getKey(o),o):sA(o)?this.map.set(o.id,o):iA(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),es(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())}),es(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),es(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>PA(a[c],o[c]))):this.values)),es(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=Tp(Tp({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),es(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=Me(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return Ye(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=R("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:i}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}};var hC=Object.defineProperty,uC=(s,e,t)=>e in s?hC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,pe=(s,e,t)=>uC(s,typeof e!="symbol"?e+"":e,t);let dC=class{constructor(e,t){this.core=e,this.logger=t,pe(this,"name",GA),pe(this,"version",YA),pe(this,"events",new Qn),pe(this,"pairings"),pe(this,"initialized",!1),pe(this,"storagePrefix",pi),pe(this,"ignoredPayloadTypes",[Mi]),pe(this,"registeredMethods",[]),pe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),pe(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),pe(this,"create",async i=>{this.isInitialized();const r=Ah(),n=await this.core.crypto.setSymKey(r),o=mt(N.FIVE_MINUTES),a={protocol:my},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},l=ap({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(Er.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:l}}),pe(this,"pair",async i=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[li.pairing_started]}});this.isValidPair(i,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=op(i.uri);r.props.properties.topic=n,r.addTrace(li.pairing_uri_validation_success),r.addTrace(li.pairing_uri_not_expired);let h;if(this.pairings.keys.includes(n)){if(h=this.pairings.get(n),r.addTrace(li.existing_pairing),h.active)throw r.setError(_i.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(li.pairing_not_expired)}const u=c||mt(N.FIVE_MINUTES),d={topic:n,relay:a,expiry:u,active:!1,methods:l};this.core.expirer.set(n,u),await this.pairings.set(n,d),r.addTrace(li.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(Er.create,d),r.addTrace(li.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(li.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(_i.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(g){throw r.setError(_i.subscribe_pairing_topic_failure),g}return r.addTrace(li.subscribe_pairing_topic_success),d}),pe(this,"activate",async({topic:i})=>{this.isInitialized();const r=mt(N.FIVE_MINUTES);this.core.expirer.set(i,r),await this.pairings.update(i,{active:!0,expiry:r})}),pe(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=i;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=mr();this.events.once(Te("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),pe(this,"updateExpiry",async({topic:i,expiry:r})=>{this.isInitialized(),await this.pairings.update(i,{expiry:r})}),pe(this,"updateMetadata",async({topic:i,metadata:r})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:r})}),pe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),pe(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:r}=i;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Re("USER_DISCONNECTED")),await this.deletePairing(r))}),pe(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(r);return ap({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),pe(this,"sendRequest",async(i,r,n)=>{const o=cs(r,n),a=await this.core.crypto.encode(i,o),c=vo[r].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),pe(this,"sendResult",async(i,r,n)=>{const o=nr(i,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,i)).request.method,l=vo[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),pe(this,"sendError",async(i,r,n)=>{const o=Bc(i,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,i)).request.method,l=vo[c]?vo[c].res:vo.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),pe(this,"deletePairing",async(i,r)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Re("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),r?Promise.resolve():this.core.expirer.del(i)])}),pe(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(r=>Wi(r.expiry));await Promise.all(i.map(r=>this.deletePairing(r.topic)))}),pe(this,"onRelayEventRequest",i=>{const{topic:r,payload:n}=i;switch(n.method){case"wc_pairingPing":return this.onPairingPingRequest(r,n);case"wc_pairingDelete":return this.onPairingDeleteRequest(r,n);default:return this.onUnknownRpcMethodRequest(r,n)}}),pe(this,"onRelayEventResponse",async i=>{const{topic:r,payload:n}=i,o=(await this.core.history.get(r,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,n);default:return this.onUnknownRpcMethodResponse(o)}}),pe(this,"onPairingPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(Er.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),pe(this,"onPairingPingResponse",(i,r)=>{const{id:n}=r;setTimeout(()=>{Ct(r)?this.events.emit(Te("pairing_ping",n),{}):gt(r)&&this.events.emit(Te("pairing_ping",n),{error:r.error})},500)}),pe(this,"onPairingDeleteRequest",async(i,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Er.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),pe(this,"onUnknownRpcMethodRequest",async(i,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Re("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),pe(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(Re("WC_METHOD_UNSUPPORTED",i))}),pe(this,"isValidPair",(i,r)=>{var n;if(!ns(i)){const{message:a}=R("MISSING_OR_INVALID",`pair() params: ${i}`);throw r.setError(_i.malformed_pairing_uri),new Error(a)}if(!tA(i.uri)){const{message:a}=R("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw r.setError(_i.malformed_pairing_uri),new Error(a)}const o=op(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=R("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(_i.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=R("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(_i.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&N.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(_i.pairing_expired);const{message:a}=R("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),pe(this,"isValidPing",async i=>{if(!ns(i)){const{message:n}=R("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),pe(this,"isValidDisconnect",async i=>{if(!ns(i)){const{message:n}=R("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),pe(this,"isValidPairingTopic",async i=>{if(!ht(i,!1)){const{message:r}=R("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(r)}if(!this.pairings.keys.includes(i)){const{message:r}=R("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(r)}if(Wi(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:r}=R("EXPIRED",`pairing topic: ${i}`);throw new Error(r)}}),this.core=e,this.logger=Me(t,this.name),this.pairings=new Lr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ye(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(St.message,async e=>{const{topic:t,message:i,transportType:r}=e;if(!this.pairings.keys.includes(t)||r===Je.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const n=await this.core.crypto.decode(t,i);try{Jn(n)?(this.core.history.set(t,n),this.onRelayEventRequest({topic:t,payload:n})):Xn(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(Ms.expired,async e=>{const{topic:t}=Bw(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Er.expire,{topic:t}))})}};var pC=Object.defineProperty,gC=(s,e,t)=>e in s?pC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,xt=(s,e,t)=>gC(s,typeof e!="symbol"?e+"":e,t);let fC=class extends P0{constructor(e,t){super(e,t),this.core=e,this.logger=t,xt(this,"records",new Map),xt(this,"events",new us.EventEmitter),xt(this,"name",QA),xt(this,"version",ZA),xt(this,"cached",[]),xt(this,"initialized",!1),xt(this,"storagePrefix",pi),xt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),xt(this,"set",(i,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:i,request:{method:r.method,params:r.params||null},chainId:n,expiry:mt(N.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Fs.created,o)}),xt(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const r=await this.getRecord(i.id);typeof r.response>"u"&&(r.response=gt(i)?{error:i.error}:{result:i.result},this.records.set(r.id,r),this.persist(),this.events.emit(Fs.updated,r))}),xt(this,"get",async(i,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:r}),await this.getRecord(r))),xt(this,"delete",(i,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===i){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(Fs.deleted,n)}}),this.persist()}),xt(this,"exists",async(i,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===i:!1)),xt(this,"on",(i,r)=>{this.events.on(i,r)}),xt(this,"once",(i,r)=>{this.events.once(i,r)}),xt(this,"off",(i,r)=>{this.events.off(i,r)}),xt(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=Me(t,this.name)}get context(){return Ye(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:cs(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Fs.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Fs.created,e=>{const t=Fs.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Fs.updated,e=>{const t=Fs.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Fs.deleted,e=>{const t=Fs.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(fi.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{N.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Fs.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}};var wC=Object.defineProperty,yC=(s,e,t)=>e in s?wC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Wt=(s,e,t)=>yC(s,typeof e!="symbol"?e+"":e,t);let mC=class extends k0{constructor(e,t){super(e,t),this.core=e,this.logger=t,Wt(this,"expirations",new Map),Wt(this,"events",new us.EventEmitter),Wt(this,"name",JA),Wt(this,"version",XA),Wt(this,"cached",[]),Wt(this,"initialized",!1),Wt(this,"storagePrefix",pi),Wt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Wt(this,"has",i=>{try{const r=this.formatTarget(i);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Wt(this,"set",(i,r)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(Ms.created,{target:n,expiration:o})}),Wt(this,"get",i=>{this.isInitialized();const r=this.formatTarget(i);return this.getExpiration(r)}),Wt(this,"del",i=>{if(this.isInitialized(),this.has(i)){const r=this.formatTarget(i),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Ms.deleted,{target:r,expiration:n})}}),Wt(this,"on",(i,r)=>{this.events.on(i,r)}),Wt(this,"once",(i,r)=>{this.events.once(i,r)}),Wt(this,"off",(i,r)=>{this.events.off(i,r)}),Wt(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=Me(t,this.name)}get context(){return Ye(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 RI(e);if(typeof e=="number")return UI(e);const{message:t}=R("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Ms.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:i}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;N.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Ms.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(fi.pulse,()=>this.checkExpirations()),this.events.on(Ms.created,e=>{const t=Ms.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Ms.expired,e=>{const t=Ms.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Ms.deleted,e=>{const t=Ms.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}};var bC=Object.defineProperty,vC=(s,e,t)=>e in s?bC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ut=(s,e,t)=>vC(s,typeof e!="symbol"?e+"":e,t);let IC=class extends j0{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,ut(this,"name",eN),ut(this,"abortController"),ut(this,"isDevEnv"),ut(this,"verifyUrlV3",sN),ut(this,"storagePrefix",pi),ut(this,"version",yy),ut(this,"publicKey"),ut(this,"fetchPromise"),ut(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&N.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ut(this,"register",async r=>{if(!ga()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=rr(),h=this.startAbortTimer(N.ONE_SECOND*5),u=await new Promise((d,g)=>{const p=()=>{window.removeEventListener("message",b),l.body.removeChild(f),g("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const f=l.createElement("iframe");f.src=c,f.style.display="none",f.addEventListener("error",p,{signal:this.abortController.signal});const b=m=>{if(m.data&&typeof m.data=="string")try{const w=JSON.parse(m.data);if(w.type==="verify_attestation"){if(Bn(w.attestation).payload.id!==o)return;clearInterval(h),l.body.removeChild(f),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",b),d(w.attestation===null?"":w.attestation)}}catch(w){this.logger.warn(w)}};l.body.appendChild(f),window.addEventListener("message",b,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(l){this.logger.warn(l)}return""}),ut(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(Bn(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(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),ut(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(N.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ut(this,"getVerifyUrl",r=>{let n=r||Ho;return iN.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Ho}`),n=Ho),n}),ut(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(N.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),ut(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),ut(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ut(this,"isValidJwtAttestation",async r=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(r,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ut(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ut(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),ut(this,"validateAttestation",(r,n)=>{const o=qE(r,n.publicKey),a={hasExpired:N.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Me(t,this.name),this.abortController=new AbortController,this.isDevEnv=bu(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ye(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),N.toMiliseconds(e))}};var EC=Object.defineProperty,AC=(s,e,t)=>e in s?EC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Pp=(s,e,t)=>AC(s,typeof e!="symbol"?e+"":e,t);let NC=class extends R0{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Pp(this,"context",rN),Pp(this,"registerDeviceToken",async i=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${nN}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=Me(t,this.context)}};var _C=Object.defineProperty,$p=Object.getOwnPropertySymbols,CC=Object.prototype.hasOwnProperty,SC=Object.prototype.propertyIsEnumerable,Oh=(s,e,t)=>e in s?_C(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ao=(s,e)=>{for(var t in e||(e={}))CC.call(e,t)&&Oh(s,t,e[t]);if($p)for(var t of $p(e))SC.call(e,t)&&Oh(s,t,e[t]);return s},Et=(s,e,t)=>Oh(s,typeof e!="symbol"?e+"":e,t);let TC=class extends U0{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,Et(this,"context",aN),Et(this,"storagePrefix",pi),Et(this,"storageVersion",oN),Et(this,"events",new Map),Et(this,"shouldPersist",!1),Et(this,"init",async()=>{if(!bu())try{const r={eventId:xd(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Lw(this.core.relayer.protocol,this.core.relayer.version,_h)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),Et(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=xd(),h=this.core.projectId||"",u=Date.now(),d=Ao({eventId:l,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:h,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,d),this.shouldPersist=!0),d}),Et(this,"getEvent",r=>{const{eventId:n,topic:o}=r;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Ao(Ao({},a),this.setMethods(a.eventId))}),Et(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),Et(this,"setEventListeners",()=>{this.core.heartbeat.on(fi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{N.fromMiliseconds(Date.now())-N.fromMiliseconds(r.timestamp)>cN&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),Et(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),Et(this,"addTrace",(r,n)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(n),this.events.set(r,o),this.shouldPersist=!0)}),Et(this,"setError",(r,n)=>{const o=this.events.get(r);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),Et(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Et(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(n=>{this.events.set(n.eventId,Ao(Ao({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),Et(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[n,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const n of r)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),Et(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${lN}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${_h}${n}`,{method:"POST",body:JSON.stringify(r)})}),Et(this,"getAppDomain",()=>Uw().url),this.logger=Me(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}};var PC=Object.defineProperty,Mp=Object.getOwnPropertySymbols,$C=Object.prototype.hasOwnProperty,MC=Object.prototype.propertyIsEnumerable,xh=(s,e,t)=>e in s?PC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Op=(s,e)=>{for(var t in e||(e={}))$C.call(e,t)&&xh(s,t,e[t]);if(Mp)for(var t of Mp(e))MC.call(e,t)&&xh(s,t,e[t]);return s},qe=(s,e,t)=>xh(s,typeof e!="symbol"?e+"":e,t);let OC=class My extends _0{constructor(e){var t;super(e),qe(this,"protocol",wy),qe(this,"version",yy),qe(this,"name",Nh),qe(this,"relayUrl"),qe(this,"projectId"),qe(this,"customStoragePrefix"),qe(this,"events",new us.EventEmitter),qe(this,"logger"),qe(this,"heartbeat"),qe(this,"relayer"),qe(this,"crypto"),qe(this,"storage"),qe(this,"history"),qe(this,"expirer"),qe(this,"pairing"),qe(this,"verify"),qe(this,"echoClient"),qe(this,"linkModeSupportedApps"),qe(this,"eventClient"),qe(this,"initialized",!1),qe(this,"logChunkController"),qe(this,"on",(o,a)=>this.events.on(o,a)),qe(this,"once",(o,a)=>this.events.once(o,a)),qe(this,"off",(o,a)=>this.events.off(o,a)),qe(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),qe(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:c})=>{if(!o||!a)return;const l={topic:o,message:a,publishedAt:Date.now(),transportType:Je.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:c})}),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||by,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Di({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:$A.logger,name:Nh}),{logger:r,chunkLoggerController:n}=yu({opts:i,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=n,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,a;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((a=this.logChunkController)==null||a.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Me(r,this.name),this.heartbeat=new dw,this.crypto=new U_(this,this.logger,e==null?void 0:e.keychain),this.history=new fC(this,this.logger),this.expirer=new mC(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new pw(Op(Op({},MA),e==null?void 0:e.storageOptions)),this.relayer=new oC({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new dC(this,this.logger),this.verify=new IC(this,this.logger,this.storage),this.echoClient=new NC(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new TC(this,this.logger,e==null?void 0:e.telemetryEnabled)}static async init(e){const t=new My(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(HA,i),t}get context(){return Ye(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(wp,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(wp)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}};const xC=OC;var DC=Object.defineProperty,kC=(s,e,t)=>e in s?DC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,xp=(s,e,t)=>kC(s,typeof e!="symbol"?e+"":e,t);let jC=class{constructor(e){this.opts=e,xp(this,"protocol","wc"),xp(this,"version",2)}},RC=class{constructor(e){this.client=e}};const Oy="wc",xy=2,Dy="client",Tu=`${Oy}@${xy}:${Dy}:`,Ol={name:Dy,logger:"error"},Dp="WALLETCONNECT_DEEPLINK_CHOICE",UC="proposal",kp="Proposal expired",LC="session",Qr=N.SEVEN_DAYS,zC="engine",At={wc_sessionPropose:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1104},res:{ttl:N.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1106},res:{ttl:N.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1112},res:{ttl:N.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1114},res:{ttl:N.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:N.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:N.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1119}}},xl={min:N.FIVE_MINUTES,max:N.SEVEN_DAYS},ri={idle:"IDLE",active:"ACTIVE"},jp={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},FC="request",qC=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],BC="wc",HC="auth",WC="authKeys",VC="pairingTopics",KC="requests",Qc=`${BC}@${1.5}:${HC}:`,uc=`${Qc}:PUB_KEY`;var GC=Object.defineProperty,YC=Object.defineProperties,QC=Object.getOwnPropertyDescriptors,Rp=Object.getOwnPropertySymbols,ZC=Object.prototype.hasOwnProperty,JC=Object.prototype.propertyIsEnumerable,Dh=(s,e,t)=>e in s?GC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,it=(s,e)=>{for(var t in e||(e={}))ZC.call(e,t)&&Dh(s,t,e[t]);if(Rp)for(var t of Rp(e))JC.call(e,t)&&Dh(s,t,e[t]);return s},ts=(s,e)=>YC(s,QC(e)),D=(s,e,t)=>Dh(s,typeof e!="symbol"?e+"":e,t);let XC=class extends RC{constructor(e){super(e),D(this,"name",zC),D(this,"events",new Qn),D(this,"initialized",!1),D(this,"requestQueue",{state:ri.idle,queue:[]}),D(this,"sessionRequestQueue",{state:ri.idle,queue:[]}),D(this,"requestQueueDelay",N.ONE_SECOND),D(this,"expectedPairingMethodMap",new Map),D(this,"recentlyDeletedMap",new Map),D(this,"recentlyDeletedLimit",200),D(this,"relayMessageCache",[]),D(this,"pendingSessions",new Map),D(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(At)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay)))}),D(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=ts(it({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,relays:c}=i;let l=r,h,u=!1;try{if(l){const _=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),u=_.active}}catch(_){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),_}if(!l||!u){const{topic:_,uri:S}=await this.client.core.pairing.create();l=_,h=S}if(!l){const{message:_}=R("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(_)}const d=await this.client.core.crypto.generateKeyPair(),g=At.wc_sessionPropose.req.ttl||N.FIVE_MINUTES,p=mt(g),f=ts(it({requiredNamespaces:n,optionalNamespaces:o,relays:c??[{protocol:my}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:p,pairingTopic:l},a&&{sessionProperties:a}),{id:Gt()}),b=Te("session_connect",f.id),{reject:m,resolve:w,done:E}=mr(g,kp),A=({id:_})=>{_===f.id&&(this.client.events.off("proposal_expire",A),this.pendingSessions.delete(f.id),this.events.emit(b,{error:{message:kp,code:0}}))};return this.client.events.on("proposal_expire",A),this.events.once(b,({error:_,session:S})=>{this.client.events.off("proposal_expire",A),_?m(_):S&&w(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:h,approval:E}}),D(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}}),D(this,"approve",async t=>{var i,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=t==null?void 0:t.id)==null?void 0:i.toString(),trace:[qs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(x){throw o.setError(gr.no_internet_connection),x}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(x){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(gr.proposal_not_found),x}try{await this.isValidApprove(t)}catch(x){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(gr.session_approve_namespace_validation_failure),x}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:h,sessionConfig:u}=t,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:p,requiredNamespaces:f,optionalNamespaces:b}=d;let m=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});m||(m=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:qs.session_approve_started,properties:{topic:g,trace:[qs.session_approve_started,qs.session_namespaces_validation_success]}}));const w=await this.client.core.crypto.generateKeyPair(),E=p.publicKey,A=await this.client.core.crypto.generateSharedKey(w,E),_=it(it({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:w,metadata:this.client.metadata},expiry:mt(Qr)},h&&{sessionProperties:h}),u&&{sessionConfig:u}),S=Je.relay;m.addTrace(qs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(A,{transportType:S})}catch(x){throw m.setError(gr.subscribe_session_topic_failure),x}m.addTrace(qs.subscribe_session_topic_success);const P=ts(it({},_),{topic:A,requiredNamespaces:f,optionalNamespaces:b,pairingTopic:g,acknowledged:!1,self:_.controller,peer:{publicKey:p.publicKey,metadata:p.metadata},controller:w,transportType:Je.relay});await this.client.session.set(A,P),m.addTrace(qs.store_session);try{m.addTrace(qs.publishing_session_settle),await this.sendRequest({topic:A,method:"wc_sessionSettle",params:_,throwOnFailedPublish:!0}).catch(x=>{throw m==null||m.setError(gr.session_settle_publish_failure),x}),m.addTrace(qs.session_settle_publish_success),m.addTrace(qs.publishing_session_approve),await this.sendResult({id:a,topic:g,result:{relay:{protocol:c??"irn"},responderPublicKey:w},throwOnFailedPublish:!0}).catch(x=>{throw m==null||m.setError(gr.session_approve_publish_failure),x}),m.addTrace(qs.session_approve_publish_success)}catch(x){throw this.client.logger.error(x),this.client.session.delete(A,Re("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(A),x}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:p.metadata}),await this.client.proposal.delete(a,Re("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(A,mt(Qr)),{topic:A,acknowledged:()=>Promise.resolve(this.client.session.get(A))}}),D(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:r}=t;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&(await this.sendError({id:i,topic:n,error:r,rpcOpts:At.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Re("USER_DISCONNECTED")))}),D(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:i,namespaces:r}=t,{done:n,resolve:o,reject:a}=mr(),c=Gt(),l=Ds().toString(),h=this.client.session.get(i).namespaces;return this.events.once(Te("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(i,{namespaces:r}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(u=>{this.client.logger.error(u),this.client.session.update(i,{namespaces:h}),a(u)}),{acknowledged:n}}),D(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=t,r=Gt(),{done:n,resolve:o,reject:a}=mr();return this.events.once(Te("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,mt(Qr)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),D(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:i,request:r,topic:n,expiry:o=At.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===Je.relay&&await this.confirmOnlineStateOrThrow();const c=Gt(),l=Ds().toString(),{done:h,resolve:u,reject:d}=mr(o,"Request expired. Please try again.");this.events.once(Te("session_request",c),({error:m,result:w})=>{m?d(m):u(w)});const g="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:g,params:{request:ts(it({},r),{expiryTimestamp:mt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),await h();const f={request:ts(it({},r),{expiryTimestamp:mt(o)}),chainId:i},b=this.shouldSetTVF(g,f);return await Promise.all([new Promise(async m=>{await this.sendRequest(it({clientRpcId:c,relayRpcId:l,topic:n,method:g,params:f,expiry:o,throwOnFailedPublish:!0},b&&{tvf:this.getTVFParams(c,f)})).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),m()}),new Promise(async m=>{var w;if(!((w=a.sessionConfig)!=null&&w.disableDeepLink)){const E=await qI(this.client.core.storage,Dp);await LI({id:c,topic:n,wcDeepLink:E})}m()}),h()]).then(m=>m[2])}),D(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:r}=t,{id:n}=r,o=this.client.session.get(i);o.transportType===Je.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Ct(r)?await this.sendResult({id:n,topic:i,result:r.result,throwOnFailedPublish:!0,appLink:a}):gt(r)&&await this.sendError({id:n,topic:i,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),D(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:i}=t;if(this.client.session.keys.includes(i)){const r=Gt(),n=Ds().toString(),{done:o,resolve:a,reject:c}=mr();this.events.once(Te("session_ping",r),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),D(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:r,chainId:n}=t,o=Ds().toString(),a=Gt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),D(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Re("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:r}=R("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(r)}}),D(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(i=>XE(i,t)))),D(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),D(this,"authenticate",async(t,i)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?Je.link_mode:Je.relay;o===Je.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:h,nonce:u,type:d,exp:g,nbf:p,methods:f=[],expiry:b}=t,m=[...t.resources||[]],{topic:w,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:w,uri:E}});const A=await this.client.core.crypto.generateKeyPair(),_=hc(A);if(await Promise.all([this.client.auth.authKeys.set(uc,{responseTopic:_,publicKey:A}),this.client.auth.pairingTopics.set(_,{topic:_,pairingTopic:w})]),await this.client.core.relayer.subscribe(_,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${w}`),f.length>0){const{namespace:C}=zn(a[0]);let L=O1(C,"request",f);lc(m)&&(L=D1(L,m.pop())),m.push(L)}const S=b&&b>At.wc_sessionAuthenticate.req.ttl?b:At.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:d??"caip122",chains:a,statement:c,aud:l,domain:h,version:"1",nonce:u,iat:new Date().toISOString(),exp:g,nbf:p,resources:m},requester:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:mt(S)},x={eip155:{chains:a,methods:[...new Set(["personal_sign",...f])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:x,relays:[{protocol:"irn"}],pairingTopic:w,proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:mt(At.wc_sessionPropose.req.ttl),id:Gt()},{done:F,resolve:k,reject:K}=mr(S,"Request expired"),q=Gt(),H=Te("session_connect",$.id),W=Te("session_request",q),B=async({error:C,session:L})=>{this.events.off(W,V),C?K(C):L&&k({session:L})},V=async C=>{var L,X,Q;if(await this.deletePendingAuthRequest(q,{message:"fulfilled",code:0}),C.error){const ke=Re("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return C.error.code===ke.code?void 0:(this.events.off(H,B),K(C.error.message))}await this.deleteProposal($.id),this.events.off(H,B);const{cacaos:me,responder:ue}=C.result,ee=[],nt=[];for(const ke of me){await Fd({cacao:ke,projectId:this.client.core.projectId})||(this.client.logger.error(ke,"Signature verification failed"),K(Re("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Zs}=ke,Js=lc(Zs.resources),wi=[yh(Zs.iss)],Hr=Sc(Zs.iss);if(Js){const Xs=qd(Js),ao=Bd(Js);ee.push(...Xs),wi.push(...ao)}for(const Xs of wi)nt.push(`${Xs}:${Hr}`)}const Le=await this.client.core.crypto.generateSharedKey(A,ue.publicKey);let be;ee.length>0&&(be={topic:Le,acknowledged:!0,self:{publicKey:A,metadata:this.client.metadata},peer:ue,controller:ue.publicKey,expiry:mt(Qr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:w,namespaces:cp([...new Set(ee)],[...new Set(nt)]),transportType:o},await this.client.core.relayer.subscribe(Le,{transportType:o}),await this.client.session.set(Le,be),w&&await this.client.core.pairing.updateMetadata({topic:w,metadata:ue.metadata}),be=this.client.session.get(Le)),(L=this.client.metadata.redirect)!=null&&L.linkMode&&(X=ue.metadata.redirect)!=null&&X.linkMode&&(Q=ue.metadata.redirect)!=null&&Q.universal&&i&&(this.client.core.addLinkModeSupportedApp(ue.metadata.redirect.universal),this.client.session.update(Le,{transportType:Je.link_mode})),k({auths:me,session:be})};this.events.once(H,B),this.events.once(W,V);let Y;try{if(n){const C=cs("wc_sessionAuthenticate",P,q);this.client.core.history.set(w,C);const L=await this.client.core.crypto.encode("",C,{type:ma,encoding:mo});Y=qa(i,w,L)}else await Promise.all([this.sendRequest({topic:w,method:"wc_sessionAuthenticate",params:P,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:q}),this.sendRequest({topic:w,method:"wc_sessionPropose",params:$,expiry:At.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(C){throw this.events.off(H,B),this.events.off(W,V),C}return await this.setProposal($.id,$),await this.setAuthRequest(q,{request:ts(it({},P),{verifyContext:{}}),pairingTopic:w,transportType:o}),{uri:Y??E,response:F}}),D(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[fr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(b){throw n.setError(Io.no_internet_connection),b}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(Io.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Je.relay;a===Je.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),h=hc(c),u={type:Mi,receiverPublicKey:c,senderPublicKey:l},d=[],g=[];for(const b of r){if(!await Fd({cacao:b,projectId:this.client.core.projectId})){n.setError(Io.invalid_cacao);const _=Re("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:h,error:_,encodeOpts:u}),new Error(_.message)}n.addTrace(fr.cacaos_verified);const{p:m}=b,w=lc(m.resources),E=[yh(m.iss)],A=Sc(m.iss);if(w){const _=qd(w),S=Bd(w);d.push(..._),E.push(...S)}for(const _ of E)g.push(`${_}:${A}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(fr.create_authenticated_session_topic);let f;if((d==null?void 0:d.length)>0){f={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:mt(Qr),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:cp([...new Set(d)],[...new Set(g)]),transportType:a},n.addTrace(fr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(b){throw n.setError(Io.subscribe_authenticated_session_topic_failure),b}n.addTrace(fr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,f),n.addTrace(fr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(fr.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:i,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(b){throw n.setError(Io.authenticated_session_approve_publish_failure),b}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:f}}),D(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:i,reason:r}=t,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===Je.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=hc(o),l={type:Mi,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:r,encodeOpts:l,rpcOpts:At.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Re("USER_DISCONNECTED"))}),D(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:r}=t;return Jw(i,r)}),D(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),D(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===t.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),D(this,"deleteSession",async t=>{var i;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Re("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Dp).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===r&&this.deletePendingSessionRequest(l.id,Re("USER_DISCONNECTED"))}),r===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=ri.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),D(this,"deleteProposal",async(t,i)=>{if(i)try{const r=this.client.proposal.get(t),n=this.client.core.eventClient.getEvent({topic:r.pairingTopic});n==null||n.setError(gr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Re("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),D(this,"deletePendingSessionRequest",async(t,i,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==t),r&&(this.sessionRequestQueue.state=ri.idle,this.client.events.emit("session_request_expire",{id:t}))}),D(this,"deletePendingAuthRequest",async(t,i,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)])}),D(this,"setExpiry",async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))}),D(this,"setProposal",async(t,i)=>{this.client.core.expirer.set(t,mt(At.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),D(this,"setAuthRequest",async(t,i)=>{const{request:r,pairingTopic:n,transportType:o=Je.relay}=i;this.client.core.expirer.set(t,r.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:t,pairingTopic:n,verifyContext:r.verifyContext,transportType:o})}),D(this,"setPendingSessionRequest",async t=>{const{id:i,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||mt(At.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:r,params:n,verifyContext:o})}),D(this,"sendRequest",async t=>{const{topic:i,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:h,tvf:u}=t,d=cs(r,n,c);let g;const p=!!h;try{const m=p?mo:Qi;g=await this.client.core.crypto.encode(i,d,{encoding:m})}catch(m){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),m}let f;if(qC.includes(r)){const m=Pi(JSON.stringify(d)),w=Pi(g);f=await this.client.core.verify.register({id:w,decryptedId:m})}const b=At[r].req;if(b.attestation=f,o&&(b.ttl=o),a&&(b.id=a),this.client.core.history.set(i,d),p){const m=qa(h,i,g);await T.global.Linking.openURL(m,this.client.name)}else{const m=At[r].req;o&&(m.ttl=o),a&&(m.id=a),m.tvf=ts(it({},u),{correlationId:d.id}),l?(m.internal=ts(it({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,g,m)):this.client.core.relayer.publish(i,g,m).catch(w=>this.client.logger.error(w))}return d.id}),D(this,"sendResult",async t=>{const{id:i,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,l=nr(i,n);let h;const u=c&&typeof(T.global==null?void 0:T.global.Linking)<"u";try{const p=u?mo:Qi;h=await this.client.core.crypto.encode(r,l,ts(it({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),p}let d,g;try{d=await this.client.core.history.get(r,i);const p=d.request;try{this.shouldSetTVF(p.method,p.params)&&(g=this.getTVFParams(i,p.params,n))}catch(f){this.client.logger.warn("sendResult() -> getTVFParams() failed",f)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${i}) failed`),p}if(u){const p=qa(c,r,h);await T.global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,f=At[p].res;f.tvf=ts(it({},g),{correlationId:i}),o?(f.internal=ts(it({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,h,f)):this.client.core.relayer.publish(r,h,f).catch(b=>this.client.logger.error(b))}await this.client.core.history.resolve(l)}),D(this,"sendError",async t=>{const{id:i,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,l=Bc(i,n);let h;const u=c&&typeof(T.global==null?void 0:T.global.Linking)<"u";try{const g=u?mo:Qi;h=await this.client.core.crypto.encode(r,l,ts(it({},o||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),g}let d;try{d=await this.client.core.history.get(r,i)}catch(g){throw this.client.logger.error(`sendError() -> history.get(${r}, ${i}) failed`),g}if(u){const g=qa(c,r,h);await T.global.Linking.openURL(g,this.client.name)}else{const g=d.request.method,p=a||At[g].res;this.client.core.relayer.publish(r,h,p)}await this.client.core.history.resolve(l)}),D(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(r=>{let n=!1;Wi(r.expiry)&&(n=!0),this.client.core.crypto.keychain.has(r.topic)||(n=!0),n&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{Wi(r.expiryTimestamp)&&i.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...i.map(r=>this.deleteProposal(r))])}),D(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),D(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===ri.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=ri.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=ri.idle}),D(this,"processRequest",async t=>{const{topic:i,payload:r,attestation:n,transportType:o,encryptedId:a}=t,c=r.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,r);case"wc_sessionPing":return await this.onSessionPingRequest(i,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),D(this,"onRelayEventResponse",async t=>{const{topic:i,payload:r,transportType:n}=t,o=(await this.client.core.history.get(i,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,r);case"wc_sessionExtend":return this.onSessionExtendResponse(i,r);case"wc_sessionPing":return this.onSessionPingResponse(i,r);case"wc_sessionRequest":return this.onSessionRequestResponse(i,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),D(this,"onRelayEventUnknownPayload",t=>{const{topic:i}=t,{message:r}=R("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),D(this,"shouldIgnorePairingRequest",t=>{const{topic:i,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),D(this,"onSessionProposeRequest",async t=>{const{topic:i,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:c}=r;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(_i.proposal_listener_not_found)),this.isValidConnect(it({},r.params));const h=a.expiryTimestamp||mt(At.wc_sessionPropose.req.ttl),u=it({id:c,pairingTopic:i,expiryTimestamp:h},a);await this.setProposal(c,u);const d=await this.getVerifyContext({attestationId:n,hash:Pi(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});l==null||l.addTrace(li.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:d})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:At.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),D(this,"onSessionProposeResponse",async(t,i,r)=>{const{id:n}=i;if(Ct(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const 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 h=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(n,{sessionTopic:h,pairingTopic:t,proposalId:n,publicKey:c});const u=await this.client.core.relayer.subscribe(h,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(gt(i)){await this.client.proposal.delete(n,Re("USER_DISCONNECTED"));const o=Te("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),D(this,"onSessionSettleRequest",async(t,i)=>{const{id:r,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:h,sessionConfig:u}=i.params,d=[...this.pendingSessions.values()].find(f=>f.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const g=this.client.proposal.get(d.proposalId),p=ts(it(it({topic:t,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},h&&{sessionProperties:h}),u&&{sessionConfig:u}),{transportType:Je.relay});await this.client.session.set(p.topic,p),await this.setExpiry(p.topic,p.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:p.peer.metadata}),this.client.events.emit("session_connect",{session:p}),this.events.emit(Te("session_connect",d.proposalId),{session:p}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(p),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),D(this,"onSessionSettleResponse",async(t,i)=>{const{id:r}=i;Ct(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Te("session_approve",r),{})):gt(i)&&(await this.client.session.delete(t,Re("USER_DISCONNECTED")),this.events.emit(Te("session_approve",r),{error:i.error}))}),D(this,"onSessionUpdateRequest",async(t,i)=>{const{params:r,id:n}=i;try{const o=`${t}_session_update`,a=bo.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:t,error:Re("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(it({topic:t},r));try{bo.set(o,n),await this.client.session.update(t,{namespaces:r.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(c){throw bo.delete(o),c}this.client.events.emit("session_update",{id:n,topic:t,params:r})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}}),D(this,"isRequestOutOfSync",(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3)),D(this,"onSessionUpdateResponse",(t,i)=>{const{id:r}=i,n=Te("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Ct(i)?this.events.emit(Te("session_update",r),{}):gt(i)&&this.events.emit(Te("session_update",r),{error:i.error})}),D(this,"onSessionExtendRequest",async(t,i)=>{const{id:r}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,mt(Qr)),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),D(this,"onSessionExtendResponse",(t,i)=>{const{id:r}=i,n=Te("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Ct(i)?this.events.emit(Te("session_extend",r),{}):gt(i)&&this.events.emit(Te("session_extend",r),{error:i.error})}),D(this,"onSessionPingRequest",async(t,i)=>{const{id:r}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),D(this,"onSessionPingResponse",(t,i)=>{const{id:r}=i,n=Te("session_ping",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);setTimeout(()=>{Ct(i)?this.events.emit(Te("session_ping",r),{}):gt(i)&&this.events.emit(Te("session_ping",r),{error:i.error})},500)}),D(this,"onSessionDeleteRequest",async(t,i)=>{const{id:r}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(St.publish,async()=>{n(await this.deleteSession({topic:t,id:r}))})}),this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Re("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),D(this,"onSessionRequest",async t=>{var i,r,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:h}=t,{id:u,params:d}=a;try{await this.isValidRequest(it({topic:o},d));const g=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Pi(JSON.stringify(cs("wc_sessionRequest",d,u))),encryptedId:l,metadata:g.peer.metadata,transportType:h}),f={id:u,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(f),h===Je.link_mode&&(i=g.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((r=g.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(g){await this.sendError({id:u,topic:o,error:g}),this.client.logger.error(g)}}),D(this,"onSessionRequestResponse",(t,i)=>{const{id:r}=i,n=Te("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Ct(i)?this.events.emit(Te("session_request",r),{result:i.result}):gt(i)&&this.events.emit(Te("session_request",r),{error:i.error})}),D(this,"onSessionEventRequest",async(t,i)=>{const{id:r,params:n}=i;try{const o=`${t}_session_event_${n.event.name}`,a=bo.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(it({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),bo.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),D(this,"onSessionAuthenticateResponse",(t,i)=>{const{id:r}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),Ct(i)?this.events.emit(Te("session_request",r),{result:i.result}):gt(i)&&this.events.emit(Te("session_request",r),{error:i.error})}),D(this,"onSessionAuthenticateRequest",async t=>{var i;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:l,authPayload:h,expiryTimestamp:u}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Pi(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),g={requester:l,pairingTopic:r,id:n.id,authPayload:h,verifyContext:d,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:g,pairingTopic:r,transportType:c}),c===Je.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:d})}catch(l){this.client.logger.error(l);const h=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),g={type:Mi,receiverPublicKey:h,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:l,encodeOpts:g,rpcOpts:At.wc_sessionAuthenticate.autoReject,appLink:d})}}),D(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),D(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ri.idle,this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay))}),D(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:i})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=Te("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Te("session_request",n.request.id),{error:i})})}),D(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===ri.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=ri.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}}),D(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),D(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:cs("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})}),D(this,"isValidConnect",async t=>{if(!ns(t)){const{message:c}=R("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(c)}const{pairingTopic:i,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,relays:a}=t;if(Xt(i)||await this.isValidPairingTopic(i),!uA(a)){const{message:c}=R("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!Xt(r)&&ra(r)!==0&&this.validateNamespaces(r,"requiredNamespaces"),!Xt(n)&&ra(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Xt(o)||this.validateSessionProps(o,"sessionProperties")}),D(this,"validateNamespaces",(t,i)=>{const r=hA(t,"connect()",i);if(r)throw new Error(r.message)}),D(this,"isValidApprove",async t=>{if(!ns(t))throw new Error(R("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:r,relayProtocol:n,sessionProperties:o}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const a=this.client.proposal.get(i),c=Sl(r,"approve()");if(c)throw new Error(c.message);const l=up(a.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!ht(n,!0)){const{message:h}=R("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}Xt(o)||this.validateSessionProps(o,"sessionProperties")}),D(this,"isValidReject",async t=>{if(!ns(t)){const{message:n}=R("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:r}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!pA(r)){const{message:n}=R("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),D(this,"isValidSessionSettleRequest",t=>{if(!ns(t)){const{message:l}=R("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(l)}const{relay:i,controller:r,namespaces:n,expiry:o}=t;if(!fy(i)){const{message:l}=R("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=rA(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Sl(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Wi(o)){const{message:l}=R("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),D(this,"isValidUpdate",async t=>{if(!ns(t)){const{message:c}=R("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:i,namespaces:r}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=Sl(r,"update()");if(o)throw new Error(o.message);const a=up(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),D(this,"isValidExtend",async t=>{if(!ns(t)){const{message:r}=R("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),D(this,"isValidRequest",async t=>{if(!ns(t)){const{message:c}=R("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:i,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!hp(a,n)){const{message:c}=R("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!gA(r)){const{message:c}=R("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!yA(a,n,r.method)){const{message:c}=R("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!IA(o,xl)){const{message:c}=R("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${xl.min} and ${xl.max}`);throw new Error(c)}}),D(this,"isValidRespond",async t=>{var i;if(!ns(t)){const{message:o}=R("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(i=t==null?void 0:t.response)!=null&&i.id&&this.cleanupAfterResponse(t),o}if(!fA(n)){const{message:o}=R("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),D(this,"isValidPing",async t=>{if(!ns(t)){const{message:r}=R("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),D(this,"isValidEmit",async t=>{if(!ns(t)){const{message:a}=R("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:i,event:r,chainId:n}=t;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!hp(o,n)){const{message:a}=R("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!wA(r)){const{message:a}=R("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!mA(o,n,r.name)){const{message:a}=R("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),D(this,"isValidDisconnect",async t=>{if(!ns(t)){const{message:r}=R("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),D(this,"isValidAuthenticate",t=>{const{chains:i,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!ht(r,!1))throw new Error("uri is required parameter");if(!ht(n,!1))throw new Error("domain is required parameter");if(!ht(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>zn(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=zn(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),D(this,"getVerifyContext",async t=>{const{attestationId:i,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||Ho,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Je.link_mode){const h=this.getAppLinkIfEnabled(o,a);return c.verified.validation=h&&new URL(h).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:i,hash:r,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}),D(this,"validateSessionProps",(t,i)=>{Object.values(t).forEach(r=>{if(!ht(r,!1)){const{message:n}=R("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(r)}`);throw new Error(n)}})}),D(this,"getPendingAuthRequest",t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0}),D(this,"addToRecentlyDeleted",(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=n)break;this.recentlyDeletedMap.delete(o)}}}),D(this,"checkRecentlyDeleted",t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:r}=R("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(r)}}),D(this,"isLinkModeEnabled",(t,i)=>{var r,n,o,a,c,l,h,u,d;return!t||i!==Je.link_mode?!1:((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((h=t==null?void 0:t.redirect)==null?void 0:h.universal)!==void 0&&((u=t==null?void 0:t.redirect)==null?void 0:u.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(T.global==null?void 0:T.global.Linking)<"u"}),D(this,"getAppLinkIfEnabled",(t,i)=>{var r;return this.isLinkModeEnabled(t,i)?(r=t==null?void 0:t.redirect)==null?void 0:r.universal:void 0}),D(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Od(t,"topic")||"",r=decodeURIComponent(Od(t,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:Je.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:r,sessionExists:n})}),D(this,"registerLinkModeListeners",async()=>{var t;if(bu()||ar()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=T.global==null?void 0:T.global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await i.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),D(this,"shouldSetTVF",(t,i)=>{if(!i||t!=="wc_sessionRequest")return!1;const{request:r}=i;return Object.keys(jp).includes(r.method)}),D(this,"getTVFParams",(t,i,r)=>{var n,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,r);return ts(it({correlationId:t,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),D(this,"isValidContractData",t=>{var i;if(!t)return!1;try{const r=(t==null?void 0:t.data)||((i=t==null?void 0:t[0])==null?void 0:i.data);if(!r.startsWith("0x"))return!1;const n=r.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),D(this,"extractTxHashesFromResult",(t,i)=>{try{const r=jp[t];if(typeof i=="string")return[i];const n=i[r.key];if(xr(n))return n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(St.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(uc)?this.client.auth.authKeys.get(uc):{publicKey:void 0},a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===Je.link_mode?mo:Qi});try{Jn(a)?(this.client.core.history.set(t,a),this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:Pi(i)})):Xn(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n})}catch(c){this.client.logger.error(c)}}registerExpirerEvents(){this.client.core.expirer.on(Ms.expired,async e=>{const{topic:t,id:i}=Bw(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,R("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,R("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Er.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Er.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ht(e,!1)){const{message:t}=R("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=R("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Wi(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=R("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ht(e,!1)){const{message:t}=R("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=R("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Wi(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=R("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=R("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ht(e,!1)){const{message:t}=R("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=R("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!dA(e)){const{message:t}=R("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=R("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Wi(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=R("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}},eS=class extends Lr{constructor(e,t){super(e,t,UC,Tu),this.core=e,this.logger=t}},tS=class extends Lr{constructor(e,t){super(e,t,LC,Tu),this.core=e,this.logger=t}},sS=class extends Lr{constructor(e,t){super(e,t,FC,Tu,i=>i.id),this.core=e,this.logger=t}},iS=class extends Lr{constructor(e,t){super(e,t,WC,Qc,()=>uc),this.core=e,this.logger=t}},rS=class extends Lr{constructor(e,t){super(e,t,VC,Qc),this.core=e,this.logger=t}},nS=class extends Lr{constructor(e,t){super(e,t,KC,Qc,i=>i.id),this.core=e,this.logger=t}};var oS=Object.defineProperty,aS=(s,e,t)=>e in s?oS(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Dl=(s,e,t)=>aS(s,typeof e!="symbol"?e+"":e,t);let cS=class{constructor(e,t){this.core=e,this.logger=t,Dl(this,"authKeys"),Dl(this,"pairingTopics"),Dl(this,"requests"),this.authKeys=new iS(this.core,this.logger),this.pairingTopics=new rS(this.core,this.logger),this.requests=new nS(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}};var lS=Object.defineProperty,hS=(s,e,t)=>e in s?lS(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ge=(s,e,t)=>hS(s,typeof e!="symbol"?e+"":e,t);let uS=class ky extends jC{constructor(e){super(e),ge(this,"protocol",Oy),ge(this,"version",xy),ge(this,"name",Ol.name),ge(this,"metadata"),ge(this,"core"),ge(this,"logger"),ge(this,"events",new us.EventEmitter),ge(this,"engine"),ge(this,"session"),ge(this,"proposal"),ge(this,"pendingRequest"),ge(this,"auth"),ge(this,"signConfig"),ge(this,"on",(i,r)=>this.events.on(i,r)),ge(this,"once",(i,r)=>this.events.once(i,r)),ge(this,"off",(i,r)=>this.events.off(i,r)),ge(this,"removeListener",(i,r)=>this.events.removeListener(i,r)),ge(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),ge(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"update",async i=>{try{return await this.engine.update(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"request",async i=>{try{return await this.engine.request(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"find",i=>{try{return this.engine.find(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),ge(this,"authenticate",async(i,r)=>{try{return await this.engine.authenticate(i,r)}catch(n){throw this.logger.error(n.message),n}}),ge(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||Ol.name,this.metadata=(e==null?void 0:e.metadata)||Uw(),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Zn(Di({level:(e==null?void 0:e.logger)||Ol.logger}));this.core=(e==null?void 0:e.core)||new xC(e),this.logger=Me(t,this.name),this.session=new tS(this.core,this.logger),this.proposal=new eS(this.core,this.logger),this.pendingRequest=new sS(this.core,this.logger),this.engine=new XC(this),this.auth=new cS(this.core,this.logger)}static async init(e){const t=new ky(e);return await t.initialize(),t}get context(){return Ye(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},N.toMiliseconds(N.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Up="error",dS="wss://relay.walletconnect.org",pS="wc",gS="universal_provider",Lp=`${pS}@2:${gS}:`,jy="https://rpc.walletconnect.org/v1/",Cn="generic",fS=`${jy}bundler`,Rs={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Ha=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof T.global<"u"?T.global:typeof self<"u"?self:{};function wS(){this.__data__=[],this.size=0}var yS=wS;function mS(s,e){return s===e||s!==s&&e!==e}var Zc=mS,bS=Zc;function vS(s,e){for(var t=s.length;t--;)if(bS(s[t][0],e))return t;return-1}var Jc=vS,IS=Jc,ES=Array.prototype,AS=ES.splice;function NS(s){var e=this.__data__,t=IS(e,s);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():AS.call(e,t,1),--this.size,!0}var _S=NS,CS=Jc;function SS(s){var e=this.__data__,t=CS(e,s);return t<0?void 0:e[t][1]}var TS=SS,PS=Jc;function $S(s){return PS(this.__data__,s)>-1}var MS=$S,OS=Jc;function xS(s,e){var t=this.__data__,i=OS(t,s);return i<0?(++this.size,t.push([s,e])):t[i][1]=e,this}var DS=xS,kS=yS,jS=_S,RS=TS,US=MS,LS=DS;function Sn(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}Sn.prototype.clear=kS,Sn.prototype.delete=jS,Sn.prototype.get=RS,Sn.prototype.has=US,Sn.prototype.set=LS;var Xc=Sn,zS=Xc;function FS(){this.__data__=new zS,this.size=0}var qS=FS;function BS(s){var e=this.__data__,t=e.delete(s);return this.size=e.size,t}var HS=BS;function WS(s){return this.__data__.get(s)}var VS=WS;function KS(s){return this.__data__.has(s)}var GS=KS,YS=typeof Ha=="object"&&Ha&&Ha.Object===Object&&Ha,Ry=YS,QS=Ry,ZS=typeof self=="object"&&self&&self.Object===Object&&self,JS=QS||ZS||Function("return this")(),io=JS,XS=io,eT=XS.Symbol,Uy=eT,zp=Uy,Ly=Object.prototype,tT=Ly.hasOwnProperty,sT=Ly.toString,No=zp?zp.toStringTag:void 0;function iT(s){var e=tT.call(s,No),t=s[No];try{s[No]=void 0;var i=!0}catch{}var r=sT.call(s);return i&&(e?s[No]=t:delete s[No]),r}var rT=iT,nT=Object.prototype,oT=nT.toString;function aT(s){return oT.call(s)}var cT=aT,Fp=Uy,lT=rT,hT=cT,uT="[object Null]",dT="[object Undefined]",qp=Fp?Fp.toStringTag:void 0;function pT(s){return s==null?s===void 0?dT:uT:qp&&qp in Object(s)?lT(s):hT(s)}var el=pT;function gT(s){var e=typeof s;return s!=null&&(e=="object"||e=="function")}var zr=gT,fT=el,wT=zr,yT="[object AsyncFunction]",mT="[object Function]",bT="[object GeneratorFunction]",vT="[object Proxy]";function IT(s){if(!wT(s))return!1;var e=fT(s);return e==mT||e==bT||e==yT||e==vT}var Pu=IT,ET=io,AT=ET["__core-js_shared__"],NT=AT,kl=NT,Bp=function(){var s=/[^.]+$/.exec(kl&&kl.keys&&kl.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function _T(s){return!!Bp&&Bp in s}var CT=_T,ST=Function.prototype,TT=ST.toString;function PT(s){if(s!=null){try{return TT.call(s)}catch{}try{return s+""}catch{}}return""}var $T=PT,MT=Pu,OT=CT,xT=zr,DT=$T,kT=/[\\^$.*+?()[\]{}|]/g,jT=/^\[object .+?Constructor\]$/,RT=Function.prototype,UT=Object.prototype,LT=RT.toString,zT=UT.hasOwnProperty,FT=RegExp("^"+LT.call(zT).replace(kT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function qT(s){if(!xT(s)||OT(s))return!1;var e=MT(s)?FT:jT;return e.test(DT(s))}var BT=qT;function HT(s,e){return s==null?void 0:s[e]}var WT=HT,VT=BT,KT=WT;function GT(s,e){var t=KT(s,e);return VT(t)?t:void 0}var $u=GT,YT=$u,QT=io,ZT=YT(QT,"Map"),zy=ZT,JT=$u,XT=JT(Object,"create"),tl=XT,Hp=tl;function eP(){this.__data__=Hp?Hp(null):{},this.size=0}var tP=eP;function sP(s){var e=this.has(s)&&delete this.__data__[s];return this.size-=e?1:0,e}var iP=sP,rP=tl,nP="__lodash_hash_undefined__",oP=Object.prototype,aP=oP.hasOwnProperty;function cP(s){var e=this.__data__;if(rP){var t=e[s];return t===nP?void 0:t}return aP.call(e,s)?e[s]:void 0}var lP=cP,hP=tl,uP=Object.prototype,dP=uP.hasOwnProperty;function pP(s){var e=this.__data__;return hP?e[s]!==void 0:dP.call(e,s)}var gP=pP,fP=tl,wP="__lodash_hash_undefined__";function yP(s,e){var t=this.__data__;return this.size+=this.has(s)?0:1,t[s]=fP&&e===void 0?wP:e,this}var mP=yP,bP=tP,vP=iP,IP=lP,EP=gP,AP=mP;function Tn(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}Tn.prototype.clear=bP,Tn.prototype.delete=vP,Tn.prototype.get=IP,Tn.prototype.has=EP,Tn.prototype.set=AP;var NP=Tn,Wp=NP,_P=Xc,CP=zy;function SP(){this.size=0,this.__data__={hash:new Wp,map:new(CP||_P),string:new Wp}}var TP=SP;function PP(s){var e=typeof s;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?s!=="__proto__":s===null}var $P=PP,MP=$P;function OP(s,e){var t=s.__data__;return MP(e)?t[typeof e=="string"?"string":"hash"]:t.map}var sl=OP,xP=sl;function DP(s){var e=xP(this,s).delete(s);return this.size-=e?1:0,e}var kP=DP,jP=sl;function RP(s){return jP(this,s).get(s)}var UP=RP,LP=sl;function zP(s){return LP(this,s).has(s)}var FP=zP,qP=sl;function BP(s,e){var t=qP(this,s),i=t.size;return t.set(s,e),this.size+=t.size==i?0:1,this}var HP=BP,WP=TP,VP=kP,KP=UP,GP=FP,YP=HP;function Pn(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}Pn.prototype.clear=WP,Pn.prototype.delete=VP,Pn.prototype.get=KP,Pn.prototype.has=GP,Pn.prototype.set=YP;var QP=Pn,ZP=Xc,JP=zy,XP=QP,e$=200;function t$(s,e){var t=this.__data__;if(t instanceof ZP){var i=t.__data__;if(!JP||i.length<e$-1)return i.push([s,e]),this.size=++t.size,this;t=this.__data__=new XP(i)}return t.set(s,e),this.size=t.size,this}var s$=t$,i$=Xc,r$=qS,n$=HS,o$=VS,a$=GS,c$=s$;function $n(s){var e=this.__data__=new i$(s);this.size=e.size}$n.prototype.clear=r$,$n.prototype.delete=n$,$n.prototype.get=o$,$n.prototype.has=a$,$n.prototype.set=c$;var l$=$n,h$=$u,u$=function(){try{var s=h$(Object,"defineProperty");return s({},"",{}),s}catch{}}(),Fy=u$,Vp=Fy;function d$(s,e,t){e=="__proto__"&&Vp?Vp(s,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):s[e]=t}var Mu=d$,p$=Mu,g$=Zc;function f$(s,e,t){(t!==void 0&&!g$(s[e],t)||t===void 0&&!(e in s))&&p$(s,e,t)}var qy=f$;function w$(s){return function(e,t,i){for(var r=-1,n=Object(e),o=i(e),a=o.length;a--;){var c=o[s?a:++r];if(t(n[c],c,n)===!1)break}return e}}var y$=w$,m$=y$,b$=m$(),v$=b$,kh={exports:{}};(function(s,e){var t=io,i=e&&!e.nodeType&&e,r=i&&!0&&s&&!s.nodeType&&s,n=r&&r.exports===i,o=n?t.Buffer:void 0,a=o?o.allocUnsafe:void 0;function c(l,h){if(h)return l.slice();var u=l.length,d=a?a(u):new l.constructor(u);return l.copy(d),d}s.exports=c})(kh,kh.exports);var I$=io,E$=I$.Uint8Array,A$=E$,Kp=A$;function N$(s){var e=new s.constructor(s.byteLength);return new Kp(e).set(new Kp(s)),e}var _$=N$,C$=_$;function S$(s,e){var t=e?C$(s.buffer):s.buffer;return new s.constructor(t,s.byteOffset,s.length)}var T$=S$;function P$(s,e){var t=-1,i=s.length;for(e||(e=Array(i));++t<i;)e[t]=s[t];return e}var $$=P$,M$=zr,Gp=Object.create,O$=function(){function s(){}return function(e){if(!M$(e))return{};if(Gp)return Gp(e);s.prototype=e;var t=new s;return s.prototype=void 0,t}}(),x$=O$;function D$(s,e){return function(t){return s(e(t))}}var k$=D$,j$=k$,R$=j$(Object.getPrototypeOf,Object),By=R$,U$=Object.prototype;function L$(s){var e=s&&s.constructor,t=typeof e=="function"&&e.prototype||U$;return s===t}var Hy=L$,z$=x$,F$=By,q$=Hy;function B$(s){return typeof s.constructor=="function"&&!q$(s)?z$(F$(s)):{}}var H$=B$;function W$(s){return s!=null&&typeof s=="object"}var va=W$,V$=el,K$=va,G$="[object Arguments]";function Y$(s){return K$(s)&&V$(s)==G$}var Q$=Y$,Yp=Q$,Z$=va,Wy=Object.prototype,J$=Wy.hasOwnProperty,X$=Wy.propertyIsEnumerable,e2=Yp(function(){return arguments}())?Yp:function(s){return Z$(s)&&J$.call(s,"callee")&&!X$.call(s,"callee")},Vy=e2,t2=Array.isArray,Ky=t2,s2=9007199254740991;function i2(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=s2}var Gy=i2,r2=Pu,n2=Gy;function o2(s){return s!=null&&n2(s.length)&&!r2(s)}var Ou=o2,a2=Ou,c2=va;function l2(s){return c2(s)&&a2(s)}var h2=l2,Mc={exports:{}};function u2(){return!1}var d2=u2;(function(s,e){var t=io,i=d2,r=e&&!e.nodeType&&e,n=r&&!0&&s&&!s.nodeType&&s,o=n&&n.exports===r,a=o?t.Buffer:void 0,c=a?a.isBuffer:void 0,l=c||i;s.exports=l})(Mc,Mc.exports);var p2=el,g2=By,f2=va,w2="[object Object]",y2=Function.prototype,m2=Object.prototype,Yy=y2.toString,b2=m2.hasOwnProperty,v2=Yy.call(Object);function I2(s){if(!f2(s)||p2(s)!=w2)return!1;var e=g2(s);if(e===null)return!0;var t=b2.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Yy.call(t)==v2}var E2=I2,A2=el,N2=Gy,_2=va,C2="[object Arguments]",S2="[object Array]",T2="[object Boolean]",P2="[object Date]",$2="[object Error]",M2="[object Function]",O2="[object Map]",x2="[object Number]",D2="[object Object]",k2="[object RegExp]",j2="[object Set]",R2="[object String]",U2="[object WeakMap]",L2="[object ArrayBuffer]",z2="[object DataView]",F2="[object Float32Array]",q2="[object Float64Array]",B2="[object Int8Array]",H2="[object Int16Array]",W2="[object Int32Array]",V2="[object Uint8Array]",K2="[object Uint8ClampedArray]",G2="[object Uint16Array]",Y2="[object Uint32Array]",Ze={};Ze[F2]=Ze[q2]=Ze[B2]=Ze[H2]=Ze[W2]=Ze[V2]=Ze[K2]=Ze[G2]=Ze[Y2]=!0,Ze[C2]=Ze[S2]=Ze[L2]=Ze[T2]=Ze[z2]=Ze[P2]=Ze[$2]=Ze[M2]=Ze[O2]=Ze[x2]=Ze[D2]=Ze[k2]=Ze[j2]=Ze[R2]=Ze[U2]=!1;function Q2(s){return _2(s)&&N2(s.length)&&!!Ze[A2(s)]}var Z2=Q2;function J2(s){return function(e){return s(e)}}var X2=J2,jh={exports:{}};(function(s,e){var t=Ry,i=e&&!e.nodeType&&e,r=i&&!0&&s&&!s.nodeType&&s,n=r&&r.exports===i,o=n&&t.process,a=function(){try{var c=r&&r.require&&r.require("util").types;return c||o&&o.binding&&o.binding("util")}catch{}}();s.exports=a})(jh,jh.exports);var eM=Z2,tM=X2,Qp=jh.exports,Zp=Qp&&Qp.isTypedArray,sM=Zp?tM(Zp):eM,Qy=sM;function iM(s,e){if(!(e==="constructor"&&typeof s[e]=="function")&&e!="__proto__")return s[e]}var Zy=iM,rM=Mu,nM=Zc,oM=Object.prototype,aM=oM.hasOwnProperty;function cM(s,e,t){var i=s[e];(!(aM.call(s,e)&&nM(i,t))||t===void 0&&!(e in s))&&rM(s,e,t)}var lM=cM,hM=lM,uM=Mu;function dM(s,e,t,i){var r=!t;t||(t={});for(var n=-1,o=e.length;++n<o;){var a=e[n],c=i?i(t[a],s[a],a,t,s):void 0;c===void 0&&(c=s[a]),r?uM(t,a,c):hM(t,a,c)}return t}var pM=dM;function gM(s,e){for(var t=-1,i=Array(s);++t<s;)i[t]=e(t);return i}var fM=gM,wM=9007199254740991,yM=/^(?:0|[1-9]\d*)$/;function mM(s,e){var t=typeof s;return e=e??wM,!!e&&(t=="number"||t!="symbol"&&yM.test(s))&&s>-1&&s%1==0&&s<e}var Jy=mM,bM=fM,vM=Vy,IM=Ky,EM=Mc.exports,AM=Jy,NM=Qy,_M=Object.prototype,CM=_M.hasOwnProperty;function SM(s,e){var t=IM(s),i=!t&&vM(s),r=!t&&!i&&EM(s),n=!t&&!i&&!r&&NM(s),o=t||i||r||n,a=o?bM(s.length,String):[],c=a.length;for(var l in s)(e||CM.call(s,l))&&!(o&&(l=="length"||r&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||AM(l,c)))&&a.push(l);return a}var TM=SM;function PM(s){var e=[];if(s!=null)for(var t in Object(s))e.push(t);return e}var $M=PM,MM=zr,OM=Hy,xM=$M,DM=Object.prototype,kM=DM.hasOwnProperty;function jM(s){if(!MM(s))return xM(s);var e=OM(s),t=[];for(var i in s)i=="constructor"&&(e||!kM.call(s,i))||t.push(i);return t}var RM=jM,UM=TM,LM=RM,zM=Ou;function FM(s){return zM(s)?UM(s,!0):LM(s)}var Xy=FM,qM=pM,BM=Xy;function HM(s){return qM(s,BM(s))}var WM=HM,Jp=qy,VM=kh.exports,KM=T$,GM=$$,YM=H$,Xp=Vy,eg=Ky,QM=h2,ZM=Mc.exports,JM=Pu,XM=zr,eO=E2,tO=Qy,tg=Zy,sO=WM;function iO(s,e,t,i,r,n,o){var a=tg(s,t),c=tg(e,t),l=o.get(c);if(l){Jp(s,t,l);return}var h=n?n(a,c,t+"",s,e,o):void 0,u=h===void 0;if(u){var d=eg(c),g=!d&&ZM(c),p=!d&&!g&&tO(c);h=c,d||g||p?eg(a)?h=a:QM(a)?h=GM(a):g?(u=!1,h=VM(c,!0)):p?(u=!1,h=KM(c,!0)):h=[]:eO(c)||Xp(c)?(h=a,Xp(a)?h=sO(a):(!XM(a)||JM(a))&&(h=YM(c))):u=!1}u&&(o.set(c,h),r(h,c,i,n,o),o.delete(c)),Jp(s,t,h)}var rO=iO,nO=l$,oO=qy,aO=v$,cO=rO,lO=zr,hO=Xy,uO=Zy;function em(s,e,t,i,r){s!==e&&aO(e,function(n,o){if(r||(r=new nO),lO(n))cO(s,e,o,t,em,i,r);else{var a=i?i(uO(s,o),n,o+"",s,e,r):void 0;a===void 0&&(a=n),oO(s,o,a)}},hO)}var dO=em;function pO(s){return s}var tm=pO;function gO(s,e,t){switch(t.length){case 0:return s.call(e);case 1:return s.call(e,t[0]);case 2:return s.call(e,t[0],t[1]);case 3:return s.call(e,t[0],t[1],t[2])}return s.apply(e,t)}var fO=gO,wO=fO,sg=Math.max;function yO(s,e,t){return e=sg(e===void 0?s.length-1:e,0),function(){for(var i=arguments,r=-1,n=sg(i.length-e,0),o=Array(n);++r<n;)o[r]=i[e+r];r=-1;for(var a=Array(e+1);++r<e;)a[r]=i[r];return a[e]=t(o),wO(s,this,a)}}var mO=yO;function bO(s){return function(){return s}}var vO=bO,IO=vO,ig=Fy,EO=tm,AO=ig?function(s,e){return ig(s,"toString",{configurable:!0,enumerable:!1,value:IO(e),writable:!0})}:EO,NO=AO,_O=800,CO=16,SO=Date.now;function TO(s){var e=0,t=0;return function(){var i=SO(),r=CO-(i-t);if(t=i,r>0){if(++e>=_O)return arguments[0]}else e=0;return s.apply(void 0,arguments)}}var PO=TO,$O=NO,MO=PO,OO=MO($O),xO=OO,DO=tm,kO=mO,jO=xO;function RO(s,e){return jO(kO(s,e,DO),s+"")}var UO=RO,LO=Zc,zO=Ou,FO=Jy,qO=zr;function BO(s,e,t){if(!qO(t))return!1;var i=typeof e;return(i=="number"?zO(t)&&FO(e,t.length):i=="string"&&e in t)?LO(t[e],s):!1}var HO=BO,WO=UO,VO=HO;function KO(s){return WO(function(e,t){var i=-1,r=t.length,n=r>1?t[r-1]:void 0,o=r>2?t[2]:void 0;for(n=s.length>3&&typeof n=="function"?(r--,n):void 0,o&&VO(t[0],t[1],o)&&(n=r<3?void 0:n,r=1),e=Object(e);++i<r;){var a=t[i];a&&s(e,a,i,n)}return e})}var GO=KO,YO=dO,QO=GO,ZO=QO(function(s,e,t){YO(s,e,t)}),JO=ZO,XO=Object.defineProperty,ex=Object.defineProperties,tx=Object.getOwnPropertyDescriptors,rg=Object.getOwnPropertySymbols,sx=Object.prototype.hasOwnProperty,ix=Object.prototype.propertyIsEnumerable,ng=(s,e,t)=>e in s?XO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Wa=(s,e)=>{for(var t in e||(e={}))sx.call(e,t)&&ng(s,t,e[t]);if(rg)for(var t of rg(e))ix.call(e,t)&&ng(s,t,e[t]);return s},rx=(s,e)=>ex(s,tx(e));function Es(s,e,t){var i;const r=zn(s);return((i=e.rpcMap)==null?void 0:i[r.reference])||`${jy}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Fr(s){return s.includes(":")?s.split(":")[1]:s}function sm(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function nx(s,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(s));if(!t.length)return[];const i=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;i.push(...n)}),i}function jl(s={},e={}){const t=og(s),i=og(e);return JO(t,i)}function og(s){var e,t,i,r;const n={};if(!ra(s))return n;for(const[o,a]of Object.entries(s)){const c=Cu(o)?[o]:a.chains,l=a.methods||[],h=a.events||[],u=a.rpcMap||{},d=Ro(o);n[d]=rx(Wa(Wa({},n[d]),a),{chains:cc(c,(e=n[d])==null?void 0:e.chains),methods:cc(l,(t=n[d])==null?void 0:t.methods),events:cc(h,(i=n[d])==null?void 0:i.events),rpcMap:Wa(Wa({},u),(r=n[d])==null?void 0:r.rpcMap)})}return n}function ox(s){return s.includes(":")?s.split(":")[2]:s}function ag(s){const e={};for(const[t,i]of Object.entries(s)){const r=i.methods||[],n=i.events||[],o=i.accounts||[],a=Cu(t)?[t]:i.chains?i.chains:sm(i.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Rl(s){return typeof s=="number"?s:s.includes("0x")?parseInt(s,16):(s=s.includes(":")?s.split(":")[1]:s,isNaN(Number(s))?s:Number(s))}const im={},_e=s=>im[s],Ul=(s,e)=>{im[s]=e};var ax=Object.defineProperty,cx=(s,e,t)=>e in s?ax(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Zr=(s,e,t)=>cx(s,typeof e!="symbol"?e+"":e,t);class lx{constructor(e){Zr(this,"name","polkadot"),Zr(this,"client"),Zr(this,"httpProviders"),Zr(this,"events"),Zr(this,"namespace"),Zr(this,"chainId"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Fr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Es(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new tt(new lt(i,_e("disableProviderPing")))}}var hx=Object.defineProperty,ux=Object.defineProperties,dx=Object.getOwnPropertyDescriptors,cg=Object.getOwnPropertySymbols,px=Object.prototype.hasOwnProperty,gx=Object.prototype.propertyIsEnumerable,Rh=(s,e,t)=>e in s?hx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,lg=(s,e)=>{for(var t in e||(e={}))px.call(e,t)&&Rh(s,t,e[t]);if(cg)for(var t of cg(e))gx.call(e,t)&&Rh(s,t,e[t]);return s},hg=(s,e)=>ux(s,dx(e)),Jr=(s,e,t)=>Rh(s,typeof e!="symbol"?e+"":e,t);class fx{constructor(e){Jr(this,"name","eip155"),Jr(this,"client"),Jr(this,"chainId"),Jr(this,"namespace"),Jr(this,"httpProviders"),Jr(this,"events"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const i=t||Es(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new tt(new lt(i,_e("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=parseInt(Fr(t));e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let r=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const n=parseInt(r,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,r;const n=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0];if(!n)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const o=this.client.session.get(e.topic),a=((r=o==null?void 0:o.sessionProperties)==null?void 0:r.capabilities)||{};if(a!=null&&a[n])return a==null?void 0:a[n];const c=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:hg(lg({},o.sessionProperties||{}),{capabilities:hg(lg({},a||{}),{[n]:c})})})}catch(l){console.warn("Failed to update session with capabilities",l)}return c}async getCallStatus(e){var t,i;const r=this.client.session.get(e.topic),n=(t=r.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=r.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(cs("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${fS}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var wx=Object.defineProperty,yx=(s,e,t)=>e in s?wx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Xr=(s,e,t)=>yx(s,typeof e!="symbol"?e+"":e,t);class mx{constructor(e){Xr(this,"name","solana"),Xr(this,"client"),Xr(this,"httpProviders"),Xr(this,"events"),Xr(this,"namespace"),Xr(this,"chainId"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Fr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Es(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new tt(new lt(i,_e("disableProviderPing")))}}var bx=Object.defineProperty,vx=(s,e,t)=>e in s?bx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,en=(s,e,t)=>vx(s,typeof e!="symbol"?e+"":e,t);class Ix{constructor(e){en(this,"name","cosmos"),en(this,"client"),en(this,"httpProviders"),en(this,"events"),en(this,"namespace"),en(this,"chainId"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Fr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Es(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new tt(new lt(i,_e("disableProviderPing")))}}var Ex=Object.defineProperty,Ax=(s,e,t)=>e in s?Ex(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,tn=(s,e,t)=>Ax(s,typeof e!="symbol"?e+"":e,t);class Nx{constructor(e){tn(this,"name","algorand"),tn(this,"client"),tn(this,"httpProviders"),tn(this,"events"),tn(this,"namespace"),tn(this,"chainId"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||Es(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Es(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new tt(new lt(i,_e("disableProviderPing")))}}var _x=Object.defineProperty,Cx=(s,e,t)=>e in s?_x(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,sn=(s,e,t)=>Cx(s,typeof e!="symbol"?e+"":e,t);class Sx{constructor(e){sn(this,"name","cip34"),sn(this,"client"),sn(this,"httpProviders"),sn(this,"events"),sn(this,"namespace"),sn(this,"chainId"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),r=Fr(t);e[r]=this.createHttpProvider(r,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new tt(new lt(i,_e("disableProviderPing")))}}var Tx=Object.defineProperty,Px=(s,e,t)=>e in s?Tx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,rn=(s,e,t)=>Px(s,typeof e!="symbol"?e+"":e,t);class $x{constructor(e){rn(this,"name","elrond"),rn(this,"client"),rn(this,"httpProviders"),rn(this,"events"),rn(this,"namespace"),rn(this,"chainId"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Fr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Es(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new tt(new lt(i,_e("disableProviderPing")))}}var Mx=Object.defineProperty,Ox=(s,e,t)=>e in s?Mx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,nn=(s,e,t)=>Ox(s,typeof e!="symbol"?e+"":e,t);class xx{constructor(e){nn(this,"name","multiversx"),nn(this,"client"),nn(this,"httpProviders"),nn(this,"events"),nn(this,"namespace"),nn(this,"chainId"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=Fr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Es(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new tt(new lt(i,_e("disableProviderPing")))}}var Dx=Object.defineProperty,kx=(s,e,t)=>e in s?Dx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,on=(s,e,t)=>kx(s,typeof e!="symbol"?e+"":e,t);class jx{constructor(e){on(this,"name","near"),on(this,"client"),on(this,"httpProviders"),on(this,"events"),on(this,"namespace"),on(this,"chainId"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Es(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Es(e,this.namespace);return typeof i>"u"?void 0:new tt(new lt(i,_e("disableProviderPing")))}}var Rx=Object.defineProperty,Ux=(s,e,t)=>e in s?Rx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,an=(s,e,t)=>Ux(s,typeof e!="symbol"?e+"":e,t);class Lx{constructor(e){an(this,"name","tezos"),an(this,"client"),an(this,"httpProviders"),an(this,"events"),an(this,"namespace"),an(this,"chainId"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Es(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Es(e,this.namespace);return typeof i>"u"?void 0:new tt(new lt(i))}}var zx=Object.defineProperty,Fx=(s,e,t)=>e in s?zx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,cn=(s,e,t)=>Fx(s,typeof e!="symbol"?e+"":e,t);class qx{constructor(e){cn(this,"name",Cn),cn(this,"client"),cn(this,"httpProviders"),cn(this,"events"),cn(this,"namespace"),cn(this,"chainId"),this.namespace=e.namespace,this.events=_e("events"),this.client=_e("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(Rs.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=zn(r);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Es(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new tt(new lt(i,_e("disableProviderPing")))}}var Bx=Object.defineProperty,Hx=Object.defineProperties,Wx=Object.getOwnPropertyDescriptors,ug=Object.getOwnPropertySymbols,Vx=Object.prototype.hasOwnProperty,Kx=Object.prototype.propertyIsEnumerable,Uh=(s,e,t)=>e in s?Bx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Va=(s,e)=>{for(var t in e||(e={}))Vx.call(e,t)&&Uh(s,t,e[t]);if(ug)for(var t of ug(e))Kx.call(e,t)&&Uh(s,t,e[t]);return s},Ll=(s,e)=>Hx(s,Wx(e)),Hs=(s,e,t)=>Uh(s,typeof e!="symbol"?e+"":e,t);class xu{constructor(e){Hs(this,"client"),Hs(this,"namespaces"),Hs(this,"optionalNamespaces"),Hs(this,"sessionProperties"),Hs(this,"events",new Qn),Hs(this,"rpcProviders",{}),Hs(this,"session"),Hs(this,"providerOpts"),Hs(this,"logger"),Hs(this,"uri"),Hs(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:Zn(Di({level:(e==null?void 0:e.logger)||Up})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new xu(e);return await t.initialize(),t}async request(e,t,i){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Va({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,r){const n=new Date().getTime();this.request(e,i,r).then(o=>t(null,nr(n,o))).catch(o=>t(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Re("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:r}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await r();if(this.session=n.session,this.session){const o=ag(this.session.namespaces);this.namespaces=jl(this.namespaces,o),this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await i();this.session=r;const n=ag(r.namespaces);return this.namespaces=jl(this.namespaces,n),this.persist("namespaces",this.namespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,r]=this.validateChain(e),n=this.getProvider(i);n.name===Cn?n.setDefaultChain(`${i}:${r}`,t):n.setDefaultChain(r,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(xr(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await uS.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Up,relayUrl:this.providerOpts.relayUrl||dS,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>Ro(t)))];Ul("client",this.client),Ul("events",this.events),Ul("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=nx(t,this.session),r=sm(i),n=jl(this.namespaces,this.optionalNamespaces),o=Ll(Va({},n[t]),{accounts:i,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new fx({namespace:o});break;case"algorand":this.rpcProviders[t]=new Nx({namespace:o});break;case"solana":this.rpcProviders[t]=new mx({namespace:o});break;case"cosmos":this.rpcProviders[t]=new Ix({namespace:o});break;case"polkadot":this.rpcProviders[t]=new lx({namespace:o});break;case"cip34":this.rpcProviders[t]=new Sx({namespace:o});break;case"elrond":this.rpcProviders[t]=new $x({namespace:o});break;case"multiversx":this.rpcProviders[t]=new xx({namespace:o});break;case"near":this.rpcProviders[t]=new jx({namespace:o});break;case"tezos":this.rpcProviders[t]=new Lx({namespace:o});break;default:this.rpcProviders[Cn]?this.rpcProviders[Cn].updateNamespace(o):this.rpcProviders[Cn]=new qx({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:t}=e,{event:i}=t;if(i.name==="accountsChanged"){const r=i.data;r&&xr(r)&&this.events.emit("accountsChanged",r.map(ox))}else if(i.name==="chainChanged"){const r=t.chainId,n=t.event.data,o=Ro(r),a=Rl(r)!==Rl(n)?`${o}:${Rl(n)}`:r;this.onChainChanged(a)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i;const{namespaces:r}=t,n=(i=this.client)==null?void 0:i.session.get(e);this.session=Ll(Va({},n),{namespaces:r}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Ll(Va({},Re("USER_DISCONNECTED")),{data:e.topic}))}),this.on(Rs.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Cn]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t,optionalNamespaces:i,sessionProperties:r}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=r,this.persist("namespaces",t),this.persist("optionalNamespaces",i)}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>Ro(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const r=Ro(Object.keys(this.namespaces)[0]),n=this.rpcProviders[r].getDefaultChain();return[r,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,r]=this.validateChain(e);r&&(t||this.getProvider(i).setDefaultChain(r),this.namespaces[i]?this.namespaces[i].defaultChain=r:this.namespaces[`${i}:${r}`]?this.namespaces[`${i}:${r}`].defaultChain=r:this.namespaces[`${i}:${r}`]={defaultChain:r},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",r))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(e,t){this.client.core.storage.setItem(`${Lp}/${e}`,t)}async getFromStore(e){return await this.client.core.storage.getItem(`${Lp}/${e}`)}}const Gx=xu,rm={caipNetworkIdToNumber(s){return s?Number(s.split(":")[1]):void 0},parseEvmChainId(s){return typeof s=="string"?this.caipNetworkIdToNumber(s):s},getNetworksByNamespace(s,e){return(s==null?void 0:s.filter(t=>t.chainNamespace===e))||[]},getFirstNetworkByNamespace(s,e){return this.getNetworksByNamespace(s,e)[0]}},Ka={bigNumber(s){return s?new po(s):new po(0)},multiply(s,e){if(s===void 0||e===void 0)return new po(0);const t=new po(s),i=new po(e);return t.times(i)},formatNumberToLocalString(s,e=2){return s===void 0?"0.00":typeof s=="number"?s.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(s).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(s){return s===void 0?0:parseFloat(s.replace(/,/gu,""))}},Yx=[{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"}]}],Qx=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Zx=[{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"}]}],te={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network"},Jx={getERC20Abi:s=>te.USDT_CONTRACT_ADDRESSES.includes(s)?Zx:Yx,getSwapAbi:()=>Qx},zi={validateCaipAddress(s){var e;if(((e=s.split(":"))==null?void 0:e.length)!==3)throw new Error("Invalid CAIP Address");return s},parseCaipAddress(s){const e=s.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${s}`);const[t,i,r]=e;if(!t||!i||!r)throw new Error(`Invalid CAIP-10 address: ${s}`);return{chainNamespace:t,chainId:i,address:r}},parseCaipNetworkId(s){const e=s.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${s}`);const[t,i]=e;if(!t||!i)throw new Error(`Invalid CAIP-2 network id: ${s}`);return{chainNamespace:t,chainId:i}}},he={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache"};function zl(s){if(!s)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${s}:connected_connector_id`}const oe={setItem(s,e){Uo()&&e!==void 0&&localStorage.setItem(s,e)},getItem(s){if(Uo())return localStorage.getItem(s)||void 0},removeItem(s){Uo()&&localStorage.removeItem(s)},clear(){Uo()&&localStorage.clear()}};function Uo(){return typeof window<"u"&&typeof localStorage<"u"}function Zi(s,e){return e==="light"?{"--w3m-accent":(s==null?void 0:s["--w3m-accent"])||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":(s==null?void 0:s["--w3m-accent"])||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}var dg={};const Fl=(typeof T.process<"u"&&typeof dg<"u"?dg.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",ls={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:Fl,SECURE_SITE_DASHBOARD:`${Fl}/dashboard`,SECURE_SITE_FAVICON:`${Fl}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],WC_COINBASE_PAY_SDK_CHAINS:["ethereum","arbitrum","polygon","berachain","avalanche-c-chain","optimism","celo","base"],WC_COINBASE_PAY_SDK_FALLBACK_CHAIN:"ethereum",WC_COINBASE_PAY_SDK_CHAIN_NAME_MAP:{Ethereum:"ethereum","Arbitrum One":"arbitrum",Polygon:"polygon",Berachain:"berachain",Avalanche:"avalanche-c-chain","OP Mainnet":"optimism",Celo:"celo",Base:"base"},WC_COINBASE_ONRAMP_APP_ID:"bf18c88d-495a-463b-b249-0b9d3656cf5e",SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:["eip155","solana"],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:["eip155"],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:["eip155","solana"],ACTIVITY_ENABLED_CHAIN_NAMESPACES:["eip155","solana"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in a new browser tab"},DEFAULT_FEATURES:{swaps:!0,onramp:!0,receive:!0,send:!0,email:!0,emailShowWallets:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],history:!0,analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0},DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"}},J={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(s,e){return Date.now()-s>e},getActiveNetworkProps(){const s=J.getActiveNamespace(),e=J.getActiveCaipNetworkId(),t=e?e.split(":")[1]:void 0,i=t?isNaN(Number(t))?t:Number(t):void 0;return{namespace:s,caipNetworkId:e,chainId:i}},setWalletConnectDeepLink({name:s,href:e}){try{oe.setItem(he.DEEPLINK_CHOICE,JSON.stringify({href:e,name:s}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const s=oe.getItem(he.DEEPLINK_CHOICE);if(s)return JSON.parse(s)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{oe.removeItem(he.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(s){try{oe.setItem(he.ACTIVE_NAMESPACE,s)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(s){try{oe.setItem(he.ACTIVE_CAIP_NETWORK_ID,s),J.setActiveNamespace(s.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return oe.getItem(he.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{oe.removeItem(he.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(s){try{const e=zl(s);oe.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(s){try{const e=J.getRecentWallets();e.find(i=>i.id===s.id)||(e.unshift(s),e.length>2&&e.pop(),oe.setItem(he.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const s=oe.getItem(he.RECENT_WALLETS);return s?JSON.parse(s):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(s,e){try{const t=zl(s);oe.setItem(t,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return oe.getItem(he.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(s){if(s)try{const e=zl(s);return oe.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",s)}},setConnectedSocialProvider(s){try{oe.setItem(he.CONNECTED_SOCIAL,s)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return oe.getItem(he.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{oe.removeItem(he.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return oe.getItem(he.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var t;const s=oe.getItem(he.ACTIVE_CAIP_NETWORK_ID);return(t=s==null?void 0:s.split(":"))==null?void 0:t[1]},setConnectionStatus(s){try{oe.setItem(he.CONNECTION_STATUS,s)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return oe.getItem(he.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const s=oe.getItem(he.CONNECTED_NAMESPACES);return s!=null&&s.length?s.split(","):[]}catch{return[]}},setConnectedNamespaces(s){try{const e=Array.from(new Set(s));oe.setItem(he.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(s){try{const e=J.getConnectedNamespaces();e.includes(s)||(e.push(s),J.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(s){try{const e=J.getConnectedNamespaces(),t=e.indexOf(s);t>-1&&(e.splice(t,1),J.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return oe.getItem(he.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(s){try{oe.setItem(he.TELEGRAM_SOCIAL_PROVIDER,s)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{oe.removeItem(he.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let s={};try{const e=oe.getItem(he.PORTFOLIO_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return s},removeAddressFromBalanceCache(s){try{const e=J.getBalanceCache();oe.setItem(he.PORTFOLIO_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove address from balance cache",s)}},getBalanceCacheForCaipAddress(s){try{const t=J.getBalanceCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;J.removeAddressFromBalanceCache(s)}catch{console.info("Unable to get balance cache for address",s)}},updateBalanceCache(s){try{const e=J.getBalanceCache();e[s.caipAddress]=s,oe.setItem(he.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",s)}},getNativeBalanceCache(){let s={};try{const e=oe.getItem(he.NATIVE_BALANCE_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return s},removeAddressFromNativeBalanceCache(s){try{const e=J.getBalanceCache();oe.setItem(he.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove address from balance cache",s)}},getNativeBalanceCacheForCaipAddress(s){try{const t=J.getNativeBalanceCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",s),J.removeAddressFromBalanceCache(s)}catch{console.info("Unable to get balance cache for address",s)}},updateNativeBalanceCache(s){try{const e=J.getNativeBalanceCache();e[s.caipAddress]=s,oe.setItem(he.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",s)}},getEnsCache(){let s={};try{const e=oe.getItem(he.ENS_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return s},getEnsFromCacheForAddress(s){try{const t=J.getEnsCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;J.removeEnsFromCache(s)}catch{console.info("Unable to get ens name from cache",s)}},updateEnsCache(s){try{const e=J.getEnsCache();e[s.address]=s,oe.setItem(he.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",s)}},removeEnsFromCache(s){try{const e=J.getEnsCache();oe.setItem(he.ENS_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove ens name from cache",s)}},getIdentityCache(){let s={};try{const e=oe.getItem(he.IDENTITY_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return s},getIdentityFromCacheForAddress(s){try{const t=J.getIdentityCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;J.removeIdentityFromCache(s)}catch{console.info("Unable to get identity from cache",s)}},updateIdentityCache(s){try{const e=J.getIdentityCache();e[s.address]={identity:s.identity,timestamp:s.timestamp},oe.setItem(he.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",s)}},removeIdentityFromCache(s){try{const e=J.getIdentityCache();oe.setItem(he.IDENTITY_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove identity from cache",s)}},clearAddressCache(){try{oe.removeItem(he.PORTFOLIO_CACHE),oe.removeItem(he.NATIVE_BALANCE_CACHE),oe.removeItem(he.ENS_CACHE),oe.removeItem(he.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}}},ce={isMobile(){var s;return this.isClient()?!!((s=window==null?void 0:window.matchMedia("(pointer:coarse)"))!=null&&s.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(s,e=""){return s==null?void 0:s.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const s=window==null?void 0:window.navigator.userAgent.toLowerCase();return ce.isMobile()&&s.includes("android")},isIos(){if(!this.isMobile())return!1;const s=window==null?void 0:window.navigator.userAgent.toLowerCase();return s.includes("iphone")||s.includes("ipad")},isSafari(){return this.isClient()?(window==null?void 0:window.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(s){return s?s-Date.now()<=ls.TEN_SEC_MS:!0},isAllowedRetry(s,e=ls.ONE_SEC_MS){return Date.now()-s>=e},copyToClopboard(s){navigator.clipboard.writeText(s)},isIframe(){try{return(window==null?void 0:window.self)!==(window==null?void 0:window.top)}catch{return!1}},getPairingExpiry(){return Date.now()+ls.FOUR_MINUTES_MS},getNetworkId(s){return s==null?void 0:s.split(":")[1]},getPlainAddress(s){return s==null?void 0:s.split(":")[2]},async wait(s){return new Promise(e=>{setTimeout(e,s)})},debounce(s,e=500){let t;return(...i)=>{function r(){s(...i)}t&&clearTimeout(t),t=setTimeout(r,e)}},isHttpUrl(s){return s.startsWith("http://")||s.startsWith("https://")},formatNativeUrl(s,e){if(ce.isHttpUrl(s))return this.formatUniversalUrl(s,e);let t=s;t.includes("://")||(t=s.replaceAll("/","").replaceAll(":",""),t=`${t}://`),t.endsWith("/")||(t=`${t}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const i=encodeURIComponent(e);return{redirect:`${t}wc?uri=${i}`,href:t}},formatUniversalUrl(s,e){if(!ce.isHttpUrl(s))return this.formatNativeUrl(s,e);let t=s;t.endsWith("/")||(t=`${t}/`);const i=encodeURIComponent(e);return{redirect:`${t}wc?uri=${i}`,href:t}},getOpenTargetForPlatform(s){return s==="popupWindow"?s:this.isTelegram()?J.getTelegramSocialProvider()?"_top":"_blank":s},openHref(s,e,t){window==null||window.open(s,this.getOpenTargetForPlatform(e),t||"noreferrer noopener")},returnOpenHref(s,e,t){return window==null?void 0:window.open(s,this.getOpenTargetForPlatform(e),t||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},async preloadImage(s){const e=new Promise((t,i)=>{const r=new Image;r.onload=t,r.onerror=i,r.crossOrigin="anonymous",r.src=s});return Promise.race([e,ce.wait(2e3)])},formatBalance(s,e){let t="0.000";if(typeof s=="string"){const i=Number(s);if(i){const r=Math.floor(i*1e3)/1e3;r&&(t=r.toString())}}return`${t}${e?` ${e}`:""}`},formatBalance2(s,e){var i;let t;if(s==="0")t="0";else if(typeof s=="string"){const r=Number(s);r&&(t=(i=r.toString().match(/^-?\d+(?:\.\d{0,3})?/u))==null?void 0:i[0])}return{value:t??"0",rest:t==="0"?"000":"",symbol:e}},getApiUrl(){return te.W3M_API_URL},getBlockchainApiUrl(){return te.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return te.PULSE_API_URL},getUUID(){return crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})},parseError(s){var e,t;return typeof s=="string"?s:typeof((t=(e=s==null?void 0:s.issues)==null?void 0:e[0])==null?void 0:t.message)=="string"?s.issues[0].message:s instanceof Error?s.message:"Unknown error"},sortRequestedNetworks(s,e=[]){const t={};return e&&s&&(s.forEach((i,r)=>{t[i]=r}),e.sort((i,r)=>{const n=t[i.id],o=t[r.id];return n!==void 0&&o!==void 0?n-o:n!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(s){let e=0;for(const t of s)e+=t.value??0;return e},formatTokenBalance(s){const e=s.toFixed(2),[t,i]=e.split(".");return{dollars:t,pennies:i}},isAddress(s,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(s)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(s)||/^(?:0x)?[0-9A-F]{40}$/iu.test(s))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(s);default:return!1}},uniqueBy(s,e){const t=new Set;return s.filter(i=>{const r=i[e];return t.has(r)?!1:(t.add(r),!0)})},generateSdkVersion(s,e,t){const r=s.length===0?ls.ADAPTER_TYPES.UNIVERSAL:s.map(n=>n.adapterType).join(",");return`${e}-${r}-${t}`},createAccount(s,e,t,i,r){return{namespace:s,address:e,type:t,publicKey:i,path:r}},isCaipAddress(s){if(typeof s!="string")return!1;const e=s.split(":"),t=e[0];return e.filter(Boolean).length===3&&t in te.CHAIN_NAME_MAP},isMac(){const s=window==null?void 0:window.navigator.userAgent.toLowerCase();return s.includes("macintosh")&&!s.includes("safari")},formatTelegramSocialLoginUrl(s){const e=`--${encodeURIComponent(window==null?void 0:window.location.href)}`,t="state=";if(new URL(s).host==="auth.magic.link"){const r="provider_authorization_url=",n=s.substring(s.indexOf(r)+r.length),o=this.injectIntoUrl(decodeURIComponent(n),t,e);return s.replace(n,encodeURIComponent(o))}return this.injectIntoUrl(s,t,e)},injectIntoUrl(s,e,t){const i=s.indexOf(e);if(i===-1)throw new Error(`${e} parameter not found in the URL: ${s}`);const r=s.indexOf("&",i),n=e.length,o=r!==-1?r:s.length,a=s.substring(0,i+n),c=s.substring(i+n,o),l=s.substring(r),h=c+t;return a+h+l}};async function _o(...s){const e=await fetch(...s);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class il{constructor({baseUrl:e,clientId:t}){this.baseUrl=e,this.clientId=t}async get({headers:e,signal:t,cache:i,...r}){const n=this.createUrl(r);return(await _o(n,{method:"GET",headers:e,signal:t,cache:i})).json()}async getBlob({headers:e,signal:t,...i}){const r=this.createUrl(i);return(await _o(r,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await _o(n,{method:"POST",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}async put({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await _o(n,{method:"PUT",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}async delete({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await _o(n,{method:"DELETE",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}createUrl({path:e,params:t}){const i=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([r,n])=>{n&&i.searchParams.append(r,n)}),this.clientId&&i.searchParams.append("clientId",this.clientId),i}}const Xx={handleSolanaDeeplinkRedirect(s){if(v.state.activeChain===te.CHAIN.SOLANA){const e=window.location.href,t=encodeURIComponent(e);if(s==="Phantom"&&!("phantom"in window)){const i=e.startsWith("https")?"https":"http",r=e.split("/")[2],n=encodeURIComponent(`${i}://${r}`);window.location.href=`https://phantom.app/ul/browse/${t}?ref=${n}`}s==="Coinbase Wallet"&&!("coinbaseSolana"in window)&&(window.location.href=`https://go.cb-w.com/dapp?cb_url=${t}`)}}},ps=ct({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Qs={state:ps,subscribeNetworkImages(s){return hs(ps.networkImages,()=>s(ps.networkImages))},subscribeKey(s,e){return Ns(ps,s,e)},subscribe(s){return hs(ps,()=>s(ps))},setWalletImage(s,e){ps.walletImages[s]=e},setNetworkImage(s,e){ps.networkImages[s]=e},setChainImage(s,e){ps.chainImages[s]=e},setConnectorImage(s,e){ps.connectorImages={...ps.connectorImages,[s]:e}},setTokenImage(s,e){ps.tokenImages[s]=e},setCurrencyImage(s,e){ps.currencyImages[s]=e}},eD={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},ql=ct({networkImagePromises:{}}),nm={async fetchWalletImage(s){if(s)return await le._fetchWalletImage(s),this.getWalletImageById(s)},async fetchNetworkImage(s){if(!s)return;const e=this.getNetworkImageById(s);return e||(ql.networkImagePromises[s]||(ql.networkImagePromises[s]=le._fetchNetworkImage(s)),await ql.networkImagePromises[s],this.getNetworkImageById(s))},getWalletImageById(s){if(s)return Qs.state.walletImages[s]},getWalletImage(s){if(s!=null&&s.image_url)return s==null?void 0:s.image_url;if(s!=null&&s.image_id)return Qs.state.walletImages[s.image_id]},getNetworkImage(s){var e,t,i;if((e=s==null?void 0:s.assets)!=null&&e.imageUrl)return(t=s==null?void 0:s.assets)==null?void 0:t.imageUrl;if((i=s==null?void 0:s.assets)!=null&&i.imageId)return Qs.state.networkImages[s.assets.imageId]},getNetworkImageById(s){if(s)return Qs.state.networkImages[s]},getConnectorImage(s){if(s!=null&&s.imageUrl)return s.imageUrl;if(s!=null&&s.imageId)return Qs.state.connectorImages[s.imageId]},getChainImage(s){return Qs.state.networkImages[eD[s]]}},tD={getFeatureValue(s,e){const t=e==null?void 0:e[s];return t===void 0?ls.DEFAULT_FEATURES[s]:t},filterSocialsByPlatform(s){if(!s||!s.length)return s;if(ce.isTelegram()){if(ce.isIos())return s.filter(e=>e!=="google");if(ce.isMac())return s.filter(e=>e!=="x");if(ce.isAndroid())return s.filter(e=>!["facebook","x"].includes(e))}return s}},ie=ct({features:ls.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:ls.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0}),j={state:ie,subscribeKey(s,e){return Ns(ie,s,e)},setOptions(s){Object.assign(ie,s)},setFeatures(s){if(!s)return;ie.features||(ie.features=ls.DEFAULT_FEATURES);const e={...ie.features,...s};ie.features=e,ie.features.socials&&(ie.features.socials=tD.filterSocialsByPlatform(ie.features.socials))},setProjectId(s){ie.projectId=s},setCustomRpcUrls(s){ie.customRpcUrls=s},setAllWallets(s){ie.allWallets=s},setIncludeWalletIds(s){ie.includeWalletIds=s},setExcludeWalletIds(s){ie.excludeWalletIds=s},setFeaturedWalletIds(s){ie.featuredWalletIds=s},setTokens(s){ie.tokens=s},setTermsConditionsUrl(s){ie.termsConditionsUrl=s},setPrivacyPolicyUrl(s){ie.privacyPolicyUrl=s},setCustomWallets(s){ie.customWallets=s},setIsSiweEnabled(s){ie.isSiweEnabled=s},setIsUniversalProvider(s){ie.isUniversalProvider=s},setSdkVersion(s){ie.sdkVersion=s},setMetadata(s){ie.metadata=s},setDisableAppend(s){ie.disableAppend=s},setEIP6963Enabled(s){ie.enableEIP6963=s},setDebug(s){ie.debug=s},setEnableWalletConnect(s){ie.enableWalletConnect=s},setEnableWalletGuide(s){ie.enableWalletGuide=s},setEnableAuthLogger(s){ie.enableAuthLogger=s},setEnableWallets(s){ie.enableWallets=s},setHasMultipleAddresses(s){ie.hasMultipleAddresses=s},setSIWX(s){ie.siwx=s},setConnectMethodsOrder(s){ie.features={...ie.features,connectMethodsOrder:s}},setWalletFeaturesOrder(s){ie.features={...ie.features,walletFeaturesOrder:s}},setSocialsOrder(s){ie.features={...ie.features,socials:s}},setCollapseWallets(s){ie.features={...ie.features,collapseWallets:s}},setEnableEmbedded(s){ie.enableEmbedded=s},setAllowUnsupportedChain(s){ie.allowUnsupportedChain=s},setManualWCControl(s){ie.manualWCControl=s},setEnableNetworkSwitch(s){ie.enableNetworkSwitch=s},setDefaultAccountTypes(s={}){Object.entries(s).forEach(([e,t])=>{t&&(ie.defaultAccountTypes[e]=t)})},setUniversalProviderConfigOverride(s){ie.universalProviderConfigOverride=s},getUniversalProviderConfigOverride(){return ie.universalProviderConfigOverride},getSnapshot(){return Jo(ie)}},Fi=ct({message:"",variant:"info",open:!1}),dc={state:Fi,subscribeKey(s,e){return Ns(Fi,s,e)},open(s,e){const{debug:t}=j.state,{shortMessage:i,longMessage:r}=s;t&&(Fi.message=i,Fi.variant=e,Fi.open=!0),r&&console.error(typeof r=="function"?r():r)},close(){Fi.open=!1,Fi.message="",Fi.variant="info"}},sD=ce.getAnalyticsUrl(),iD=new il({baseUrl:sD,clientId:null}),rD=["MODAL_CREATED"],Ii=ct({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),Ke={state:Ii,subscribe(s){return hs(Ii,()=>s(Ii))},getSdkProperties(){const{projectId:s,sdkType:e,sdkVersion:t}=j.state;return{projectId:s,st:e,sv:t||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(s){try{const e=se.state.address;if(rD.includes(s.data.event)||typeof window>"u")return;await iD.post({path:"/e",params:Ke.getSdkProperties(),body:{eventId:ce.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:s.timestamp,props:{...s.data,address:e}}}),Ii.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===te.HTTP_STATUS_CODES.FORBIDDEN&&!Ii.reportedErrors.FORBIDDEN&&(dc.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${Uo()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),Ii.reportedErrors.FORBIDDEN=!0)}},sendEvent(s){var e;Ii.timestamp=Date.now(),Ii.data=s,(e=j.state.features)!=null&&e.analytics&&Ke._sendAnalyticsEvent(Ii)}},nD=ce.getApiUrl(),Vt=new il({baseUrl:nD,clientId:null}),oD="40",pg="4",aD=20,Oe=ct({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),le={state:Oe,subscribeKey(s,e){return Ns(Oe,s,e)},_getSdkProperties(){const{projectId:s,sdkType:e,sdkVersion:t}=j.state;return{projectId:s,st:e||"appkit",sv:t||"html-wagmi-4.2.2"}},_filterOutExtensions(s){return j.state.isUniversalProvider?s.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):s},async _fetchWalletImage(s){const e=`${Vt.baseUrl}/getWalletImage/${s}`,t=await Vt.getBlob({path:e,params:le._getSdkProperties()});Qs.setWalletImage(s,URL.createObjectURL(t))},async _fetchNetworkImage(s){const e=`${Vt.baseUrl}/public/getAssetImage/${s}`,t=await Vt.getBlob({path:e,params:le._getSdkProperties()});Qs.setNetworkImage(s,URL.createObjectURL(t))},async _fetchConnectorImage(s){const e=`${Vt.baseUrl}/public/getAssetImage/${s}`,t=await Vt.getBlob({path:e,params:le._getSdkProperties()});Qs.setConnectorImage(s,URL.createObjectURL(t))},async _fetchCurrencyImage(s){const e=`${Vt.baseUrl}/public/getCurrencyImage/${s}`,t=await Vt.getBlob({path:e,params:le._getSdkProperties()});Qs.setCurrencyImage(s,URL.createObjectURL(t))},async _fetchTokenImage(s){const e=`${Vt.baseUrl}/public/getTokenImage/${s}`,t=await Vt.getBlob({path:e,params:le._getSdkProperties()});Qs.setTokenImage(s,URL.createObjectURL(t))},async fetchNetworkImages(){const s=v.getAllRequestedCaipNetworks(),e=s==null?void 0:s.map(({assets:t})=>t==null?void 0:t.imageId).filter(Boolean).filter(t=>!nm.getNetworkImageById(t));e&&await Promise.allSettled(e.map(t=>le._fetchNetworkImage(t)))},async fetchConnectorImages(){const{connectors:s}=ae.state,e=s.map(({imageId:t})=>t).filter(Boolean);await Promise.allSettled(e.map(t=>le._fetchConnectorImage(t)))},async fetchCurrencyImages(s=[]){await Promise.allSettled(s.map(e=>le._fetchCurrencyImage(e)))},async fetchTokenImages(s=[]){await Promise.allSettled(s.map(e=>le._fetchTokenImage(e)))},async fetchFeaturedWallets(){const{featuredWalletIds:s}=j.state;if(s!=null&&s.length){const{data:e}=await Vt.get({path:"/getWallets",params:{...le._getSdkProperties(),page:"1",entries:s!=null&&s.length?String(s.length):pg,include:s==null?void 0:s.join(",")}});e.sort((i,r)=>s.indexOf(i.id)-s.indexOf(r.id));const t=e.map(i=>i.image_id).filter(Boolean);await Promise.allSettled(t.map(i=>le._fetchWalletImage(i))),Oe.featured=e,Oe.allFeatured=e}},async fetchRecommendedWallets(){try{Oe.isFetchingRecommendedWallets=!0;const{includeWalletIds:s,excludeWalletIds:e,featuredWalletIds:t}=j.state,i=[...e??[],...t??[]].filter(Boolean),r=v.getRequestedCaipNetworkIds().join(","),{data:n,count:o}=await Vt.get({path:"/getWallets",params:{...le._getSdkProperties(),page:"1",chains:r,entries:pg,include:s==null?void 0:s.join(","),exclude:i==null?void 0:i.join(",")}}),a=J.getRecentWallets(),c=n.map(h=>h.image_id).filter(Boolean),l=a.map(h=>h.image_id).filter(Boolean);await Promise.allSettled([...c,...l].map(h=>le._fetchWalletImage(h))),Oe.recommended=n,Oe.allRecommended=n,Oe.count=o??0}catch{}finally{Oe.isFetchingRecommendedWallets=!1}},async fetchWallets({page:s}){const{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:i}=j.state,r=v.getRequestedCaipNetworkIds().join(","),n=[...Oe.recommended.map(({id:l})=>l),...t??[],...i??[]].filter(Boolean),{data:o,count:a}=await Vt.get({path:"/getWallets",params:{...le._getSdkProperties(),page:String(s),entries:oD,chains:r,include:e==null?void 0:e.join(","),exclude:n.join(",")}}),c=o.slice(0,aD).map(l=>l.image_id).filter(Boolean);await Promise.allSettled(c.map(l=>le._fetchWalletImage(l))),Oe.wallets=ce.uniqueBy([...Oe.wallets,...le._filterOutExtensions(o)],"id"),Oe.count=a>Oe.count?a:Oe.count,Oe.page=s},async initializeExcludedWallets({ids:s}){const e=v.getRequestedCaipNetworkIds().join(","),{data:t}=await Vt.get({path:"/getWallets",params:{...le._getSdkProperties(),page:"1",entries:String(s.length),chains:e,include:s==null?void 0:s.join(",")}});t&&t.forEach(i=>{i!=null&&i.rdns&&Oe.excludedWallets.push({rdns:i.rdns,name:i.name})})},async searchWallet({search:s,badge:e}){const{includeWalletIds:t,excludeWalletIds:i}=j.state;Oe.search=[];const r=v.getRequestedCaipNetworkIds().join(","),{data:n}=await Vt.get({path:"/getWallets",params:{...le._getSdkProperties(),page:"1",entries:"100",search:s==null?void 0:s.trim(),badge_type:e,chains:r,include:t==null?void 0:t.join(","),exclude:i==null?void 0:i.join(",")}});Ke.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:s??""}});const o=n.map(a=>a.image_id).filter(Boolean);await Promise.allSettled([...o.map(a=>le._fetchWalletImage(a)),ce.wait(300)]),Oe.search=le._filterOutExtensions(n)},initPromise(s,e){const t=Oe.promises[s];return t||(Oe.promises[s]=e())},prefetch({fetchConnectorImages:s=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:t=!0,fetchNetworkImages:i=!0}={}){const r=[s&&le.initPromise("connectorImages",le.fetchConnectorImages),e&&le.initPromise("featuredWallets",le.fetchFeaturedWallets),t&&le.initPromise("recommendedWallets",le.fetchRecommendedWallets),i&&le.initPromise("networkImages",le.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(r)},prefetchAnalyticsConfig(){var s;(s=j.state.features)!=null&&s.analytics&&le.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:s}=await Vt.get({path:"/getAnalyticsConfig",params:le._getSdkProperties()});j.setFeatures({analytics:s})}catch{j.setFeatures({analytics:!1})}},setFilterByNamespace(s){if(!s){Oe.featured=Oe.allFeatured,Oe.recommended=Oe.allRecommended;return}const e=v.getRequestedCaipNetworkIds().join(",");Oe.featured=Oe.allFeatured.filter(t=>{var i;return(i=t.chains)==null?void 0:i.some(r=>e.includes(r))}),Oe.recommended=Oe.allRecommended.filter(t=>{var i;return(i=t.chains)==null?void 0:i.some(r=>e.includes(r))})}},Se=ct({view:"Connect",history:["Connect"],transactionStack:[]}),De={state:Se,subscribeKey(s,e){return Ns(Se,s,e)},pushTransactionStack(s){Se.transactionStack.push(s)},popTransactionStack(s){var t,i;const e=Se.transactionStack.pop();if(e)if(s)this.goBack(),(t=e==null?void 0:e.onCancel)==null||t.call(e);else{if(e.goBack)this.goBack();else if(e.replace){const n=Se.history.indexOf("ConnectingSiwe");n>0?this.goBackToIndex(n-1):(wt.close(),Se.history=[])}else e.view&&this.reset(e.view);(i=e==null?void 0:e.onSuccess)==null||i.call(e)}},push(s,e){s!==Se.view&&(Se.view=s,Se.history.push(s),Se.data=e)},reset(s,e){Se.view=s,Se.history=[s],Se.data=e},replace(s,e){Se.history.at(-1)===s||(Se.view=s,Se.history[Se.history.length-1]=s,Se.data=e)},goBack(){var e;const s=!v.state.activeCaipAddress&&this.state.view==="ConnectingFarcaster";if(Se.history.length>1&&!Se.history.includes("UnsupportedChain")){Se.history.pop();const[t]=Se.history.slice(-1);t&&(Se.view=t)}else wt.close();(e=Se.data)!=null&&e.wallet&&(Se.data.wallet=void 0),setTimeout(()=>{var t,i,r;if(s){se.setFarcasterUrl(void 0,v.state.activeChain);const n=ae.getAuthConnector();(t=n==null?void 0:n.provider)==null||t.reload();const o=Jo(j.state);(r=(i=n==null?void 0:n.provider)==null?void 0:i.syncDappData)==null||r.call(i,{metadata:o.metadata,sdkVersion:o.sdkVersion,projectId:o.projectId,sdkType:o.sdkType})}},100)},goBackToIndex(s){if(Se.history.length>1){Se.history=Se.history.slice(0,s+1);const[e]=Se.history.slice(-1);e&&(Se.view=e)}}},Ei=ct({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Jt={state:Ei,subscribe(s){return hs(Ei,()=>s(Ei))},setThemeMode(s){Ei.themeMode=s;try{const e=ae.getAuthConnector();if(e){const t=Jt.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:s,themeVariables:t,w3mThemeVariables:Zi(t,s)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(s){Ei.themeVariables={...Ei.themeVariables,...s};try{const e=ae.getAuthConnector();if(e){const t=Jt.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:Zi(Ei.themeVariables,Ei.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Jo(Ei)}},om={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0},xe=ct({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...om}}),ae={state:xe,subscribe(s){return hs(xe,()=>{s(xe)})},subscribeKey(s,e){return Ns(xe,s,e)},initialize(s){s.forEach(e=>{const t=J.getConnectedConnectorId(e);t&&this.setConnectorId(t,e)})},setActiveConnector(s){s&&(xe.activeConnector=$r(s))},setConnectors(s){s.filter(t=>!xe.allConnectors.some(i=>i.id===t.id&&this.getConnectorName(i.name)===this.getConnectorName(t.name)&&i.chain===t.chain)).forEach(t=>{t.type!=="MULTI_CHAIN"&&xe.allConnectors.push($r(t))}),xe.connectors=this.mergeMultiChainConnectors(xe.allConnectors)},removeAdapter(s){xe.allConnectors=xe.allConnectors.filter(e=>e.chain!==s),xe.connectors=this.mergeMultiChainConnectors(xe.allConnectors)},mergeMultiChainConnectors(s){const e=this.generateConnectorMapByName(s),t=[];return e.forEach(i=>{const r=i[0],n=(r==null?void 0:r.id)===te.CONNECTOR_ID.AUTH;i.length>1&&r?t.push({name:r.name,imageUrl:r.imageUrl,imageId:r.imageId,connectors:[...i],type:n?"AUTH":"MULTI_CHAIN",chain:"eip155",id:(r==null?void 0:r.id)||""}):r&&t.push(r)}),t},generateConnectorMapByName(s){const e=new Map;return s.forEach(t=>{const{name:i}=t,r=this.getConnectorName(i);if(!r)return;const n=e.get(r)||[];n.find(a=>a.chain===t.chain)||n.push(t),e.set(r,n)}),e},getConnectorName(s){return s&&({"Trust Wallet":"Trust"}[s]||s)},getUniqueConnectorsByName(s){const e=[];return s.forEach(t=>{e.find(i=>i.chain===t.chain)||e.push(t)}),e},addConnector(s){var e,t,i;if(s.id===te.CONNECTOR_ID.AUTH){const r=s,n=Jo(j.state),o=Jt.getSnapshot().themeMode,a=Jt.getSnapshot().themeVariables;(t=(e=r==null?void 0:r.provider)==null?void 0:e.syncDappData)==null||t.call(e,{metadata:n.metadata,sdkVersion:n.sdkVersion,projectId:n.projectId,sdkType:n.sdkType}),(i=r==null?void 0:r.provider)==null||i.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:Zi(a,o)}),this.setConnectors([s])}else this.setConnectors([s])},getAuthConnector(s){var i;const e=s||v.state.activeChain,t=xe.connectors.find(r=>r.id===te.CONNECTOR_ID.AUTH);if(t)return(i=t==null?void 0:t.connectors)!=null&&i.length?t.connectors.find(n=>n.chain===e):t},getAnnouncedConnectorRdns(){return xe.connectors.filter(s=>s.type==="ANNOUNCED").map(s=>{var e;return(e=s.info)==null?void 0:e.rdns})},getConnectorById(s){return xe.allConnectors.find(e=>e.id===s)},getConnector(s,e){return xe.allConnectors.filter(i=>i.chain===v.state.activeChain).find(i=>{var r;return i.explorerId===s||((r=i.info)==null?void 0:r.rdns)===e})},syncIfAuthConnector(s){var n,o;if(s.id!=="ID_AUTH")return;const e=s,t=Jo(j.state),i=Jt.getSnapshot().themeMode,r=Jt.getSnapshot().themeVariables;(o=(n=e==null?void 0:e.provider)==null?void 0:n.syncDappData)==null||o.call(n,{metadata:t.metadata,sdkVersion:t.sdkVersion,sdkType:t.sdkType,projectId:t.projectId}),e.provider.syncTheme({themeMode:i,themeVariables:r,w3mThemeVariables:Zi(r,i)})},getConnectorsByNamespace(s){const e=xe.allConnectors.filter(t=>t.chain===s);return this.mergeMultiChainConnectors(e)},selectWalletConnector(s){const e=ae.getConnector(s.id,s.rdns);v.state.activeChain===te.CHAIN.SOLANA&&Xx.handleSolanaDeeplinkRedirect((e==null?void 0:e.name)||s.name||""),e?De.push("ConnectingExternal",{connector:e}):De.push("ConnectingWalletConnect",{wallet:s})},getConnectors(s){return s?this.getConnectorsByNamespace(s):this.mergeMultiChainConnectors(xe.allConnectors)},setFilterByNamespace(s){xe.filterByNamespace=s,xe.connectors=this.getConnectors(s),le.setFilterByNamespace(s)},setConnectorId(s,e){s&&(xe.activeConnectorIds={...xe.activeConnectorIds,[e]:s},J.setConnectedConnectorId(e,s))},removeConnectorId(s){xe.activeConnectorIds={...xe.activeConnectorIds,[s]:void 0},J.deleteConnectedConnectorId(s)},getConnectorId(s){if(s)return xe.activeConnectorIds[s]},isConnected(s){return s?!!xe.activeConnectorIds[s]:Object.values(xe.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){xe.activeConnectorIds={...om}}};function Ga(s,e){return ae.getConnectorId(s)===e}function cD(s){const e=Array.from(v.state.chains.keys());let t=[];return s?(t.push([s,v.state.chains.get(s)]),Ga(s,te.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(i=>{i!==s&&Ga(i,te.CONNECTOR_ID.WALLET_CONNECT)&&t.push([i,v.state.chains.get(i)])}):Ga(s,te.CONNECTOR_ID.AUTH)&&e.forEach(i=>{i!==s&&Ga(i,te.CONNECTOR_ID.AUTH)&&t.push([i,v.state.chains.get(i)])})):t=Array.from(v.state.chains.entries()),t}var lD=Object.defineProperty,hD=(s,e,t)=>e in s?lD(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,gg=(s,e,t)=>hD(s,typeof e!="symbol"?e+"":e,t);class uD extends js{constructor(e){super(),this.opts=e,gg(this,"protocol","wc"),gg(this,"version",2)}}var dD=Object.defineProperty,pD=(s,e,t)=>e in s?dD(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,gD=(s,e,t)=>pD(s,e+"",t);let fD=class extends js{constructor(e,t){super(),this.core=e,this.logger=t,gD(this,"records",new Map)}},wD=class{constructor(e,t){this.logger=e,this.core=t}};class yD extends js{constructor(e,t){super(),this.relayer=e,this.logger=t}}let mD=class extends js{constructor(e){super()}},bD=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},vD=class extends js{constructor(e,t){super(),this.relayer=e,this.logger=t}},ID=class extends js{constructor(e,t){super(),this.core=e,this.logger=t}},ED=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},AD=class{constructor(e,t){this.projectId=e,this.logger=t}},ND=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};var _D=Object.defineProperty,CD=(s,e,t)=>e in s?_D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fg=(s,e,t)=>CD(s,typeof e!="symbol"?e+"":e,t);let SD=class{constructor(e){this.opts=e,fg(this,"protocol","wc"),fg(this,"version",2)}},TD=class{constructor(e){this.client=e}};const Vi={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}},br=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),yt=ct({...br}),Lt={state:yt,subscribeKey(s,e){return Ns(yt,s,e)},showLoading(s,e={}){this._showMessage({message:s,variant:"loading",...e})},showSuccess(s){this._showMessage({message:s,variant:"success"})},showSvg(s,e){this._showMessage({message:s,svg:e})},showError(s){const e=ce.parseError(s);this._showMessage({message:e,variant:"error"})},hide(){yt.message=br.message,yt.variant=br.variant,yt.svg=br.svg,yt.open=br.open,yt.autoClose=br.autoClose},_showMessage({message:s,svg:e,variant:t="success",autoClose:i=br.autoClose}){yt.open?(yt.open=!1,setTimeout(()=>{yt.message=s,yt.variant=t,yt.svg=e,yt.open=!0,yt.autoClose=i},150)):(yt.message=s,yt.variant=t,yt.svg=e,yt.open=!0,yt.autoClose=i)}},Wo={getSIWX(){return j.state.siwx},async initializeIfEnabled(){var n;const s=j.state.siwx,e=v.getActiveCaipAddress();if(!(s&&e))return;const[t,i,r]=e.split(":");if(v.checkIfSupportedNetwork(t))try{if((await s.getSessions(`${t}:${i}`,r)).length)return;await wt.open({view:"SIWXSignMessage"})}catch(o){console.error("SIWXUtil:initializeIfEnabled",o),Ke.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await((n=Ve._getClient())==null?void 0:n.disconnect().catch(console.error)),De.reset("Connect"),Lt.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const s=j.state.siwx,e=ce.getPlainAddress(v.getActiveCaipAddress()),t=v.getActiveCaipNetwork(),i=Ve._getClient();if(!s)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!t)throw new Error("No ActiveCaipNetwork or client found");if(!i)throw new Error("No ConnectionController client found");try{const r=await s.createMessage({chainId:t.caipNetworkId,accountAddress:e}),n=r.toString();ae.getConnectorId(t.chainNamespace)===te.CONNECTOR_ID.AUTH&&De.pushTransactionStack({view:null,goBack:!1,replace:!0});const a=await i.signMessage(n);await s.addSession({data:r,message:n,signature:a}),wt.close(),Ke.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){const n=this.getSIWXEventProperties();(!wt.state.open||De.state.view==="ApproveTransaction")&&await wt.open({view:"SIWXSignMessage"}),n.isSmartAccount?Lt.showError("This application might not support Smart Accounts"):Lt.showError("Signature declined"),Ke.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:n}),console.error("SWIXUtil:requestSignMessage",r)}},async cancelSignMessage(){var s;try{const e=this.getSIWX();((s=e==null?void 0:e.getRequired)==null?void 0:s.call(e))?await Ve.disconnect():wt.close(),De.reset("Connect"),Ke.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getSessions(){const s=j.state.siwx,e=ce.getPlainAddress(v.getActiveCaipAddress()),t=v.getActiveCaipNetwork();return s&&e&&t?s.getSessions(t.caipNetworkId,e):[]},async isSIWXCloseDisabled(){var e;const s=this.getSIWX();if(s){const t=De.state.view==="ApproveTransaction",i=De.state.view==="SIWXSignMessage";if(t||i)return((e=s.getRequired)==null?void 0:e.call(s))&&(await this.getSessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:s,chains:e,methods:t}){var a,c,l;const i=Wo.getSIWX(),r=new Set(e.map(h=>h.split(":")[0]));if(!i||r.size!==1||!r.has("eip155"))return!1;const n=await i.createMessage({chainId:((a=v.getActiveCaipNetwork())==null?void 0:a.caipNetworkId)||"",accountAddress:""}),o=await s.authenticate({nonce:n.nonce,domain:n.domain,uri:n.uri,exp:n.expirationTime,iat:n.issuedAt,nbf:n.notBefore,requestId:n.requestId,version:n.version,resources:n.resources,statement:n.statement,chainId:n.chainId,methods:t,chains:[n.chainId,...e.filter(h=>h!==n.chainId)]});if(Lt.showLoading("Authenticating...",{autoClose:!1}),se.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(r)[0]),(l=o==null?void 0:o.auths)!=null&&l.length){const h=o.auths.map(u=>{const d=s.client.formatAuthMessage({request:u.p,iss:u.p.iss});return{data:{...u.p,accountAddress:u.p.iss.split(":").slice(-1).join(""),chainId:u.p.iss.split(":").slice(2,4).join(":"),uri:u.p.aud,version:u.p.version||n.version,expirationTime:u.p.exp,issuedAt:u.p.iat,notBefore:u.p.nbf},message:d,signature:u.s.s,cacao:u}});try{await i.setSessions(h),Ke.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:Wo.getSIWXEventProperties()})}catch(u){throw console.error("SIWX:universalProviderAuth - failed to set sessions",u),Ke.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:Wo.getSIWXEventProperties()}),await s.disconnect().catch(console.error),u}finally{Lt.hide()}}return!0},getSIWXEventProperties(){var s;return{network:((s=v.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||"",isSmartAccount:se.state.preferredAccountType===Vi.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const s=this.getSIWX();s&&await s.setSessions([])}},Be=ct({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),PD={state:Be,subscribe(s){return hs(Be,()=>s(Be))},setLastNetworkInView(s){Be.lastNetworkInView=s},async fetchTransactions(s,e){var t;if(!s)throw new Error("Transactions can't be fetched without an accountAddress");Be.loading=!0;try{const i=await re.fetchTransactions({account:s,cursor:Be.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:(t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId}),r=this.filterSpamTransactions(i.data),n=this.filterByConnectedChain(r),o=[...Be.transactions,...n];Be.loading=!1,e==="coinbase"?Be.coinbaseTransactions=this.groupTransactionsByYearAndMonth(Be.coinbaseTransactions,i.data):(Be.transactions=o,Be.transactionsByYear=this.groupTransactionsByYearAndMonth(Be.transactionsByYear,n)),Be.empty=o.length===0,Be.next=i.next?i.next:void 0}catch{Ke.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:s,projectId:j.state.projectId,cursor:Be.next,isSmartAccount:se.state.preferredAccountType===Vi.ACCOUNT_TYPES.SMART_ACCOUNT}}),Lt.showError("Failed to fetch transactions"),Be.loading=!1,Be.empty=!0,Be.next=void 0}},groupTransactionsByYearAndMonth(s={},e=[]){const t=s;return e.forEach(i=>{const r=new Date(i.metadata.minedAt).getFullYear(),n=new Date(i.metadata.minedAt).getMonth(),o=t[r]??{},c=(o[n]??[]).filter(l=>l.id!==i.id);t[r]={...o,[n]:[...c,i].sort((l,h)=>new Date(h.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),t},filterSpamTransactions(s){return s.filter(e=>!e.transfers.every(i=>{var r;return((r=i.nft_info)==null?void 0:r.flags.is_spam)===!0}))},filterByConnectedChain(s){var i;const e=(i=v.state.activeCaipNetwork)==null?void 0:i.caipNetworkId;return s.filter(r=>r.metadata.chain===e)},clearCursor(){Be.next=void 0},resetTransactions(){Be.transactions=[],Be.transactionsByYear={},Be.lastNetworkInView=void 0,Be.loading=!1,Be.empty=!1,Be.next=void 0}},He=ct({wcError:!1,buffering:!1,status:"disconnected"});let ln;const Ve={state:He,subscribeKey(s,e){return Ns(He,s,e)},_getClient(){return He._client},setClient(s){He._client=$r(s)},async connectWalletConnect(){var s,e,t,i;if(ce.isTelegram()||ce.isSafari()&&ce.isIos()){if(ln){await ln,ln=void 0;return}if(!ce.isPairingExpired(He==null?void 0:He.wcPairingExpiry)){const r=He.wcUri;He.wcUri=r;return}ln=(e=(s=this._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:e.call(s).catch(()=>{}),this.state.status="connecting",await ln,ln=void 0,He.wcPairingExpiry=void 0,this.state.status="connected"}else await((i=(t=this._getClient())==null?void 0:t.connectWalletConnect)==null?void 0:i.call(t))},async connectExternal(s,e,t=!0){var i,r;await((r=(i=this._getClient())==null?void 0:i.connectExternal)==null?void 0:r.call(i,s)),t&&v.setActiveNamespace(e)},async reconnectExternal(s){var t,i;await((i=(t=this._getClient())==null?void 0:t.reconnectExternal)==null?void 0:i.call(t,s));const e=s.chain||v.state.activeChain;e&&ae.setConnectorId(s.id,e)},async setPreferredAccountType(s){var t;wt.setLoading(!0,v.state.activeChain);const e=ae.getAuthConnector();e&&(await(e==null?void 0:e.provider.setPreferredAccount(s)),await this.reconnectExternal(e),wt.setLoading(!1,v.state.activeChain),Ke.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:s,network:((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)||""}}))},async signMessage(s){var e;return(e=this._getClient())==null?void 0:e.signMessage(s)},parseUnits(s,e){var t;return(t=this._getClient())==null?void 0:t.parseUnits(s,e)},formatUnits(s,e){var t;return(t=this._getClient())==null?void 0:t.formatUnits(s,e)},async sendTransaction(s){var e;return(e=this._getClient())==null?void 0:e.sendTransaction(s)},async getCapabilities(s){var e;return(e=this._getClient())==null?void 0:e.getCapabilities(s)},async grantPermissions(s){var e;return(e=this._getClient())==null?void 0:e.grantPermissions(s)},async walletGetAssets(s){var e;return((e=this._getClient())==null?void 0:e.walletGetAssets(s))??{}},async estimateGas(s){var e;return(e=this._getClient())==null?void 0:e.estimateGas(s)},async writeContract(s){var e;return(e=this._getClient())==null?void 0:e.writeContract(s)},async getEnsAddress(s){var e;return(e=this._getClient())==null?void 0:e.getEnsAddress(s)},async getEnsAvatar(s){var e;return(e=this._getClient())==null?void 0:e.getEnsAvatar(s)},checkInstalled(s){var e,t;return((t=(e=this._getClient())==null?void 0:e.checkInstalled)==null?void 0:t.call(e,s))||!1},resetWcConnection(){He.wcUri=void 0,He.wcPairingExpiry=void 0,He.wcLinking=void 0,He.recentWallet=void 0,He.status="disconnected",PD.resetTransactions(),J.deleteWalletConnectDeepLink()},resetUri(){He.wcUri=void 0,He.wcPairingExpiry=void 0},finalizeWcConnection(){var t,i;const{wcLinking:s,recentWallet:e}=Ve.state;s&&J.setWalletConnectDeepLink(s),e&&J.setAppKitRecent(e),Ke.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:s?"mobile":"qrcode",name:((i=(t=De.state.data)==null?void 0:t.wallet)==null?void 0:i.name)||"Unknown"}})},setWcBasic(s){He.wcBasic=s},setUri(s){He.wcUri=s,He.wcPairingExpiry=ce.getPairingExpiry()},setWcLinking(s){He.wcLinking=s},setWcError(s){He.wcError=s,He.buffering=!1},setRecentWallet(s){He.recentWallet=s},setBuffering(s){He.buffering=s},setStatus(s){He.status=s},async disconnect(s){try{wt.setLoading(!0,s),await Wo.clearSessions(),await v.disconnect(s),wt.setLoading(!1,s),ae.setFilterByNamespace(void 0)}catch{throw new Error("Failed to disconnect")}}},Co=ct({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),Oi={state:Co,subscribe(s){return hs(Co,()=>s(Co))},set(s){Object.assign(Co,{...Co,...s})}},Bl={createBalance(s,e){const t={name:s.metadata.name||"",symbol:s.metadata.symbol||"",decimals:s.metadata.decimals||0,value:s.metadata.value||0,price:s.metadata.price||0,iconUrl:s.metadata.iconUrl||""};return{name:t.name,symbol:t.symbol,chainId:e,address:s.address==="native"?void 0:this.convertAddressToCAIP10Address(s.address,e),value:t.value,price:t.price,quantity:{decimals:t.decimals.toString(),numeric:this.convertHexToBalance({hex:s.balance,decimals:t.decimals})},iconUrl:t.iconUrl}},convertHexToBalance({hex:s,decimals:e}){return t0(BigInt(s),e)},convertAddressToCAIP10Address(s,e){return`${e}:${s}`},createCAIP2ChainId(s,e){return`${e}:${parseInt(s,16)}`},getChainIdHexFromCAIP2ChainId(s){const e=s.split(":");if(e.length<2||!e[1])return"0x0";const t=e[1],i=parseInt(t,10);return isNaN(i)?"0x0":`0x${i.toString(16)}`},isWalletGetAssetsResponse(s){return typeof s!="object"||s===null?!1:Object.values(s).every(e=>Array.isArray(e)&&e.every(t=>this.isValidAsset(t)))},isValidAsset(s){return typeof s=="object"&&s!==null&&typeof s.address=="string"&&typeof s.balance=="string"&&(s.type==="ERC20"||s.type==="NATIVE")&&typeof s.metadata=="object"&&s.metadata!==null&&typeof s.metadata.name=="string"&&typeof s.metadata.symbol=="string"&&typeof s.metadata.decimals=="number"&&typeof s.metadata.price=="number"&&typeof s.metadata.iconUrl=="string"}},wg={async getMyTokensWithBalance(s){const e=se.state.address,t=v.state.activeCaipNetwork;if(!e||!t)return[];if(t.chainNamespace==="eip155"){const r=await this.getEIP155Balances(e,t);if(r)return this.filterLowQualityTokens(r)}const i=await re.getBalance(e,t.caipNetworkId,s);return this.filterLowQualityTokens(i.balances)},async getEIP155Balances(s,e){var t,i;try{const r=Bl.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),n=await Ve.getCapabilities(s);if(!((i=(t=n==null?void 0:n[r])==null?void 0:t.assetDiscovery)!=null&&i.supported))return null;const o=await Ve.walletGetAssets({account:s,chainFilter:[r]});return Bl.isWalletGetAssetsResponse(o)?(o[r]||[]).map(c=>Bl.createBalance(c,e.caipNetworkId)):null}catch{return null}},filterLowQualityTokens(s){return s.filter(e=>e.quantity.decimals!=="0")},mapBalancesToSwapTokens(s){return(s==null?void 0:s.map(e=>({...e,address:e!=null&&e.address?e.address:v.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]}},ye=ct({tokenBalances:[],loading:!1}),yg={state:ye,subscribe(s){return hs(ye,()=>s(ye))},subscribeKey(s,e){return Ns(ye,s,e)},setToken(s){s&&(ye.token=$r(s))},setTokenAmount(s){ye.sendTokenAmount=s},setReceiverAddress(s){ye.receiverAddress=s},setReceiverProfileImageUrl(s){ye.receiverProfileImageUrl=s},setReceiverProfileName(s){ye.receiverProfileName=s},setGasPrice(s){ye.gasPrice=s},setGasPriceInUsd(s){ye.gasPriceInUSD=s},setNetworkBalanceInUsd(s){ye.networkBalanceInUSD=s},setLoading(s){ye.loading=s},sendToken(){var s;switch((s=v.state.activeCaipNetwork)==null?void 0:s.chainNamespace){case"eip155":this.sendEvmToken();return;case"solana":this.sendSolanaToken();return;default:throw new Error("Unsupported chain")}},sendEvmToken(){var s,e,t,i,r;(s=this.state.token)!=null&&s.address&&this.state.sendTokenAmount&&this.state.receiverAddress?(Ke.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:se.state.preferredAccountType===Vi.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token.address,amount:this.state.sendTokenAmount,network:((e=v.state.activeCaipNetwork)==null?void 0:e.caipNetworkId)||""}}),this.sendERC20Token({receiverAddress:this.state.receiverAddress,tokenAddress:this.state.token.address,sendTokenAmount:this.state.sendTokenAmount,decimals:this.state.token.quantity.decimals})):this.state.receiverAddress&&this.state.sendTokenAmount&&this.state.gasPrice&&((t=this.state.token)!=null&&t.quantity.decimals)&&(Ke.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:se.state.preferredAccountType===Vi.ACCOUNT_TYPES.SMART_ACCOUNT,token:(i=this.state.token)==null?void 0:i.symbol,amount:this.state.sendTokenAmount,network:((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||""}}),this.sendNativeToken({receiverAddress:this.state.receiverAddress,sendTokenAmount:this.state.sendTokenAmount,gasPrice:this.state.gasPrice,decimals:this.state.token.quantity.decimals}))},async fetchTokenBalance(s){var n,o;ye.loading=!0;const e=(n=v.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,t=(o=v.state.activeCaipNetwork)==null?void 0:o.chainNamespace,i=v.state.activeCaipAddress,r=i?ce.getPlainAddress(i):void 0;if(ye.lastRetry&&!ce.isAllowedRetry(ye.lastRetry,30*ls.ONE_SEC_MS))return ye.loading=!1,[];try{if(r&&e&&t){const a=await wg.getMyTokensWithBalance();return ye.tokenBalances=a,ye.lastRetry=void 0,a}}catch(a){ye.lastRetry=Date.now(),s==null||s(a),Lt.showError("Token Balance Unavailable")}finally{ye.loading=!1}return[]},fetchNetworkBalance(){if(ye.tokenBalances.length===0)return;const s=wg.mapBalancesToSwapTokens(ye.tokenBalances);if(!s)return;const e=s.find(t=>t.address===v.getActiveNetworkTokenAddress());e&&(ye.networkBalanceInUSD=e?Ka.multiply(e.quantity.numeric,e.price).toString():"0")},isInsufficientNetworkTokenForGas(s,e){const t=e||"0";return Ka.bigNumber(s).eq(0)?!0:Ka.bigNumber(Ka.bigNumber(t)).gt(s)},hasInsufficientGasFunds(){let s=!0;return se.state.preferredAccountType===Vi.ACCOUNT_TYPES.SMART_ACCOUNT?s=!1:ye.networkBalanceInUSD&&(s=this.isInsufficientNetworkTokenForGas(ye.networkBalanceInUSD,ye.gasPriceInUSD)),s},async sendNativeToken(s){var n,o,a,c;De.pushTransactionStack({view:"Account",goBack:!1});const e=s.receiverAddress,t=se.state.address,i=Ve.parseUnits(s.sendTokenAmount.toString(),Number(s.decimals)),r="0x";try{await Ve.sendTransaction({chainNamespace:"eip155",to:e,address:t,data:r,value:i??BigInt(0),gasPrice:s.gasPrice}),Lt.showSuccess("Transaction started"),Ke.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:se.state.preferredAccountType===Vi.ACCOUNT_TYPES.SMART_ACCOUNT,token:((n=this.state.token)==null?void 0:n.symbol)||"",amount:s.sendTokenAmount,network:((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)||""}}),this.resetSend()}catch(l){console.error("SendController:sendERC20Token - failed to send native token",l);const h=l instanceof Error?l.message:"Unknown error";Ke.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:h,isSmartAccount:se.state.preferredAccountType===Vi.ACCOUNT_TYPES.SMART_ACCOUNT,token:((a=this.state.token)==null?void 0:a.symbol)||"",amount:s.sendTokenAmount,network:((c=v.state.activeCaipNetwork)==null?void 0:c.caipNetworkId)||""}}),Lt.showError("Something went wrong")}},async sendERC20Token(s){var t,i;De.pushTransactionStack({view:"Account",goBack:!1});const e=Ve.parseUnits(s.sendTokenAmount.toString(),Number(s.decimals));try{if(se.state.address&&s.sendTokenAmount&&s.receiverAddress&&s.tokenAddress){const r=ce.getPlainAddress(s.tokenAddress);await Ve.writeContract({fromAddress:se.state.address,tokenAddress:r,args:[s.receiverAddress,e??BigInt(0)],method:"transfer",abi:Jx.getERC20Abi(r),chainNamespace:"eip155"}),Lt.showSuccess("Transaction started"),this.resetSend()}}catch(r){console.error("SendController:sendERC20Token - failed to send erc20 token",r);const n=r instanceof Error?r.message:"Unknown error";Ke.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:n,isSmartAccount:se.state.preferredAccountType===Vi.ACCOUNT_TYPES.SMART_ACCOUNT,token:((t=this.state.token)==null?void 0:t.symbol)||"",amount:s.sendTokenAmount,network:((i=v.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||""}}),Lt.showError("Something went wrong")}},sendSolanaToken(){if(!this.state.sendTokenAmount||!this.state.receiverAddress){Lt.showError("Please enter a valid amount and receiver address");return}De.pushTransactionStack({view:"Account",goBack:!1}),Ve.sendTransaction({chainNamespace:"solana",to:this.state.receiverAddress,value:this.state.sendTokenAmount}).then(()=>{this.resetSend(),se.fetchTokenBalance()}).catch(s=>{Lt.showError("Failed to send transaction. Please try again."),console.error("SendController:sendToken - failed to send solana transaction",s)})},resetSend(){ye.token=void 0,ye.sendTokenAmount=void 0,ye.receiverAddress=void 0,ye.receiverProfileImageUrl=void 0,ye.receiverProfileName=void 0,ye.loading=!1,ye.tokenBalances=[]}},Hl={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},Ya={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},z=ct({chains:e0(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),v={state:z,subscribe(s){return hs(z,()=>{s(z)})},subscribeKey(s,e){return Ns(z,s,e)},subscribeChainProp(s,e,t){let i;return hs(z.chains,()=>{var n;const r=t||z.activeChain;if(r){const o=(n=z.chains.get(r))==null?void 0:n[s];i!==o&&(i=o,e(o))}})},initialize(s,e,t){const{chainId:i,namespace:r}=J.getActiveNetworkProps(),n=e==null?void 0:e.find(l=>l.id.toString()===(i==null?void 0:i.toString())),a=s.find(l=>(l==null?void 0:l.namespace)===r)||(s==null?void 0:s[0]),c=new Set([...(e==null?void 0:e.map(l=>l.chainNamespace))??[]]);((s==null?void 0:s.length)===0||!a)&&(z.noAdapters=!0),z.noAdapters||(z.activeChain=a==null?void 0:a.namespace,z.activeCaipNetwork=n,this.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:n}),z.activeChain&&Oi.set({activeChain:a==null?void 0:a.namespace})),c.forEach(l=>{const h=e==null?void 0:e.filter(u=>u.chainNamespace===l);v.state.chains.set(l,{namespace:l,networkState:ct({...Ya,caipNetwork:h==null?void 0:h[0]}),accountState:ct(Hl),caipNetworks:h??[],...t}),this.setRequestedCaipNetworks(h??[],l)})},removeAdapter(s){var e,t;if(z.activeChain===s){const i=Array.from(z.chains.entries()).find(([r])=>r!==s);if(i){const r=(t=(e=i[1])==null?void 0:e.caipNetworks)==null?void 0:t[0];r&&this.setActiveCaipNetwork(r)}}z.chains.delete(s)},addAdapter(s,{networkControllerClient:e,connectionControllerClient:t},i){z.chains.set(s.namespace,{namespace:s.namespace,networkState:{...Ya,caipNetwork:i[0]},accountState:Hl,caipNetworks:i,connectionControllerClient:t,networkControllerClient:e}),this.setRequestedCaipNetworks((i==null?void 0:i.filter(r=>r.chainNamespace===s.namespace))??[],s.namespace)},addNetwork(s){var t;const e=z.chains.get(s.chainNamespace);if(e){const i=[...e.caipNetworks||[]];(t=e.caipNetworks)!=null&&t.find(r=>r.id===s.id)||i.push(s),z.chains.set(s.chainNamespace,{...e,caipNetworks:i}),this.setRequestedCaipNetworks(i,s.chainNamespace)}},removeNetwork(s,e){var i,r,n;const t=z.chains.get(s);if(t){const o=((i=z.activeCaipNetwork)==null?void 0:i.id)===e,a=[...((r=t.caipNetworks)==null?void 0:r.filter(c=>c.id!==e))||[]];o&&((n=t==null?void 0:t.caipNetworks)!=null&&n[0])&&this.setActiveCaipNetwork(t.caipNetworks[0]),z.chains.set(s,{...t,caipNetworks:a}),this.setRequestedCaipNetworks(a||[],s)}},setAdapterNetworkState(s,e){const t=z.chains.get(s);t&&(t.networkState={...t.networkState||Ya,...e},z.chains.set(s,t))},setChainAccountData(s,e,t=!0){if(!s)throw new Error("Chain is required to update chain account data");const i=z.chains.get(s);if(i){const r={...i.accountState||Hl,...e};z.chains.set(s,{...i,accountState:r}),(z.chains.size===1||z.activeChain===s)&&(e.caipAddress&&(z.activeCaipAddress=e.caipAddress),se.replaceState(r))}},setChainNetworkData(s,e){if(!s)return;const t=z.chains.get(s);if(t){const i={...t.networkState||Ya,...e};z.chains.set(s,{...t,networkState:i})}},setAccountProp(s,e,t,i=!0){this.setChainAccountData(t,{[s]:e},i),s==="status"&&e==="disconnected"&&t&&ae.removeConnectorId(t)},setActiveNamespace(s){var i,r;z.activeChain=s;const e=s?z.chains.get(s):void 0,t=(i=e==null?void 0:e.networkState)==null?void 0:i.caipNetwork;t!=null&&t.id&&s&&(z.activeCaipAddress=(r=e==null?void 0:e.accountState)==null?void 0:r.caipAddress,z.activeCaipNetwork=t,this.setChainNetworkData(s,{caipNetwork:t}),J.setActiveCaipNetworkId(t==null?void 0:t.caipNetworkId),Oi.set({activeChain:s,selectedNetworkId:t==null?void 0:t.caipNetworkId}))},setActiveCaipNetwork(s){var i,r,n;if(!s)return;z.activeChain!==s.chainNamespace&&this.setIsSwitchingNamespace(!0);const e=z.chains.get(s.chainNamespace);z.activeChain=s.chainNamespace,z.activeCaipNetwork=s,this.setChainNetworkData(s.chainNamespace,{caipNetwork:s}),(i=e==null?void 0:e.accountState)!=null&&i.address?z.activeCaipAddress=`${s.chainNamespace}:${s.id}:${(r=e==null?void 0:e.accountState)==null?void 0:r.address}`:z.activeCaipAddress=void 0,this.setAccountProp("caipAddress",z.activeCaipAddress,s.chainNamespace),e&&se.replaceState(e.accountState),yg.resetSend(),Oi.set({activeChain:z.activeChain,selectedNetworkId:(n=z.activeCaipNetwork)==null?void 0:n.caipNetworkId}),J.setActiveCaipNetworkId(s.caipNetworkId),!this.checkIfSupportedNetwork(s.chainNamespace)&&j.state.enableNetworkSwitch&&!j.state.allowUnsupportedChain&&!Ve.state.wcBasic&&this.showUnsupportedChainUI()},addCaipNetwork(s){var t;if(!s)return;const e=z.chains.get(s.chainNamespace);e&&((t=e==null?void 0:e.caipNetworks)==null||t.push(s))},async switchActiveNamespace(s){var r;if(!s)return;const e=s!==v.state.activeChain,t=(r=v.getNetworkData(s))==null?void 0:r.caipNetwork,i=v.getCaipNetworkByNamespace(s,t==null?void 0:t.id);e&&i&&await v.switchActiveNetwork(i)},async switchActiveNetwork(s){var r;const e=v.state.chains.get(v.state.activeChain);!((r=e==null?void 0:e.caipNetworks)!=null&&r.some(n=>{var o;return n.id===((o=z.activeCaipNetwork)==null?void 0:o.id)}))&&De.goBack();const i=this.getNetworkControllerClient(s.chainNamespace);i&&(await i.switchCaipNetwork(s),Ke.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:s.caipNetworkId}}))},getNetworkControllerClient(s){const e=s||z.activeChain,t=z.chains.get(e);if(!t)throw new Error("Chain adapter not found");if(!t.networkControllerClient)throw new Error("NetworkController client not set");return t.networkControllerClient},getConnectionControllerClient(s){const e=s||z.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const t=z.chains.get(e);if(!(t!=null&&t.connectionControllerClient))throw new Error("ConnectionController client not set");return t.connectionControllerClient},getAccountProp(s,e){var r;let t=z.activeChain;if(e&&(t=e),!t)return;const i=(r=z.chains.get(t))==null?void 0:r.accountState;if(i)return i[s]},getNetworkProp(s,e){var i;const t=(i=z.chains.get(e))==null?void 0:i.networkState;if(t)return t[s]},getRequestedCaipNetworks(s){const e=z.chains.get(s),{approvedCaipNetworkIds:t=[],requestedCaipNetworks:i=[]}=(e==null?void 0:e.networkState)||{};return ce.sortRequestedNetworks(t,i)},getAllRequestedCaipNetworks(){const s=[];return z.chains.forEach(e=>{const t=this.getRequestedCaipNetworks(e.namespace);s.push(...t)}),s},setRequestedCaipNetworks(s,e){this.setAdapterNetworkState(e,{requestedCaipNetworks:s})},getAllApprovedCaipNetworkIds(){const s=[];return z.chains.forEach(e=>{const t=this.getApprovedCaipNetworkIds(e.namespace);s.push(...t)}),s},getActiveCaipNetwork(){return z.activeCaipNetwork},getActiveCaipAddress(){return z.activeCaipAddress},getApprovedCaipNetworkIds(s){var i;const e=z.chains.get(s);return((i=e==null?void 0:e.networkState)==null?void 0:i.approvedCaipNetworkIds)||[]},async setApprovedCaipNetworksData(s){const e=this.getNetworkControllerClient(),t=await(e==null?void 0:e.getApprovedCaipNetworksData());this.setAdapterNetworkState(s,{approvedCaipNetworkIds:t==null?void 0:t.approvedCaipNetworkIds,supportsAllNetworks:t==null?void 0:t.supportsAllNetworks})},checkIfSupportedNetwork(s,e){const t=e||z.activeCaipNetwork,i=this.getRequestedCaipNetworks(s);return i.length?i==null?void 0:i.some(r=>r.id===(t==null?void 0:t.id)):!0},checkIfSupportedChainId(s){if(!z.activeChain)return!0;const e=this.getRequestedCaipNetworks(z.activeChain);return e==null?void 0:e.some(t=>t.id===s)},setSmartAccountEnabledNetworks(s,e){this.setAdapterNetworkState(e,{smartAccountEnabledNetworks:s})},checkIfSmartAccountEnabled(){var i;const s=rm.caipNetworkIdToNumber((i=z.activeCaipNetwork)==null?void 0:i.caipNetworkId),e=z.activeChain;if(!e||!s)return!1;const t=this.getNetworkProp("smartAccountEnabledNetworks",e);return!!(t!=null&&t.includes(Number(s)))},getActiveNetworkTokenAddress(){var i,r;const s=((i=z.activeCaipNetwork)==null?void 0:i.chainNamespace)||"eip155",e=((r=z.activeCaipNetwork)==null?void 0:r.id)||1,t=ls.NATIVE_TOKEN_ADDRESS[s];return`${s}:${e}:${t}`},showUnsupportedChainUI(){wt.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const s=z.activeCaipNetwork;return!!(s!=null&&s.chainNamespace&&ls.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(s.chainNamespace))},resetNetwork(s){this.setAdapterNetworkState(s,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(s){const e=s;if(!e)throw new Error("Chain is required to set account prop");z.activeCaipAddress=void 0,this.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),ae.removeConnectorId(e)},async disconnect(s){const e=cD(s);try{yg.resetSend();const t=await Promise.allSettled(e.map(async([r,n])=>{var o;try{const{caipAddress:a}=this.getAccountData(r)||{};a&&((o=n.connectionControllerClient)!=null&&o.disconnect)&&await n.connectionControllerClient.disconnect(r),this.resetAccount(r),this.resetNetwork(r)}catch(a){throw new Error(`Failed to disconnect chain ${r}: ${a.message}`)}}));Ve.resetWcConnection();const i=t.filter(r=>r.status==="rejected");if(i.length>0)throw new Error(i.map(r=>r.reason.message).join(", "));J.deleteConnectedSocialProvider(),s?ae.removeConnectorId(s):ae.resetConnectorIds(),Ke.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:s||"all"}})}catch(t){console.error(t.message||"Failed to disconnect chains"),Ke.sendEvent({type:"track",event:"DISCONNECT_ERROR",properties:{message:t.message||"Failed to disconnect chains"}})}},setIsSwitchingNamespace(s){z.isSwitchingNamespace=s},getFirstCaipNetworkSupportsAuthConnector(){var t,i;const s=[];let e;if(z.chains.forEach(r=>{te.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===r.namespace)&&r.namespace&&s.push(r.namespace)}),s.length>0){const r=s[0];return e=r?(i=(t=z.chains.get(r))==null?void 0:t.caipNetworks)==null?void 0:i[0]:void 0,e}},getAccountData(s){var e;return s?(e=v.state.chains.get(s))==null?void 0:e.accountState:se.state},getNetworkData(s){var t;const e=s||z.activeChain;if(e)return(t=v.state.chains.get(e))==null?void 0:t.networkState},getCaipNetworkByNamespace(s,e){var r,n,o;if(!s)return;const t=v.state.chains.get(s),i=(r=t==null?void 0:t.caipNetworks)==null?void 0:r.find(a=>a.id===e);return i||((n=t==null?void 0:t.networkState)==null?void 0:n.caipNetwork)||((o=t==null?void 0:t.caipNetworks)==null?void 0:o[0])},getRequestedCaipNetworkIds(){const s=ae.state.filterByNamespace;return(s?[z.chains.get(s)]:Array.from(z.chains.values())).flatMap(t=>(t==null?void 0:t.caipNetworks)||[]).map(t=>t.caipNetworkId)}},$D={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"}]}]},am=ce.getBlockchainApiUrl(),gs=ct({clientId:null,api:new il({baseUrl:am,clientId:null}),supportedChains:{http:[],ws:[]}}),re={state:gs,async get(s){const{st:e,sv:t}=re.getSdkProperties(),i=j.state.projectId,r={...s.params||{},st:e,sv:t,projectId:i};return gs.api.get({...s,params:r})},getSdkProperties(){const{sdkType:s,sdkVersion:e}=j.state;return{st:s||"unknown",sv:e||"unknown"}},async isNetworkSupported(s){if(!s)return!1;try{gs.supportedChains.http.length||await re.getSupportedNetworks()}catch{return!1}return gs.supportedChains.http.includes(s)},async getSupportedNetworks(){const s=await re.get({path:"v1/supported-chains"});return gs.supportedChains=s,s},async fetchIdentity({address:s,caipNetworkId:e}){if(!await re.isNetworkSupported(e))return{avatar:"",name:""};const i=J.getIdentityFromCacheForAddress(s);if(i)return i;const r=await re.get({path:`/v1/identity/${s}`,params:{sender:v.state.activeCaipAddress?ce.getPlainAddress(v.state.activeCaipAddress):void 0}});return J.updateIdentityCache({address:s,identity:r,timestamp:Date.now()}),r},async fetchTransactions({account:s,cursor:e,onramp:t,signal:i,cache:r,chainId:n}){var a;return await re.isNetworkSupported((a=v.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?re.get({path:`/v1/account/${s}/history`,params:{cursor:e,onramp:t,chainId:n},signal:i,cache:r}):{data:[],next:void 0}},async fetchSwapQuote({amount:s,userAddress:e,from:t,to:i,gasPrice:r}){var o;return await re.isNetworkSupported((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?re.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:s,userAddress:e,from:t,to:i,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:s}){var t;return await re.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?re.get({path:"/v1/convert/tokens",params:{chainId:s}}):{tokens:[]}},async fetchTokenPrice({addresses:s}){var t;return await re.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?gs.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:s,projectId:j.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:s,userAddress:e}){var i;return await re.isNetworkSupported((i=v.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?re.get({path:"/v1/convert/allowance",params:{tokenAddress:s,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:s}){var r;const{st:e,sv:t}=re.getSdkProperties();if(!await re.isNetworkSupported((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))throw new Error("Network not supported for Gas Price");return re.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:s,st:e,sv:t}})},async generateSwapCalldata({amount:s,from:e,to:t,userAddress:i,disableEstimate:r}){var o;if(!await re.isNetworkSupported((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return gs.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:s,eip155:{slippage:ls.CONVERT_SLIPPAGE_TOLERANCE},projectId:j.state.projectId,from:e,to:t,userAddress:i,disableEstimate:r}})},async generateApproveCalldata({from:s,to:e,userAddress:t}){var o;const{st:i,sv:r}=re.getSdkProperties();if(!await re.isNetworkSupported((o=v.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return re.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:t,from:s,to:e,st:i,sv:r}})},async getBalance(s,e,t){var l;const{st:i,sv:r}=re.getSdkProperties();if(!await re.isNetworkSupported((l=v.state.activeCaipNetwork)==null?void 0:l.caipNetworkId))return Lt.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${s}`,a=J.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await re.get({path:`/v1/account/${s}/balance`,params:{currency:"usd",chainId:e,forceUpdate:t,st:i,sv:r}});return J.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(s){var t;return await re.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?re.get({path:`/v1/profile/account/${s}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:s}){var t;return await re.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?re.get({path:`/v1/profile/reverse/${s}`,params:{sender:se.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(s){var t;return await re.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?re.get({path:`/v1/profile/suggestions/${s}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:s,address:e,message:t,signature:i}){var n;return await re.isNetworkSupported((n=v.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?gs.api.post({path:"/v1/profile/account",body:{coin_type:s,address:e,message:t,signature:i},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:s,partnerUserId:e,defaultNetwork:t,purchaseAmount:i,paymentAmount:r}){var a;return await re.isNetworkSupported((a=v.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await gs.api.post({path:"/v1/generators/onrampurl",params:{projectId:j.state.projectId},body:{destinationWallets:s,defaultNetwork:t,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:i,presetFiatAmount:r}})).url:""},async getOnrampOptions(){var e;if(!await re.isNetworkSupported((e=v.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await re.get({path:"/v1/onramp/options"})}catch{return $D}},async getOnrampQuote({purchaseCurrency:s,paymentCurrency:e,amount:t,network:i}){var r;try{return await re.isNetworkSupported((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?await gs.api.post({path:"/v1/onramp/quote",params:{projectId:j.state.projectId},body:{purchaseCurrency:s,paymentCurrency:e,amount:t,network:i}}):null}catch{return{coinbaseFee:{amount:t,currency:e.id},networkFee:{amount:t,currency:e.id},paymentSubtotal:{amount:t,currency:e.id},paymentTotal:{amount:t,currency:e.id},purchaseAmount:{amount:t,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(s){var t;return await re.isNetworkSupported((t=v.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?re.get({path:`/v1/sessions/${s}`}):[]},async revokeSmartSession(s,e,t){var r;return await re.isNetworkSupported((r=v.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?gs.api.post({path:`/v1/sessions/${s}/revoke`,params:{projectId:j.state.projectId},body:{pci:e,signature:t}}):{success:!1}},setClientId(s){gs.clientId=s,gs.api=new il({baseUrl:am,clientId:s})}},ni=ct({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),se={state:ni,replaceState(s){s&&Object.assign(ni,$r(s))},subscribe(s){return v.subscribeChainProp("accountState",e=>{if(e)return s(e)})},subscribeKey(s,e,t){let i;return v.subscribeChainProp("accountState",r=>{if(r){const n=r[s];i!==n&&(i=n,e(n))}},t)},setStatus(s,e){v.setAccountProp("status",s,e)},getCaipAddress(s){return v.getAccountProp("caipAddress",s)},setCaipAddress(s,e){const t=s?ce.getPlainAddress(s):void 0;e===v.state.activeChain&&(v.state.activeCaipAddress=s),v.setAccountProp("caipAddress",s,e),v.setAccountProp("address",t,e)},setBalance(s,e,t){v.setAccountProp("balance",s,t),v.setAccountProp("balanceSymbol",e,t)},setProfileName(s,e){v.setAccountProp("profileName",s,e)},setProfileImage(s,e){v.setAccountProp("profileImage",s,e)},setUser(s,e){v.setAccountProp("user",s,e)},setAddressExplorerUrl(s,e){v.setAccountProp("addressExplorerUrl",s,e)},setSmartAccountDeployed(s,e){v.setAccountProp("smartAccountDeployed",s,e)},setCurrentTab(s){v.setAccountProp("currentTab",s,v.state.activeChain)},setTokenBalance(s,e){s&&v.setAccountProp("tokenBalance",s,e)},setShouldUpdateToAddress(s,e){v.setAccountProp("shouldUpdateToAddress",s,e)},setAllAccounts(s,e){v.setAccountProp("allAccounts",s,e)},addAddressLabel(s,e,t){const i=v.getAccountProp("addressLabels",t)||new Map;i.set(s,e),v.setAccountProp("addressLabels",i,t)},removeAddressLabel(s,e){const t=v.getAccountProp("addressLabels",e)||new Map;t.delete(s),v.setAccountProp("addressLabels",t,e)},setConnectedWalletInfo(s,e){v.setAccountProp("connectedWalletInfo",s,e,!1)},setPreferredAccountType(s,e){v.setAccountProp("preferredAccountType",s,e)},setSocialProvider(s,e){s&&v.setAccountProp("socialProvider",s,e)},setSocialWindow(s,e){v.setAccountProp("socialWindow",s?$r(s):void 0,e)},setFarcasterUrl(s,e){v.setAccountProp("farcasterUrl",s,e)},async fetchTokenBalance(s){var n,o;ni.balanceLoading=!0;const e=(n=v.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,t=(o=v.state.activeCaipNetwork)==null?void 0:o.chainNamespace,i=v.state.activeCaipAddress,r=i?ce.getPlainAddress(i):void 0;if(ni.lastRetry&&!ce.isAllowedRetry(ni.lastRetry,30*ls.ONE_SEC_MS))return ni.balanceLoading=!1,[];try{if(r&&e&&t){const c=(await re.getBalance(r,e)).balances.filter(l=>l.quantity.decimals!=="0");return this.setTokenBalance(c,t),ni.lastRetry=void 0,ni.balanceLoading=!1,c}}catch(a){ni.lastRetry=Date.now(),s==null||s(a),Lt.showError("Token Balance Unavailable")}finally{ni.balanceLoading=!1}return[]},resetAccount(s){v.resetAccount(s)}},ss=ct({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),wt={state:ss,subscribe(s){return hs(ss,()=>s(ss))},subscribeKey(s,e){return Ns(ss,s,e)},async open(s){var r;const e=se.state.status==="connected";Ve.state.wcBasic?le.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await le.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),s!=null&&s.namespace?(await v.switchActiveNamespace(s.namespace),wt.setLoading(!0,s.namespace)):wt.setLoading(!0),ae.setFilterByNamespace(s==null?void 0:s.namespace);const t=(r=v.getAccountData(s==null?void 0:s.namespace))==null?void 0:r.caipAddress;v.state.noAdapters&&!t?ce.isMobile()?De.reset("AllWallets"):De.reset("ConnectingWalletConnectBasic"):s!=null&&s.view?De.reset(s.view):t?De.reset("Account"):De.reset("Connect"),ss.open=!0,Oi.set({open:!0}),Ke.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!t}})},close(){const s=j.state.enableEmbedded,e=!!v.state.activeCaipAddress;ss.open&&Ke.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),ss.open=!1,wt.clearLoading(),s?e?De.replace("Account"):De.push("Connect"):Oi.set({open:!1}),Ve.resetUri()},setLoading(s,e){e&&ss.loadingNamespaceMap.set(e,s),ss.loading=s,Oi.set({loading:s})},clearLoading(){ss.loadingNamespaceMap.clear(),ss.loading=!1},shake(){ss.shake||(ss.shake=!0,setTimeout(()=>{ss.shake=!1},500))}},mg=2147483648,MD={convertEVMChainIdToCoinType(s){if(s>=mg)throw new Error("Invalid chainId");return(mg|s)>>>0}},Ts=ct({suggestions:[],loading:!1}),cm={state:Ts,subscribe(s){return hs(Ts,()=>s(Ts))},subscribeKey(s,e){return Ns(Ts,s,e)},async resolveName(s){var e,t;try{return await re.lookupEnsName(s)}catch(i){const r=i;throw new Error(((t=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:t.description)||"Error resolving name")}},async isNameRegistered(s){try{return await re.lookupEnsName(s),!0}catch{return!1}},async getSuggestions(s){try{Ts.loading=!0,Ts.suggestions=[];const e=await re.getEnsNameSuggestions(s);return Ts.suggestions=e.suggestions.map(t=>({...t,name:t.name}))||[],Ts.suggestions}catch(e){const t=this.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(t)}finally{Ts.loading=!1}},async getNamesForAddress(s){try{if(!v.state.activeCaipNetwork)return[];const t=J.getEnsFromCacheForAddress(s);if(t)return t;const i=await re.reverseLookupEnsName({address:s});return J.updateEnsCache({address:s,ens:i,timestamp:Date.now()}),i}catch(e){const t=this.parseEnsApiError(e,"Error fetching names for address");throw new Error(t)}},async registerName(s){const e=v.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const t=se.state.address,i=ae.getAuthConnector();if(!t||!i)throw new Error("Address or auth connector not found");Ts.loading=!0;try{const r=JSON.stringify({name:s,attributes:{},timestamp:Math.floor(Date.now()/1e3)});De.pushTransactionStack({view:"RegisterAccountNameSuccess",goBack:!1,replace:!0,onCancel(){Ts.loading=!1}});const n=await Ve.signMessage(r),o=e.id;if(!o)throw new Error("Network not found");const a=MD.convertEVMChainIdToCoinType(Number(o));await re.registerEnsName({coinType:a,address:t,signature:n,message:r}),se.setProfileName(s,e.chainNamespace),De.replace("RegisterAccountNameSuccess")}catch(r){const n=this.parseEnsApiError(r,`Error registering name ${s}`);throw De.replace("RegisterAccountName"),new Error(n)}finally{Ts.loading=!1}},validateName(s){return/^[a-zA-Z0-9-]{4,}$/u.test(s)},parseEnsApiError(s,e){var i,r;const t=s;return((r=(i=t==null?void 0:t.reasons)==null?void 0:i[0])==null?void 0:r.description)||e}};function na(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function bg(s){return na(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const lm="2.23.2";let So={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${lm}`};class Dr extends Error{constructor(e,t={}){var a;const i=(()=>{var c;return t.cause instanceof Dr?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),r=t.cause instanceof Dr&&t.cause.docsPath||t.docsPath,n=(a=So.getDocsUrl)==null?void 0:a.call(So,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...So.version?[`Version: ${So.version}`]:[]].join(`
|
|
13
|
-
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=lm}walk(e){return hm(this,e)}}function hm(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?hm(s.cause,e):e?null:s}class um extends Dr{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function ro(s,{dir:e,size:t=32}={}){return typeof s=="string"?OD(s,{dir:e,size:t}):xD(s,{dir:e,size:t})}function OD(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new um({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function xD(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new um({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}class DD extends Dr{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class kD extends Dr{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function no(s,{size:e}){if(bg(s)>e)throw new kD({givenSize:bg(s),maxSize:e})}function Lh(s,e={}){const{signed:t}=e;e.size&&no(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function jD(s,e={}){return Number(Lh(s,e))}const RD=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function zh(s,e={}){return typeof s=="number"||typeof s=="bigint"?pm(s,e):typeof s=="string"?zD(s,e):typeof s=="boolean"?UD(s,e):dm(s,e)}function UD(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(no(t,{size:e.size}),ro(t,{size:e.size})):t}function dm(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=RD[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(no(i,{size:e.size}),ro(i,{dir:"right",size:e.size})):i}function pm(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof s=="bigint"?"n":"";throw new DD({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${s}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?ro(a,{size:i}):a}const LD=new TextEncoder;function zD(s,e={}){const t=LD.encode(s);return dm(t,e)}const FD=new TextEncoder;function qD(s,e={}){return typeof s=="number"||typeof s=="bigint"?HD(s,e):typeof s=="boolean"?BD(s,e):na(s)?gm(s,e):fm(s,e)}function BD(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(no(t,{size:e.size}),ro(t,{size:e.size})):t}const Ai={zero:48,nine:57,A:65,F:70,a:97,f:102};function vg(s){if(s>=Ai.zero&&s<=Ai.nine)return s-Ai.zero;if(s>=Ai.A&&s<=Ai.F)return s-(Ai.A-10);if(s>=Ai.a&&s<=Ai.f)return s-(Ai.a-10)}function gm(s,e={}){let t=s;e.size&&(no(t,{size:e.size}),t=ro(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=vg(i.charCodeAt(a++)),l=vg(i.charCodeAt(a++));if(c===void 0||l===void 0)throw new Dr(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function HD(s,e){const t=pm(s,e);return gm(t)}function fm(s,e={}){const t=FD.encode(s);return typeof e.size=="number"?(no(t,{size:e.size}),ro(t,{dir:"right",size:e.size})):t}function Oc(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function WD(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function rl(s,...e){if(!WD(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function hF(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Oc(s.outputLen),Oc(s.blockLen)}function Ig(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function VD(s,e){rl(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Qa=BigInt(2**32-1),Eg=BigInt(32);function KD(s,e=!1){return e?{h:Number(s&Qa),l:Number(s>>Eg&Qa)}:{h:Number(s>>Eg&Qa)|0,l:Number(s&Qa)|0}}function GD(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=KD(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const YD=(s,e,t)=>s<<t|e>>>32-t,QD=(s,e,t)=>e<<t|s>>>32-t,ZD=(s,e,t)=>e<<t-32|s>>>64-t,JD=(s,e,t)=>s<<t-32|e>>>64-t,hn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function XD(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function uF(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function dF(s,e){return s<<32-e|s>>>e}const Ag=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ek(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Ng(s){for(let e=0;e<s.length;e++)s[e]=ek(s[e])}function tk(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function wm(s){return typeof s=="string"&&(s=tk(s)),rl(s),s}function pF(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];rl(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}class sk{clone(){return this._cloneInto()}}function ik(s){const e=i=>s().update(wm(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function gF(s=32){if(hn&&typeof hn.getRandomValues=="function")return hn.getRandomValues(new Uint8Array(s));if(hn&&typeof hn.randomBytes=="function")return hn.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const ym=[],mm=[],bm=[],rk=BigInt(0),To=BigInt(1),nk=BigInt(2),ok=BigInt(7),ak=BigInt(256),ck=BigInt(113);for(let s=0,e=To,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],ym.push(2*(5*i+t)),mm.push((s+1)*(s+2)/2%64);let r=rk;for(let n=0;n<7;n++)e=(e<<To^(e>>ok)*ck)%ak,e&nk&&(r^=To<<(To<<BigInt(n))-To);bm.push(r)}const[lk,hk]=GD(bm,!0),_g=(s,e,t)=>t>32?ZD(s,e,t):YD(s,e,t),Cg=(s,e,t)=>t>32?JD(s,e,t):QD(s,e,t);function uk(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],h=t[c+1],u=_g(l,h,1)^t[a],d=Cg(l,h,1)^t[a+1];for(let g=0;g<50;g+=10)s[o+g]^=u,s[o+g+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=mm[o],c=_g(r,n,a),l=Cg(r,n,a),h=ym[o];r=s[h],n=s[h+1],s[h]=c,s[h+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=lk[i],s[1]^=hk[i]}t.fill(0)}class Du extends sk{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Oc(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=XD(this.state)}keccak(){Ag||Ng(this.state32),uk(this.state32,this.rounds),Ag||Ng(this.state32),this.posOut=0,this.pos=0}update(e){Ig(this);const{blockLen:t,state:i}=this;e=wm(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Ig(this,!1),rl(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Oc(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(VD(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Du(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const dk=(s,e,t)=>ik(()=>new Du(e,s,t)),pk=dk(1,136,256/8);function vm(s,e){const t=e||"hex",i=pk(na(s,{strict:!1})?qD(s):s);return t==="bytes"?i:zh(i)}class gk extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const Wl=new gk(8192);function fk(s,e){if(Wl.has(`${s}.${e}`))return Wl.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=vm(fm(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Wl.set(`${s}.${e}`,n),n}function wk(s){const e=vm(`0x${s.substring(4)}`).substring(26);return fk(`0x${e}`)}async function yk({hash:s,signature:e}){const t=na(s)?s:zh(s),{secp256k1:i}=await Zo(async()=>{const{secp256k1:o}=await import("./secp256k1-Cd7rIav0.js");return{secp256k1:o}},__vite__mapDeps([12,1,2,5,6,7,8,9,10,11]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:h,v:u,yParity:d}=e,g=Number(d??u),p=Sg(g);return new i.Signature(Lh(l),Lh(h)).addRecoveryBit(p)}const o=na(e)?e:zh(e),a=jD(`0x${o.slice(130)}`),c=Sg(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Sg(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function mk({hash:s,signature:e}){return wk(await yk({hash:s,signature:e}))}function bk(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const h=s.charAt(l),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let h=0,u=0,d=0;const g=l.length;for(;d!==g&&l[d]===0;)d++,h++;const p=(g-d)*n+1>>>0,f=new Uint8Array(p);for(;d!==g;){let w=l[d],E=0;for(let A=p-1;(w!==0||E<u)&&A!==-1;A--,E++)w+=256*f[A]>>>0,f[A]=w%t>>>0,w=w/t>>>0;if(w!==0)throw new Error("Non-zero carry");u=E,d++}let b=p-u;for(;b!==p&&f[b]===0;)b++;let m=i.repeat(h);for(;b<p;++b)m+=s.charAt(f[b]);return m}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;l[h]===i;)u++,h++;const g=(l.length-h)*r+1>>>0,p=new Uint8Array(g);for(;h<l.length;){const w=l.charCodeAt(h);if(w>255)return;let E=e[w];if(E===255)return;let A=0;for(let _=g-1;(E!==0||A<d)&&_!==-1;_--,A++)E+=t*p[_]>>>0,p[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=A,h++}let f=g-d;for(;f!==g&&p[f]===0;)f++;const b=new Uint8Array(u+(g-f));let m=u;for(;f!==g;)b[m++]=p[f++];return b}function c(l){const h=a(l);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var vk="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Im=bk(vk);var Ik={};const Ek=":";function Fn(s){const[e,t]=s.split(Ek);return{namespace:e,reference:t}}function Em(s,e){return s.includes(":")?[s]:e.chains||[]}const Ak="ReactNative",Is={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Nk="js";function xc(){return typeof T.process<"u"&&typeof T.process.versions<"u"&&typeof T.process.versions.node<"u"}function cr(){return!rr()&&!!qc()&&navigator.product===Ak}function _k(){return cr()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"&&(T.global==null?void 0:T.global.Platform.OS)==="android"}function Ck(){return cr()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"&&(T.global==null?void 0:T.global.Platform.OS)==="ios"}function Ia(){return!xc()&&!!qc()&&!!rr()}function Ea(){return cr()?Is.reactNative:xc()?Is.node:Ia()?Is.browser:Is.unknown}function Tg(){var s;try{return cr()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Application)<"u"?(s=T.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function Sk(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function Am(){return cw()||{name:"",description:"",url:"",icons:[""]}}function Tk(){if(Ea()===Is.reactNative&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"){const{OS:t,Version:i}=T.global.Platform;return[t,i].join("-")}const s=hw();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function Pk(){var s;const e=Ea();return e===Is.browser?[e,((s=uw())==null?void 0:s.host)||"unknown"].join(":"):e}function Nm(s,e,t){const i=Tk(),r=Pk();return[[s,e].join("-"),[Nk,t].join("-"),i,r].join("/")}function $k({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=t.split("?"),h=Nm(s,e,i),u={auth:r,ua:h,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=Sk(l[1]||"",u);return l[0]+"?"+d}function Sr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Fh(s){return Object.fromEntries(s.entries())}function qh(s){return new Map(Object.entries(s))}function vr(s=N.FIVE_MINUTES,e){const t=N.toMiliseconds(s||N.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},t),i=a,r=c})}}function Ji(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function _m(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${s}`)}function Mk(s){return _m("topic",s)}function Ok(s){return _m("id",s)}function Cm(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function bt(s,e){return N.fromMiliseconds(Date.now()+N.toMiliseconds(s))}function Ki(s){return Date.now()>=N.toMiliseconds(s)}function Pe(s,e){return`${s}${e?`:${e}`:""}`}function pc(s=[],e=[]){return[...new Set([...s,...e])]}async function xk({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=Dk(n,s,e),a=Ea();if(a===Is.browser){if(!((i=rr())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}kk(o)}else a===Is.reactNative&&typeof(T.global==null?void 0:T.global.Linking)<"u"&&await T.global.Linking.openURL(o)}catch(r){console.error(r)}}function Dk(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${Lk(i,!0)}`}else r=`${r}/wc?${i}`;return r}function kk(s){let e="_self";Uk()?e="_top":(Rk()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function jk(s,e){let t="";try{if(Ia()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Pg(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function $g(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function ku(){return typeof T.process<"u"&&Ik.IS_VITEST==="true"}function Rk(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Uk(){try{return window.self!==window.top}catch{return!1}}function Lk(s,e=!1){const t=T.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Sm(s){return T.Buffer.from(s,"base64").toString("utf-8")}function zk(s){return new Promise(e=>setTimeout(e,s))}function oa(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Fk(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function nl(s,...e){if(!Fk(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function ju(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");oa(s.outputLen),oa(s.blockLen)}function Kn(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Tm(s,e){nl(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Za=BigInt(2**32-1),Mg=BigInt(32);function qk(s,e=!1){return e?{h:Number(s&Za),l:Number(s>>Mg&Za)}:{h:Number(s>>Mg&Za)|0,l:Number(s&Za)|0}}function Bk(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=qk(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const Hk=(s,e,t)=>s<<t|e>>>32-t,Wk=(s,e,t)=>e<<t|s>>>32-t,Vk=(s,e,t)=>e<<t-32|s>>>64-t,Kk=(s,e,t)=>s<<t-32|e>>>64-t,un=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Gk(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Vl(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function oi(s,e){return s<<32-e|s>>>e}const Og=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Yk(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function xg(s){for(let e=0;e<s.length;e++)s[e]=Yk(s[e])}function Qk(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Gn(s){return typeof s=="string"&&(s=Qk(s)),nl(s),s}let Ru=class{clone(){return this._cloneInto()}};function Pm(s){const e=i=>s().update(Gn(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Aa(s=32){if(un&&typeof un.getRandomValues=="function")return un.getRandomValues(new Uint8Array(s));if(un&&typeof un.randomBytes=="function")return un.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const $m=[],Mm=[],Om=[],Zk=BigInt(0),Po=BigInt(1),Jk=BigInt(2),Xk=BigInt(7),e3=BigInt(256),t3=BigInt(113);for(let s=0,e=Po,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],$m.push(2*(5*i+t)),Mm.push((s+1)*(s+2)/2%64);let r=Zk;for(let n=0;n<7;n++)e=(e<<Po^(e>>Xk)*t3)%e3,e&Jk&&(r^=Po<<(Po<<BigInt(n))-Po);Om.push(r)}const[s3,i3]=Bk(Om,!0),Dg=(s,e,t)=>t>32?Vk(s,e,t):Hk(s,e,t),kg=(s,e,t)=>t>32?Kk(s,e,t):Wk(s,e,t);function r3(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],h=t[c+1],u=Dg(l,h,1)^t[a],d=kg(l,h,1)^t[a+1];for(let g=0;g<50;g+=10)s[o+g]^=u,s[o+g+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Mm[o],c=Dg(r,n,a),l=kg(r,n,a),h=$m[o];r=s[h],n=s[h+1],s[h]=c,s[h+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=s3[i],s[1]^=i3[i]}t.fill(0)}let n3=class xm extends Ru{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,oa(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Gk(this.state)}keccak(){Og||xg(this.state32),r3(this.state32,this.rounds),Og||xg(this.state32),this.posOut=0,this.pos=0}update(e){Kn(this);const{blockLen:t,state:i}=this;e=Gn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Kn(this,!1),nl(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return oa(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Tm(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new xm(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const o3=(s,e,t)=>Pm(()=>new n3(e,s,t)),a3=o3(1,136,256/8),c3="https://rpc.walletconnect.org/v1";function Dm(s){const e=`Ethereum Signed Message:
|
|
13
|
+
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=lm}walk(e){return hm(this,e)}}function hm(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?hm(s.cause,e):e?null:s}class um extends Dr{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function ro(s,{dir:e,size:t=32}={}){return typeof s=="string"?OD(s,{dir:e,size:t}):xD(s,{dir:e,size:t})}function OD(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new um({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function xD(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new um({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}class DD extends Dr{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class kD extends Dr{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function no(s,{size:e}){if(bg(s)>e)throw new kD({givenSize:bg(s),maxSize:e})}function Lh(s,e={}){const{signed:t}=e;e.size&&no(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function jD(s,e={}){return Number(Lh(s,e))}const RD=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function zh(s,e={}){return typeof s=="number"||typeof s=="bigint"?pm(s,e):typeof s=="string"?zD(s,e):typeof s=="boolean"?UD(s,e):dm(s,e)}function UD(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(no(t,{size:e.size}),ro(t,{size:e.size})):t}function dm(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=RD[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(no(i,{size:e.size}),ro(i,{dir:"right",size:e.size})):i}function pm(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof s=="bigint"?"n":"";throw new DD({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${s}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?ro(a,{size:i}):a}const LD=new TextEncoder;function zD(s,e={}){const t=LD.encode(s);return dm(t,e)}const FD=new TextEncoder;function qD(s,e={}){return typeof s=="number"||typeof s=="bigint"?HD(s,e):typeof s=="boolean"?BD(s,e):na(s)?gm(s,e):fm(s,e)}function BD(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(no(t,{size:e.size}),ro(t,{size:e.size})):t}const Ai={zero:48,nine:57,A:65,F:70,a:97,f:102};function vg(s){if(s>=Ai.zero&&s<=Ai.nine)return s-Ai.zero;if(s>=Ai.A&&s<=Ai.F)return s-(Ai.A-10);if(s>=Ai.a&&s<=Ai.f)return s-(Ai.a-10)}function gm(s,e={}){let t=s;e.size&&(no(t,{size:e.size}),t=ro(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=vg(i.charCodeAt(a++)),l=vg(i.charCodeAt(a++));if(c===void 0||l===void 0)throw new Dr(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function HD(s,e){const t=pm(s,e);return gm(t)}function fm(s,e={}){const t=FD.encode(s);return typeof e.size=="number"?(no(t,{size:e.size}),ro(t,{dir:"right",size:e.size})):t}function Oc(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function WD(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function rl(s,...e){if(!WD(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function hF(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Oc(s.outputLen),Oc(s.blockLen)}function Ig(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function VD(s,e){rl(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Qa=BigInt(2**32-1),Eg=BigInt(32);function KD(s,e=!1){return e?{h:Number(s&Qa),l:Number(s>>Eg&Qa)}:{h:Number(s>>Eg&Qa)|0,l:Number(s&Qa)|0}}function GD(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=KD(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const YD=(s,e,t)=>s<<t|e>>>32-t,QD=(s,e,t)=>e<<t|s>>>32-t,ZD=(s,e,t)=>e<<t-32|s>>>64-t,JD=(s,e,t)=>s<<t-32|e>>>64-t,hn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function XD(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function uF(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function dF(s,e){return s<<32-e|s>>>e}const Ag=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ek(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Ng(s){for(let e=0;e<s.length;e++)s[e]=ek(s[e])}function tk(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function wm(s){return typeof s=="string"&&(s=tk(s)),rl(s),s}function pF(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];rl(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}class sk{clone(){return this._cloneInto()}}function ik(s){const e=i=>s().update(wm(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function gF(s=32){if(hn&&typeof hn.getRandomValues=="function")return hn.getRandomValues(new Uint8Array(s));if(hn&&typeof hn.randomBytes=="function")return hn.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const ym=[],mm=[],bm=[],rk=BigInt(0),To=BigInt(1),nk=BigInt(2),ok=BigInt(7),ak=BigInt(256),ck=BigInt(113);for(let s=0,e=To,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],ym.push(2*(5*i+t)),mm.push((s+1)*(s+2)/2%64);let r=rk;for(let n=0;n<7;n++)e=(e<<To^(e>>ok)*ck)%ak,e&nk&&(r^=To<<(To<<BigInt(n))-To);bm.push(r)}const[lk,hk]=GD(bm,!0),_g=(s,e,t)=>t>32?ZD(s,e,t):YD(s,e,t),Cg=(s,e,t)=>t>32?JD(s,e,t):QD(s,e,t);function uk(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],h=t[c+1],u=_g(l,h,1)^t[a],d=Cg(l,h,1)^t[a+1];for(let g=0;g<50;g+=10)s[o+g]^=u,s[o+g+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=mm[o],c=_g(r,n,a),l=Cg(r,n,a),h=ym[o];r=s[h],n=s[h+1],s[h]=c,s[h+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=lk[i],s[1]^=hk[i]}t.fill(0)}class Du extends sk{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Oc(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=XD(this.state)}keccak(){Ag||Ng(this.state32),uk(this.state32,this.rounds),Ag||Ng(this.state32),this.posOut=0,this.pos=0}update(e){Ig(this);const{blockLen:t,state:i}=this;e=wm(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Ig(this,!1),rl(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Oc(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(VD(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Du(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const dk=(s,e,t)=>ik(()=>new Du(e,s,t)),pk=dk(1,136,256/8);function vm(s,e){const t=e||"hex",i=pk(na(s,{strict:!1})?qD(s):s);return t==="bytes"?i:zh(i)}class gk extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const Wl=new gk(8192);function fk(s,e){if(Wl.has(`${s}.${e}`))return Wl.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=vm(fm(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Wl.set(`${s}.${e}`,n),n}function wk(s){const e=vm(`0x${s.substring(4)}`).substring(26);return fk(`0x${e}`)}async function yk({hash:s,signature:e}){const t=na(s)?s:zh(s),{secp256k1:i}=await Zo(async()=>{const{secp256k1:o}=await import("./secp256k1-0LtSM2L1.js");return{secp256k1:o}},__vite__mapDeps([12,1,2,5,6,7,8,9,10,11]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:h,v:u,yParity:d}=e,g=Number(d??u),p=Sg(g);return new i.Signature(Lh(l),Lh(h)).addRecoveryBit(p)}const o=na(e)?e:zh(e),a=jD(`0x${o.slice(130)}`),c=Sg(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Sg(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function mk({hash:s,signature:e}){return wk(await yk({hash:s,signature:e}))}function bk(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const h=s.charAt(l),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let h=0,u=0,d=0;const g=l.length;for(;d!==g&&l[d]===0;)d++,h++;const p=(g-d)*n+1>>>0,f=new Uint8Array(p);for(;d!==g;){let w=l[d],E=0;for(let A=p-1;(w!==0||E<u)&&A!==-1;A--,E++)w+=256*f[A]>>>0,f[A]=w%t>>>0,w=w/t>>>0;if(w!==0)throw new Error("Non-zero carry");u=E,d++}let b=p-u;for(;b!==p&&f[b]===0;)b++;let m=i.repeat(h);for(;b<p;++b)m+=s.charAt(f[b]);return m}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;l[h]===i;)u++,h++;const g=(l.length-h)*r+1>>>0,p=new Uint8Array(g);for(;h<l.length;){const w=l.charCodeAt(h);if(w>255)return;let E=e[w];if(E===255)return;let A=0;for(let _=g-1;(E!==0||A<d)&&_!==-1;_--,A++)E+=t*p[_]>>>0,p[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=A,h++}let f=g-d;for(;f!==g&&p[f]===0;)f++;const b=new Uint8Array(u+(g-f));let m=u;for(;f!==g;)b[m++]=p[f++];return b}function c(l){const h=a(l);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var vk="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Im=bk(vk);var Ik={};const Ek=":";function Fn(s){const[e,t]=s.split(Ek);return{namespace:e,reference:t}}function Em(s,e){return s.includes(":")?[s]:e.chains||[]}const Ak="ReactNative",Is={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Nk="js";function xc(){return typeof T.process<"u"&&typeof T.process.versions<"u"&&typeof T.process.versions.node<"u"}function cr(){return!rr()&&!!qc()&&navigator.product===Ak}function _k(){return cr()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"&&(T.global==null?void 0:T.global.Platform.OS)==="android"}function Ck(){return cr()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"&&(T.global==null?void 0:T.global.Platform.OS)==="ios"}function Ia(){return!xc()&&!!qc()&&!!rr()}function Ea(){return cr()?Is.reactNative:xc()?Is.node:Ia()?Is.browser:Is.unknown}function Tg(){var s;try{return cr()&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Application)<"u"?(s=T.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function Sk(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function Am(){return cw()||{name:"",description:"",url:"",icons:[""]}}function Tk(){if(Ea()===Is.reactNative&&typeof T.global<"u"&&typeof(T.global==null?void 0:T.global.Platform)<"u"){const{OS:t,Version:i}=T.global.Platform;return[t,i].join("-")}const s=hw();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function Pk(){var s;const e=Ea();return e===Is.browser?[e,((s=uw())==null?void 0:s.host)||"unknown"].join(":"):e}function Nm(s,e,t){const i=Tk(),r=Pk();return[[s,e].join("-"),[Nk,t].join("-"),i,r].join("/")}function $k({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=t.split("?"),h=Nm(s,e,i),u={auth:r,ua:h,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=Sk(l[1]||"",u);return l[0]+"?"+d}function Sr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Fh(s){return Object.fromEntries(s.entries())}function qh(s){return new Map(Object.entries(s))}function vr(s=N.FIVE_MINUTES,e){const t=N.toMiliseconds(s||N.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},t),i=a,r=c})}}function Ji(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function _m(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${s}`)}function Mk(s){return _m("topic",s)}function Ok(s){return _m("id",s)}function Cm(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function bt(s,e){return N.fromMiliseconds(Date.now()+N.toMiliseconds(s))}function Ki(s){return Date.now()>=N.toMiliseconds(s)}function Pe(s,e){return`${s}${e?`:${e}`:""}`}function pc(s=[],e=[]){return[...new Set([...s,...e])]}async function xk({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=Dk(n,s,e),a=Ea();if(a===Is.browser){if(!((i=rr())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}kk(o)}else a===Is.reactNative&&typeof(T.global==null?void 0:T.global.Linking)<"u"&&await T.global.Linking.openURL(o)}catch(r){console.error(r)}}function Dk(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${Lk(i,!0)}`}else r=`${r}/wc?${i}`;return r}function kk(s){let e="_self";Uk()?e="_top":(Rk()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function jk(s,e){let t="";try{if(Ia()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Pg(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function $g(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function ku(){return typeof T.process<"u"&&Ik.IS_VITEST==="true"}function Rk(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Uk(){try{return window.self!==window.top}catch{return!1}}function Lk(s,e=!1){const t=T.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Sm(s){return T.Buffer.from(s,"base64").toString("utf-8")}function zk(s){return new Promise(e=>setTimeout(e,s))}function oa(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Fk(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function nl(s,...e){if(!Fk(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function ju(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");oa(s.outputLen),oa(s.blockLen)}function Kn(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Tm(s,e){nl(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Za=BigInt(2**32-1),Mg=BigInt(32);function qk(s,e=!1){return e?{h:Number(s&Za),l:Number(s>>Mg&Za)}:{h:Number(s>>Mg&Za)|0,l:Number(s&Za)|0}}function Bk(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=qk(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const Hk=(s,e,t)=>s<<t|e>>>32-t,Wk=(s,e,t)=>e<<t|s>>>32-t,Vk=(s,e,t)=>e<<t-32|s>>>64-t,Kk=(s,e,t)=>s<<t-32|e>>>64-t,un=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Gk(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Vl(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function oi(s,e){return s<<32-e|s>>>e}const Og=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Yk(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function xg(s){for(let e=0;e<s.length;e++)s[e]=Yk(s[e])}function Qk(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Gn(s){return typeof s=="string"&&(s=Qk(s)),nl(s),s}let Ru=class{clone(){return this._cloneInto()}};function Pm(s){const e=i=>s().update(Gn(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Aa(s=32){if(un&&typeof un.getRandomValues=="function")return un.getRandomValues(new Uint8Array(s));if(un&&typeof un.randomBytes=="function")return un.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const $m=[],Mm=[],Om=[],Zk=BigInt(0),Po=BigInt(1),Jk=BigInt(2),Xk=BigInt(7),e3=BigInt(256),t3=BigInt(113);for(let s=0,e=Po,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],$m.push(2*(5*i+t)),Mm.push((s+1)*(s+2)/2%64);let r=Zk;for(let n=0;n<7;n++)e=(e<<Po^(e>>Xk)*t3)%e3,e&Jk&&(r^=Po<<(Po<<BigInt(n))-Po);Om.push(r)}const[s3,i3]=Bk(Om,!0),Dg=(s,e,t)=>t>32?Vk(s,e,t):Hk(s,e,t),kg=(s,e,t)=>t>32?Kk(s,e,t):Wk(s,e,t);function r3(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],h=t[c+1],u=Dg(l,h,1)^t[a],d=kg(l,h,1)^t[a+1];for(let g=0;g<50;g+=10)s[o+g]^=u,s[o+g+1]^=d}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Mm[o],c=Dg(r,n,a),l=kg(r,n,a),h=$m[o];r=s[h],n=s[h+1],s[h]=c,s[h+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=s3[i],s[1]^=i3[i]}t.fill(0)}let n3=class xm extends Ru{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,oa(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Gk(this.state)}keccak(){Og||xg(this.state32),r3(this.state32,this.rounds),Og||xg(this.state32),this.posOut=0,this.pos=0}update(e){Kn(this);const{blockLen:t,state:i}=this;e=Gn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,t&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Kn(this,!1),nl(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return oa(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Tm(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new xm(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const o3=(s,e,t)=>Pm(()=>new n3(e,s,t)),a3=o3(1,136,256/8),c3="https://rpc.walletconnect.org/v1";function Dm(s){const e=`Ethereum Signed Message:
|
|
14
14
|
${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+T.Buffer.from(a3(t)).toString("hex")}async function l3(s,e,t,i,r,n){switch(t.t){case"eip191":return await h3(s,e,t.s);case"eip1271":return await u3(s,e,t.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function h3(s,e,t){return(await mk({hash:Dm(e),signature:t})).toLowerCase()===s.toLowerCase()}async function u3(s,e,t,i,r,n){const o=Fn(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l="0000000000000000000000000000000000000000000000000000000000000041",h=t.substring(2),u=Dm(e).substring(2),d=a+u+c+l+h,g=await fetch(`${n||c3}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:d3(),jsonrpc:"2.0",method:"eth_call",params:[{to:s,data:d},"latest"]})}),{result:p}=await g.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function d3(){return Date.now()+Math.floor(Math.random()*1e3)}function p3(s){const e=atob(s),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);const i=t[0];if(i===0)throw new Error("No signatures found");const r=1+i*64;if(t.length<r)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const n=T.Buffer.from(s,"base64").slice(1,65);return Im.encode(n)}var g3=Object.defineProperty,f3=Object.defineProperties,w3=Object.getOwnPropertyDescriptors,jg=Object.getOwnPropertySymbols,y3=Object.prototype.hasOwnProperty,m3=Object.prototype.propertyIsEnumerable,Rg=(s,e,t)=>e in s?g3(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,b3=(s,e)=>{for(var t in e||(e={}))y3.call(e,t)&&Rg(s,t,e[t]);if(jg)for(var t of jg(e))m3.call(e,t)&&Rg(s,t,e[t]);return s},v3=(s,e)=>f3(s,w3(e));const I3="did:pkh:",Uu=s=>s==null?void 0:s.split(":"),E3=s=>{const e=s&&Uu(s);if(e)return s.includes(I3)?e[3]:e[1]},Bh=s=>{const e=s&&Uu(s);if(e)return e[2]+":"+e[3]},Dc=s=>{const e=s&&Uu(s);if(e)return e.pop()};async function Ug(s){const{cacao:e,projectId:t}=s,{s:i,p:r}=e,n=km(r,r.iss),o=Dc(r.iss);return await l3(o,n,i,Bh(r.iss),t)}const km=(s,e)=>{const t=`${s.domain} wants you to sign in with your Ethereum account:`,i=Dc(e);if(!s.aud&&!s.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=s.statement||void 0;const n=`URI: ${s.aud||s.uri}`,o=`Version: ${s.version}`,a=`Chain ID: ${E3(e)}`,c=`Nonce: ${s.nonce}`,l=`Issued At: ${s.iat}`,h=s.exp?`Expiration Time: ${s.exp}`:void 0,u=s.nbf?`Not Before: ${s.nbf}`:void 0,d=s.requestId?`Request ID: ${s.requestId}`:void 0,g=s.resources?`Resources:${s.resources.map(f=>`
|
|
15
15
|
- ${f}`).join("")}`:void 0,p=gc(s.resources);if(p){const f=aa(p);r=M3(r,f)}return[t,i,"",r,"",n,o,a,c,l,h,u,d,g].filter(f=>f!=null).join(`
|
|
16
16
|
`)};function A3(s){return T.Buffer.from(JSON.stringify(s)).toString("base64")}function N3(s){return JSON.parse(T.Buffer.from(s,"base64").toString("utf-8"))}function kr(s){if(!s)throw new Error("No recap provided, value is undefined");if(!s.att)throw new Error("No `att` property found");const e=Object.keys(s.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=s.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(r=>{const n=i[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function _3(s,e,t,i={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[s]:C3(e,t,i)}}}function C3(s,e,t={}){e=e==null?void 0:e.sort((r,n)=>r.localeCompare(n));const i=e.map(r=>({[`${s}/${r}`]:[t]}));return Object.assign({},...i)}function jm(s){return kr(s),`urn:recap:${A3(s).replace(/=/g,"")}`}function aa(s){const e=N3(s.replace("urn:recap:",""));return kr(e),e}function S3(s,e,t){const i=_3(s,e,t);return jm(i)}function T3(s){return s&&s.includes("urn:recap:")}function P3(s,e){const t=aa(s),i=aa(e),r=$3(t,i);return jm(r)}function $3(s,e){kr(s),kr(e);const t=Object.keys(s.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),i={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=s.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;i.att[r]=v3(b3({},i.att[r]),{[a]:((c=s.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),i}function M3(s="",e){kr(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(s.includes(t))return s;const i=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,d)=>u.action.localeCompare(d.action));const l={};c.forEach(u=>{l[u.ability]||(l[u.ability]=[]),l[u.ability].push(u.action)});const h=Object.keys(l).map(u=>(r++,`(${r}) '${u}': '${l[u].join("', '")}' for '${a}'.`));i.push(h.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${s?s+" ":""}${o}`}function Lg(s){var e;const t=aa(s);kr(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function zg(s){const e=aa(s);kr(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(r=>{var n;(n=r==null?void 0:r[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function gc(s){if(!s)return;const e=s==null?void 0:s[s.length-1];return T3(e)?e:void 0}function Kl(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Rm(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function bs(s,...e){if(!Rm(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Fg(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function O3(s,e){bs(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function qg(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}const tr=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),x3=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),D3=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!D3)throw new Error("Non little-endian hardware is not supported");function k3(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Hh(s){if(typeof s=="string")s=k3(s);else if(Rm(s))s=Wh(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function j3(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function R3(s,e){if(s.length!==e.length)return!1;let t=0;for(let i=0;i<s.length;i++)t|=s[i]^e[i];return t===0}const U3=(s,e)=>{function t(i,...r){if(bs(i),s.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");s.varSizeNonce?bs(l):bs(l,s.nonceLength)}const n=s.tagLength;n&&r[1]!==void 0&&bs(r[1]);const o=e(i,...r),a=(l,h)=>{if(h!==void 0){if(l!==2)throw new Error("cipher output not supported");bs(h)}};let c=!1;return{encrypt(l,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,bs(l),a(o.encrypt.length,h),o.encrypt(l,h)},decrypt(l,h){if(bs(l),n&&l.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,h),o.decrypt(l,h)}}}return Object.assign(t,s),t};function Bg(s,e,t=!0){if(e===void 0)return new Uint8Array(s);if(e.length!==s)throw new Error("invalid output length, expected "+s+", got: "+e.length);if(t&&!L3(e))throw new Error("invalid output, must be aligned");return e}function Hg(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);s.setUint32(e+4,o,i),s.setUint32(e+0,a,i)}function L3(s){return s.byteOffset%4===0}function Wh(s){return Uint8Array.from(s)}function Yn(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}const Um=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),z3=Um("expand 16-byte k"),F3=Um("expand 32-byte k"),q3=tr(z3),B3=tr(F3);function Ee(s,e){return s<<e|s>>>32-e}function Vh(s){return s.byteOffset%4===0}const Ja=64,H3=16,Lm=2**32-1,Wg=new Uint32Array;function W3(s,e,t,i,r,n,o,a){const c=r.length,l=new Uint8Array(Ja),h=tr(l),u=Vh(r)&&Vh(n),d=u?tr(r):Wg,g=u?tr(n):Wg;for(let p=0;p<c;o++){if(s(e,t,i,h,o,a),o>=Lm)throw new Error("arx: counter overflow");const f=Math.min(Ja,c-p);if(u&&f===Ja){const b=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let m=0,w;m<H3;m++)w=b+m,g[w]=d[w]^h[m];p+=Ja;continue}for(let b=0,m;b<f;b++)m=p+b,n[m]=r[m]^l[b];p+=f}}function V3(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=j3({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return Kl(r),Kl(o),qg(n),qg(t),(a,c,l,h,u=0)=>{bs(a),bs(c),bs(l);const d=l.length;if(h===void 0&&(h=new Uint8Array(d)),bs(h),Kl(u),u<0||u>=Lm)throw new Error("arx: counter overflow");if(h.length<d)throw new Error(`arx: output (${h.length}) is shorter than data (${d})`);const g=[];let p=a.length,f,b;if(p===32)g.push(f=Wh(a)),b=B3;else if(p===16&&t)f=new Uint8Array(32),f.set(a),f.set(a,16),b=q3,g.push(f);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);Vh(c)||g.push(c=Wh(c));const m=tr(f);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(b,m,tr(c.subarray(0,16)),m),c=c.subarray(16)}const w=16-r;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){const A=new Uint8Array(12);A.set(c,n?0:12-c.length),c=A,g.push(c)}const E=tr(c);return W3(s,b,m,E,l,h,u,o),Yn(...g),h}}const Dt=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let K3=class{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=Hh(e),bs(e,32);const t=Dt(e,0),i=Dt(e,2),r=Dt(e,4),n=Dt(e,6),o=Dt(e,8),a=Dt(e,10),c=Dt(e,12),l=Dt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|r<<6)&7939,this.r[3]=(r>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let h=0;h<8;h++)this.pad[h]=Dt(e,16+2*h)}process(e,t,i=!1){const r=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],l=o[2],h=o[3],u=o[4],d=o[5],g=o[6],p=o[7],f=o[8],b=o[9],m=Dt(e,t+0),w=Dt(e,t+2),E=Dt(e,t+4),A=Dt(e,t+6),_=Dt(e,t+8),S=Dt(e,t+10),P=Dt(e,t+12),x=Dt(e,t+14);let $=n[0]+(m&8191),F=n[1]+((m>>>13|w<<3)&8191),k=n[2]+((w>>>10|E<<6)&8191),K=n[3]+((E>>>7|A<<9)&8191),q=n[4]+((A>>>4|_<<12)&8191),H=n[5]+(_>>>1&8191),W=n[6]+((_>>>14|S<<2)&8191),B=n[7]+((S>>>11|P<<5)&8191),V=n[8]+((P>>>8|x<<8)&8191),Y=n[9]+(x>>>5|r),C=0,L=C+$*a+F*(5*b)+k*(5*f)+K*(5*p)+q*(5*g);C=L>>>13,L&=8191,L+=H*(5*d)+W*(5*u)+B*(5*h)+V*(5*l)+Y*(5*c),C+=L>>>13,L&=8191;let X=C+$*c+F*a+k*(5*b)+K*(5*f)+q*(5*p);C=X>>>13,X&=8191,X+=H*(5*g)+W*(5*d)+B*(5*u)+V*(5*h)+Y*(5*l),C+=X>>>13,X&=8191;let Q=C+$*l+F*c+k*a+K*(5*b)+q*(5*f);C=Q>>>13,Q&=8191,Q+=H*(5*p)+W*(5*g)+B*(5*d)+V*(5*u)+Y*(5*h),C+=Q>>>13,Q&=8191;let me=C+$*h+F*l+k*c+K*a+q*(5*b);C=me>>>13,me&=8191,me+=H*(5*f)+W*(5*p)+B*(5*g)+V*(5*d)+Y*(5*u),C+=me>>>13,me&=8191;let ue=C+$*u+F*h+k*l+K*c+q*a;C=ue>>>13,ue&=8191,ue+=H*(5*b)+W*(5*f)+B*(5*p)+V*(5*g)+Y*(5*d),C+=ue>>>13,ue&=8191;let ee=C+$*d+F*u+k*h+K*l+q*c;C=ee>>>13,ee&=8191,ee+=H*a+W*(5*b)+B*(5*f)+V*(5*p)+Y*(5*g),C+=ee>>>13,ee&=8191;let nt=C+$*g+F*d+k*u+K*h+q*l;C=nt>>>13,nt&=8191,nt+=H*c+W*a+B*(5*b)+V*(5*f)+Y*(5*p),C+=nt>>>13,nt&=8191;let Le=C+$*p+F*g+k*d+K*u+q*h;C=Le>>>13,Le&=8191,Le+=H*l+W*c+B*a+V*(5*b)+Y*(5*f),C+=Le>>>13,Le&=8191;let be=C+$*f+F*p+k*g+K*d+q*u;C=be>>>13,be&=8191,be+=H*h+W*l+B*c+V*a+Y*(5*b),C+=be>>>13,be&=8191;let ke=C+$*b+F*f+k*p+K*g+q*d;C=ke>>>13,ke&=8191,ke+=H*u+W*h+B*l+V*c+Y*a,C+=ke>>>13,ke&=8191,C=(C<<2)+C|0,C=C+L|0,L=C&8191,C=C>>>13,X+=C,n[0]=L,n[1]=X,n[2]=Q,n[3]=me,n[4]=ue,n[5]=ee,n[6]=nt,n[7]=Le,n[8]=be,n[9]=ke}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,i[0]=e[0]+5,r=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+r,r=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;Yn(i)}update(e){Fg(this);const{buffer:t,blockLen:i}=this;e=Hh(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){for(;i<=r-n;n+=i)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Yn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Fg(this),O3(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}};function G3(s){const e=(i,r)=>s(r).update(Hh(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const Y3=G3(s=>new K3(s));function Q3(s,e,t,i,r,n=20){let o=s[0],a=s[1],c=s[2],l=s[3],h=e[0],u=e[1],d=e[2],g=e[3],p=e[4],f=e[5],b=e[6],m=e[7],w=r,E=t[0],A=t[1],_=t[2],S=o,P=a,x=c,$=l,F=h,k=u,K=d,q=g,H=p,W=f,B=b,V=m,Y=w,C=E,L=A,X=_;for(let me=0;me<n;me+=2)S=S+F|0,Y=Ee(Y^S,16),H=H+Y|0,F=Ee(F^H,12),S=S+F|0,Y=Ee(Y^S,8),H=H+Y|0,F=Ee(F^H,7),P=P+k|0,C=Ee(C^P,16),W=W+C|0,k=Ee(k^W,12),P=P+k|0,C=Ee(C^P,8),W=W+C|0,k=Ee(k^W,7),x=x+K|0,L=Ee(L^x,16),B=B+L|0,K=Ee(K^B,12),x=x+K|0,L=Ee(L^x,8),B=B+L|0,K=Ee(K^B,7),$=$+q|0,X=Ee(X^$,16),V=V+X|0,q=Ee(q^V,12),$=$+q|0,X=Ee(X^$,8),V=V+X|0,q=Ee(q^V,7),S=S+k|0,X=Ee(X^S,16),B=B+X|0,k=Ee(k^B,12),S=S+k|0,X=Ee(X^S,8),B=B+X|0,k=Ee(k^B,7),P=P+K|0,Y=Ee(Y^P,16),V=V+Y|0,K=Ee(K^V,12),P=P+K|0,Y=Ee(Y^P,8),V=V+Y|0,K=Ee(K^V,7),x=x+q|0,C=Ee(C^x,16),H=H+C|0,q=Ee(q^H,12),x=x+q|0,C=Ee(C^x,8),H=H+C|0,q=Ee(q^H,7),$=$+F|0,L=Ee(L^$,16),W=W+L|0,F=Ee(F^W,12),$=$+F|0,L=Ee(L^$,8),W=W+L|0,F=Ee(F^W,7);let Q=0;i[Q++]=o+S|0,i[Q++]=a+P|0,i[Q++]=c+x|0,i[Q++]=l+$|0,i[Q++]=h+F|0,i[Q++]=u+k|0,i[Q++]=d+K|0,i[Q++]=g+q|0,i[Q++]=p+H|0,i[Q++]=f+W|0,i[Q++]=b+B|0,i[Q++]=m+V|0,i[Q++]=w+Y|0,i[Q++]=E+C|0,i[Q++]=A+L|0,i[Q++]=_+X|0}const Z3=V3(Q3,{counterRight:!1,counterLength:4,allowShortKeys:!1}),J3=new Uint8Array(16),Vg=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(J3.subarray(t))},X3=new Uint8Array(32);function Kg(s,e,t,i,r){const n=s(e,t,X3),o=Y3.create(n);r&&Vg(o,r),Vg(o,i);const a=new Uint8Array(16),c=x3(a);Hg(c,0,BigInt(r?r.length:0),!0),Hg(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return Yn(n,a),l}const e4=s=>(e,t,i)=>({encrypt(r,n){const o=r.length;n=Bg(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);s(e,t,a,a,1);const c=Kg(s,e,t,a,i);return n.set(c,o),Yn(c),n},decrypt(r,n){n=Bg(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Kg(s,e,t,o,i);if(!R3(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),Yn(c),n}}),zm=U3({blockSize:64,nonceLength:12,tagLength:16},e4(Z3));let Fm=class extends Ru{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ju(e);const i=Gn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return Kn(this),this.iHash.update(e),this}digestInto(e){Kn(this),nl(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:i,finished:r,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Lu=(s,e,t)=>new Fm(s,e).update(t).digest();Lu.create=(s,e)=>new Fm(s,e);function t4(s,e,t){return ju(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Lu(s,Gn(t),Gn(e))}const Gl=new Uint8Array([0]),Gg=new Uint8Array;function s4(s,e,t,i=32){if(ju(s),oa(i),i>255*s.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/s.outputLen);t===void 0&&(t=Gg);const n=new Uint8Array(r*s.outputLen),o=Lu.create(s,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)Gl[0]=l+1,a.update(l===0?Gg:c).update(t).update(Gl).digestInto(c),n.set(c,s.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Gl.fill(0),n.slice(0,i)}const i4=(s,e,t,i,r)=>s4(s,t4(s,e,t),i,r);function r4(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=i?4:0,l=i?0:4;s.setUint32(e+c,o,i),s.setUint32(e+l,a,i)}function n4(s,e,t){return s&e^~s&t}function o4(s,e,t){return s&e^s&t^e&t}class a4 extends Ru{constructor(e,t,i,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Vl(this.buffer)}update(e){Kn(this);const{view:t,buffer:i,blockLen:r}=this;e=Gn(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const c=Vl(e);for(;r<=n-o;o+=r)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Kn(this),Tm(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(i,0),o=0);for(let u=o;u<r;u++)t[u]=0;r4(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=Vl(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,h[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:r,finished:n,destroyed:o,pos:a}=this;return e.length=r,e.pos=a,e.finished=n,e.destroyed=o,r%t&&e.buffer.set(i),e}}const c4=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]),qi=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Bi=new Uint32Array(64);let l4=class extends a4{constructor(){super(64,32,8,!1),this.A=qi[0]|0,this.B=qi[1]|0,this.C=qi[2]|0,this.D=qi[3]|0,this.E=qi[4]|0,this.F=qi[5]|0,this.G=qi[6]|0,this.H=qi[7]|0}get(){const{A:e,B:t,C:i,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,i,r,n,o,a,c]}set(e,t,i,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=i|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Bi[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const d=Bi[u-15],g=Bi[u-2],p=oi(d,7)^oi(d,18)^d>>>3,f=oi(g,17)^oi(g,19)^g>>>10;Bi[u]=f+Bi[u-7]+p+Bi[u-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:c,G:l,H:h}=this;for(let u=0;u<64;u++){const d=oi(a,6)^oi(a,11)^oi(a,25),g=h+d+n4(a,c,l)+c4[u]+Bi[u]|0,p=(oi(i,2)^oi(i,13)^oi(i,22))+o4(i,r,n)|0;h=l,l=c,c=a,a=o+g|0,o=n,n=r,r=i,i=g+p|0}i=i+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(i,r,n,o,a,c,l,h)}roundClean(){Bi.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const ol=Pm(()=>new l4);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qm=BigInt(0);function zu(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Bm(s){if(!zu(s))throw new Error("Uint8Array expected")}const h4=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function u4(s){Bm(s);let e="";for(let t=0;t<s.length;t++)e+=h4[s[t]];return e}function d4(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?qm:BigInt("0x"+s)}const Ni={_0:48,_9:57,A:65,F:70,a:97,f:102};function Yg(s){if(s>=Ni._0&&s<=Ni._9)return s-Ni._0;if(s>=Ni.A&&s<=Ni.F)return s-(Ni.A-10);if(s>=Ni.a&&s<=Ni.f)return s-(Ni.a-10)}function Hm(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=Yg(s.charCodeAt(n)),a=Yg(s.charCodeAt(n+1));if(o===void 0||a===void 0){const c=s[n]+s[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[r]=o*16+a}return i}function Qg(s){return Bm(s),d4(u4(Uint8Array.from(s).reverse()))}function p4(s,e){return Hm(s.toString(16).padStart(e*2,"0"))}function g4(s,e){return p4(s,e).reverse()}function Zg(s,e,t){let i;if(typeof e=="string")try{i=Hm(e)}catch(n){throw new Error(s+" must be hex string or Uint8Array, cause: "+n)}else if(zu(e))i=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");const r=i.length;if(typeof t=="number"&&r!==t)throw new Error(s+" of length "+t+" expected, got "+r);return i}const Yl=s=>typeof s=="bigint"&&qm<=s;function f4(s,e,t){return Yl(s)&&Yl(e)&&Yl(t)&&e<=s&&s<t}function Jg(s,e,t,i){if(!f4(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const w4={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||zu(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function y4(s,e,t={}){const i=(r,n,o)=>{const a=w4[n];if(typeof a!="function")throw new Error("invalid validator function");const c=s[r];if(!(o&&c===void 0)&&!a(c,s))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))i(r,n,!1);for(const[r,n]of Object.entries(t))i(r,n,!0);return s}const kn=BigInt(0),Xa=BigInt(1);function Wm(s,e){const t=s%e;return t>=kn?t:e+t}function m4(s,e,t){if(e<kn)throw new Error("invalid exponent, negatives unsupported");if(t<=kn)throw new Error("invalid modulus");if(t===Xa)return kn;let i=Xa;for(;e>kn;)e&Xa&&(i=i*s%t),s=s*s%t,e>>=Xa;return i}function Ys(s,e,t){let i=s;for(;e-- >kn;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const dn=BigInt(0),Ql=BigInt(1);function b4(s){return y4(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function v4(s){const e=b4(s),{P:t}=e,i=w=>Wm(w,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(w=>w),c=e.powPminus2||(w=>m4(w,t-BigInt(2),t));function l(w,E,A){const _=i(w*(E-A));return E=i(E-_),A=i(A+_),[E,A]}const h=(e.a-BigInt(2))/BigInt(4);function u(w,E){Jg("u",w,dn,t),Jg("scalar",E,dn,t);const A=E,_=w;let S=Ql,P=dn,x=w,$=Ql,F=dn,k;for(let q=BigInt(r-1);q>=dn;q--){const H=A>>q&Ql;F^=H,k=l(F,S,x),S=k[0],x=k[1],k=l(F,P,$),P=k[0],$=k[1],F=H;const W=S+P,B=i(W*W),V=S-P,Y=i(V*V),C=B-Y,L=x+$,X=x-$,Q=i(X*W),me=i(L*V),ue=Q+me,ee=Q-me;x=i(ue*ue),$=i(_*i(ee*ee)),S=i(B*Y),P=i(C*(B+i(h*C)))}k=l(F,S,x),S=k[0],x=k[1],k=l(F,P,$),P=k[0],$=k[1];const K=c(P);return i(S*K)}function d(w){return g4(i(w),n)}function g(w){const E=Zg("u coordinate",w,n);return o===32&&(E[31]&=127),Qg(E)}function p(w){const E=Zg("scalar",w),A=E.length;if(A!==n&&A!==o){let _=""+n+" or "+o;throw new Error("invalid scalar, expected "+_+" bytes, got "+A)}return Qg(a(E))}function f(w,E){const A=g(E),_=p(w),S=u(A,_);if(S===dn)throw new Error("invalid private or public key received");return d(S)}const b=d(e.Gu);function m(w){return f(w,b)}return{scalarMult:f,scalarMultBase:m,getSharedSecret:(w,E)=>f(w,E),getPublicKey:w=>m(w),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:b}}const Kh=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const I4=BigInt(1),Xg=BigInt(2),E4=BigInt(3),A4=BigInt(5);BigInt(8);function N4(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=Kh,o=s*s%n*s%n,a=Ys(o,Xg,n)*o%n,c=Ys(a,I4,n)*s%n,l=Ys(c,A4,n)*c%n,h=Ys(l,e,n)*l%n,u=Ys(h,t,n)*h%n,d=Ys(u,i,n)*u%n,g=Ys(d,r,n)*d%n,p=Ys(g,r,n)*d%n,f=Ys(p,e,n)*l%n;return{pow_p_5_8:Ys(f,Xg,n)*s%n,b2:o}}function _4(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const Gh=v4({P:Kh,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=Kh,{pow_p_5_8:t,b2:i}=N4(s);return Wm(Ys(t,E4,e)*i,e)},adjustScalarBytes:_4,randomBytes:Aa}),Vm="base10",Qt="base16",Xi="base64pad",$o="base64url",Na="utf8",Km=0,xi=1,_a=2,C4=0,ef=1,Vo=12,Fu=32;function S4(){const s=Gh.utils.randomPrivateKey(),e=Gh.getPublicKey(s);return{privateKey:$e(s,Qt),publicKey:$e(e,Qt)}}function Yh(){const s=Aa(Fu);return $e(s,Qt)}function T4(s,e){const t=Gh.getSharedSecret(et(s,Qt),et(e,Qt)),i=i4(ol,t,void 0,void 0,Fu);return $e(i,Qt)}function fc(s){const e=ol(et(s,Qt));return $e(e,Qt)}function ui(s){const e=ol(et(s,Na));return $e(e,Qt)}function Gm(s){return et(`${s}`,Vm)}function jr(s){return Number($e(s,Vm))}function P4(s){const e=Gm(typeof s.type<"u"?s.type:Km);if(jr(e)===xi&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?et(s.senderPublicKey,Qt):void 0,i=typeof s.iv<"u"?et(s.iv,Qt):Aa(Vo),r=et(s.symKey,Qt),n=zm(r,i).encrypt(et(s.message,Na));return Ym({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function $4(s){const e=et(s.symKey,Qt),{sealed:t,iv:i}=ca(s),r=zm(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return $e(r,Na)}function M4(s,e){const t=Gm(_a),i=Aa(Vo),r=et(s,Na);return Ym({type:t,sealed:r,iv:i,encoding:e})}function O4(s,e){const{sealed:t}=ca({encoded:s,encoding:e});return $e(t,Na)}function Ym(s){const{encoding:e=Xi}=s;if(jr(s.type)===_a)return $e(Un([s.type,s.sealed]),e);if(jr(s.type)===xi){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return $e(Un([s.type,s.senderPublicKey,s.iv,s.sealed]),e)}return $e(Un([s.type,s.iv,s.sealed]),e)}function ca(s){const{encoded:e,encoding:t=Xi}=s,i=et(e,t),r=i.slice(C4,ef),n=ef;if(jr(r)===xi){const l=n+Fu,h=l+Vo,u=i.slice(n,l),d=i.slice(l,h),g=i.slice(h);return{type:r,sealed:g,iv:d,senderPublicKey:u}}if(jr(r)===_a){const l=i.slice(n),h=Aa(Vo);return{type:r,sealed:l,iv:h}}const o=n+Vo,a=i.slice(n,o),c=i.slice(o);return{type:r,sealed:c,iv:a}}function x4(s,e){const t=ca({encoded:s,encoding:e==null?void 0:e.encoding});return Qm({type:jr(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?$e(t.senderPublicKey,Qt):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Qm(s){const e=(s==null?void 0:s.type)||Km;if(e===xi){if(typeof(s==null?void 0:s.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(s==null?void 0:s.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:s==null?void 0:s.senderPublicKey,receiverPublicKey:s==null?void 0:s.receiverPublicKey}}function tf(s){return s.type===xi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function sf(s){return s.type===_a}function D4(s){return new kw.ec("p256").keyFromPublic({x:T.Buffer.from(s.x,"base64").toString("hex"),y:T.Buffer.from(s.y,"base64").toString("hex")},"hex")}function k4(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function j4(s){return T.Buffer.from(k4(s),"base64")}function R4(s,e){const[t,i,r]=s.split("."),n=j4(r);if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32).toString("hex"),a=n.slice(32,64).toString("hex"),c=`${t}.${i}`,l=ol(c),h=D4(e),u=$e(l,Qt);if(!h.verify(u,{r:o,s:a}))throw new Error("Invalid signature");return Bn(s).payload}const U4="irn";function kc(s){return(s==null?void 0:s.relay)||{protocol:U4}}function Lo(s){const e=lw[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function L4(s,e="-"){const t={},i="relay"+e;return Object.keys(s).forEach(r=>{if(r.startsWith(i)){const n=r.replace(i,""),o=s[r];t[n]=o}}),t}function rf(s){if(!s.includes("wc:")){const l=Sm(s);l!=null&&l.includes("wc:")&&(s=l)}s=s.includes("wc://")?s.replace("wc://",""):s,s=s.includes("wc:")?s.replace("wc:",""):s;const e=s.indexOf(":"),t=s.indexOf("?")!==-1?s.indexOf("?"):void 0,i=s.substring(0,e),r=s.substring(e+1,t).split("@"),n=typeof t<"u"?s.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((l,h)=>{a[h]=l});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:z4(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:L4(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function z4(s){return s.startsWith("//")?s.substring(2):s}function F4(s,e="-"){const t="relay",i={};return Object.keys(s).forEach(r=>{const n=r,o=t+e+n;s[n]&&(i[o]=s[n])}),i}function nf(s){const e=new URLSearchParams,t=F4(s.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",s.symKey),s.expiryTimestamp&&e.set("expiryTimestamp",s.expiryTimestamp.toString()),s.methods&&e.set("methods",s.methods.join(","));const i=e.toString();return`${s.protocol}:${s.topic}@${s.version}?${i}`}function ec(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function oo(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function q4(s){const e=[];return Object.values(s).forEach(t=>{e.push(...oo(t.accounts))}),e}function B4(s,e){const t=[];return Object.values(s).forEach(i=>{oo(i.accounts).includes(e)&&t.push(...i.methods)}),t}function H4(s,e){const t=[];return Object.values(s).forEach(i=>{oo(i.accounts).includes(e)&&t.push(...i.events)}),t}function qu(s){return s.includes(":")}function zo(s){return qu(s)?s.split(":")[0]:s}function W4(s){const e={};return s==null||s.forEach(t=>{var i;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(i=e[r].chains)==null||i.push(`${r}:${n}`)}),e}function of(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=W4(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=pc(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const V4={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}},K4={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 U(s,e){const{message:t,code:i}=K4[s];return{message:e?`${t} ${e}`:t,code:i}}function Ue(s,e){const{message:t,code:i}=V4[s];return{message:e?`${t} ${e}`:t,code:i}}function Rr(s,e){return!!Array.isArray(s)}function la(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function zt(s){return typeof s>"u"}function ft(s,e){return e&&zt(s)?!0:typeof s=="string"&&!!s.trim().length}function Bu(s,e){return e&&zt(s)?!0:typeof s=="number"&&!isNaN(s)}function G4(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return Sr(r,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=s.namespaces[o],h=oo(a),u=t[o];(!Sr(Em(o,u),h)||!Sr(u.methods,c)||!Sr(u.events,l))&&(n=!1)}),n):!1}function jc(s){return ft(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function Y4(s){if(ft(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&jc(t)}}return!1}function Q4(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(ft(s,!1)){if(e(s))return!0;const t=Sm(s);return e(t)}}catch{}return!1}function Z4(s){var e;return(e=s==null?void 0:s.proposer)==null?void 0:e.publicKey}function J4(s){return s==null?void 0:s.topic}function X4(s,e){let t=null;return ft(s==null?void 0:s.publicKey,!1)||(t=U("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function af(s){let e=!0;return Rr(s)?s.length&&(e=s.every(t=>ft(t,!1))):e=!1,e}function ej(s,e,t){let i=null;return Rr(e)&&e.length?e.forEach(r=>{i||jc(r)||(i=Ue("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):jc(s)||(i=Ue("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function tj(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=ej(r,Em(r,n),`${e} ${t}`);o&&(i=o)}),i}function sj(s,e){let t=null;return Rr(s)?s.forEach(i=>{t||Y4(i)||(t=Ue("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Ue("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function ij(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=sj(i==null?void 0:i.accounts,`${e} namespace`);r&&(t=r)}),t}function rj(s,e){let t=null;return af(s==null?void 0:s.methods)?af(s==null?void 0:s.events)||(t=Ue("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Ue("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function Zm(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=rj(i,`${e}, namespace`);r&&(t=r)}),t}function nj(s,e,t){let i=null;if(s&&la(s)){const r=Zm(s,e);r&&(i=r);const n=tj(s,e,t);n&&(i=n)}else i=U("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function Zl(s,e){let t=null;if(s&&la(s)){const i=Zm(s,e);i&&(t=i);const r=ij(s,e);r&&(t=r)}else t=U("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Jm(s){return ft(s.protocol,!0)}function oj(s,e){let t=!1;return s?s&&Rr(s)&&s.length&&s.forEach(i=>{t=Jm(i)}):t=!0,t}function aj(s){return typeof s=="number"}function os(s){return typeof s<"u"&&typeof s!==null}function cj(s){return!(!s||typeof s!="object"||!s.code||!Bu(s.code,!1)||!s.message||!ft(s.message,!1))}function lj(s){return!(zt(s)||!ft(s.method,!1))}function hj(s){return!(zt(s)||zt(s.result)&&zt(s.error)||!Bu(s.id,!1)||!ft(s.jsonrpc,!1))}function uj(s){return!(zt(s)||!ft(s.name,!1))}function cf(s,e){return!(!jc(e)||!q4(s).includes(e))}function dj(s,e,t){return ft(t,!1)?B4(s,e).includes(t):!1}function pj(s,e,t){return ft(t,!1)?H4(s,e).includes(t):!1}function lf(s,e,t){let i=null;const r=gj(s),n=fj(e),o=Object.keys(r),a=Object.keys(n),c=hf(Object.keys(s)),l=hf(Object.keys(e)),h=c.filter(u=>!l.includes(u));return h.length&&(i=U("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
|
|
@@ -895,7 +895,7 @@ ${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+T.Buffer.from(a3(t)).toS
|
|
|
895
895
|
.wui-color-fg-350 {
|
|
896
896
|
background-color: var(--wui-color-fg-350);
|
|
897
897
|
}
|
|
898
|
-
`,oc={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};function Sa(s){return{formatters:void 0,fees:void 0,serializers:void 0,...s}}const du=Sa({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"}),pu=Sa({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"}),u8=Sa({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"});Sa({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});Sa({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 d8={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"]},$b={getMethodsByChainNamespace(s){return d8[s]||[]},createDefaultNamespace(s){return{methods:this.getMethodsByChainNamespace(s),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(s,e){if(!e)return{...s};const t={...s},i=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>i.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>i.add(r)),e.events&&Object.keys(e.events).forEach(r=>i.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[n]=r.split(":");n&&i.add(n)}),i.forEach(r=>{t[r]||(t[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,n])=>{t[r]&&(t[r].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([r,n])=>{t[r]&&(t[r].chains=n)}),e.events&&Object.entries(e.events).forEach(([r,n])=>{t[r]&&(t[r].events=n)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,c]=n.split(":");!a||!c||!t[a]||(t[a].rpcMap||(t[a].rpcMap={}),r.has(a)||(t[a].rpcMap={},r.add(a)),t[a].rpcMap[c]=o)})}return t},createNamespaces(s,e){const t=s.reduce((i,r)=>{const{id:n,chainNamespace:o,rpcUrls:a}=r,c=a.default.http[0];i[o]||(i[o]=this.createDefaultNamespace(o));const l=`${o}:${n}`,h=i[o];switch(h.chains.push(l),l){case du.caipNetworkId:h.chains.push(du.deprecatedCaipNetworkId);break;case pu.caipNetworkId:h.chains.push(pu.deprecatedCaipNetworkId);break}return h!=null&&h.rpcMap&&c&&(h.rpcMap[n]=c),i},{});return this.applyNamespaceOverrides(t,e)},resolveReownName:async s=>{var i;const e=await cm.resolveName(s);return((i=(Object.values(e==null?void 0:e.addresses)||[])[0])==null?void 0:i.address)||!1},getChainsFromNamespaces(s={}){return Object.values(s).flatMap(e=>{const t=e.chains||[],i=e.accounts.map(r=>{const[n,o]=r.split(":");return`${n}:${o}`});return Array.from(new Set([...t,...i]))})},isSessionEventData(s){return typeof s=="object"&&s!==null&&"id"in s&&"topic"in s&&"params"in s&&typeof s.params=="object"&&s.params!==null&&"chainId"in s.params&&"event"in s.params&&typeof s.params.event=="object"&&s.params.event!==null}};class Mb{constructor({provider:e,caipNetworks:t,namespace:i}){this.id=te.CONNECTOR_ID.WALLET_CONNECT,this.name=Rc.ConnectorNamesMap[te.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Rc.ConnectorImageIds[te.CONNECTOR_ID.WALLET_CONNECT],this.caipNetworks=t,this.provider=e,this.chain=i}get chains(){return this.caipNetworks}async connectWalletConnect(){if(!await this.authenticate()){const t=j.state.universalProviderConfigOverride,i=$b.createNamespaces(this.caipNetworks,t);await this.provider.connect({optionalNamespaces:i})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(t=>t.caipNetworkId);return Wo.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:p8})}}const p8=["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 g8{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,e&&this.construct(e)}construct(e){this.caipNetworks=e.networks,this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.caipNetworks||[]}setAuthProvider(e){this.addConnector({id:te.CONNECTOR_ID.AUTH,type:"AUTH",name:te.CONNECTOR_NAMES.AUTH,provider:e,imageId:Rc.ConnectorImageIds[te.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(i=>t.has(i.id)?!1:(t.add(i.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,t){se.setStatus(e,t)}on(e,t){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(t)}off(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,t){const i=this.eventListeners.get(e);i&&i.forEach(r=>r(t))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:t,providerType:i}=e;if(!e.provider)return;const r="provider"in e.provider?e.provider.provider:e.provider;if(i==="WALLET_CONNECT"){r.setDefaultChain(t.caipNetworkId);return}if(r&&i==="AUTH"){const n=r;await n.switchNetwork(t.caipNetworkId);const o=await n.getUser({chainId:t.caipNetworkId,preferredAccountType:j.state.defaultAccountTypes[t.chainNamespace]});this.emit("switchNetwork",o)}}getWalletConnectConnector(){const e=this.connectors.find(t=>t instanceof Mb);if(!e)throw new Error("WalletConnectConnector not found");return e}}class f8 extends g8{setUniversalProvider(e){this.addConnector(new Mb({provider:e,caipNetworks:this.caipNetworks||[],namespace:this.namespace}))}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){var r,n,o,a;const t=this.provider,i=((a=(o=(n=(r=t==null?void 0:t.session)==null?void 0:r.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const[,,l]=c.split(":");return l}).filter((c,l,h)=>h.indexOf(c)===l))||[];return Promise.resolve({accounts:i.map(c=>ce.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var n,o,a,c,l;if(!(e.caipNetwork&&ls.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(se.state.balanceLoading&&e.chainId===((c=v.state.activeCaipNetwork)==null?void 0:c.id))return{balance:se.state.balance||"0.00",symbol:se.state.balanceSymbol||""};const r=(await se.fetchTokenBalance()).find(h=>{var u,d;return h.chainId===`${(u=e.caipNetwork)==null?void 0:u.chainNamespace}:${e.chainId}`&&h.symbol===((d=e.caipNetwork)==null?void 0:d.nativeCurrency.symbol)});return{balance:(r==null?void 0:r.quantity.numeric)||"0.00",symbol:(r==null?void 0:r.symbol)||((l=e.caipNetwork)==null?void 0:l.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,c;const{provider:t,message:i,address:r}=e;if(!t)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return((o=v.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===te.CHAIN.SOLANA?n=(await t.request({method:"solana_signMessage",params:{message:Im.encode(new TextEncoder().encode(i)),pubkey:r}},(a=v.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:n=await t.request({method:"personal_sign",params:[i,r]},(c=v.state.activeCaipNetwork)==null?void 0:c.caipNetworkId),{signature:n}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async getProfile(){return Promise.resolve({profileImage:"",profileName:""})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}async getEnsAddress(){return Promise.resolve({address:!1})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){var r,n,o,a,c,l;const{caipNetwork:t}=e,i=this.getWalletConnectConnector();if(t.chainNamespace===te.CHAIN.EVM)try{await((r=i.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:wd(t.id)}]}))}catch(h){if(h.code===oc.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||h.code===oc.ERROR_INVALID_CHAIN_ID||h.code===oc.ERROR_CODE_DEFAULT||((o=(n=h==null?void 0:h.data)==null?void 0:n.originalError)==null?void 0:o.code)===oc.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=i.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:wd(t.id),rpcUrls:[(a=t==null?void 0:t.rpcUrls.chainDefault)==null?void 0:a.http],chainName:t.name,nativeCurrency:t.nativeCurrency,blockExplorerUrls:[(c=t.blockExplorers)==null?void 0:c.default.url]}]}))}catch{throw new Error("Chain is not supported")}}i.provider.setDefaultChain(t.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(i=>i.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}class w8{constructor(e){var t;this.hasSwitchedToPreferredAccountTypeOnConnect=!1,this.chainNamespaces=[],this.reportedAlertErrors={},this.getCaipNetwork=i=>{var r,n;if(i){const o=(r=v.getNetworkData(i))==null?void 0:r.caipNetwork;return o||((n=v.getRequestedCaipNetworks(i).filter(a=>a.chainNamespace===i))==null?void 0:n[0])}return v.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const i=this.getCaipNetwork();if(i)return i.id},this.getCaipNetworks=i=>v.getRequestedCaipNetworks(i),this.getActiveChainNamespace=()=>v.state.activeChain,this.setRequestedCaipNetworks=(i,r)=>{v.setRequestedCaipNetworks(i,r)},this.getApprovedCaipNetworkIds=()=>v.getAllApprovedCaipNetworkIds(),this.getCaipAddress=i=>v.state.activeChain===i||!i?v.state.activeCaipAddress:v.getAccountProp("caipAddress",i),this.setClientId=i=>{re.setClientId(i)},this.getProvider=i=>rt.getProvider(i),this.getProviderType=i=>rt.getProviderId(i),this.getPreferredAccountType=()=>se.state.preferredAccountType,this.setCaipAddress=(i,r)=>{se.setCaipAddress(i,r)},this.setBalance=(i,r,n)=>{se.setBalance(i,r,n)},this.setProfileName=(i,r)=>{se.setProfileName(i,r)},this.setProfileImage=(i,r)=>{se.setProfileImage(i,r)},this.setUser=(i,r)=>{se.setUser(i,r),j.state.enableEmbedded&&wt.close()},this.resetAccount=i=>{se.resetAccount(i)},this.setCaipNetwork=i=>{v.setActiveCaipNetwork(i)},this.setCaipNetworkOfNamespace=(i,r)=>{v.setChainNetworkData(r,{caipNetwork:i})},this.setAllAccounts=(i,r)=>{se.setAllAccounts(i,r),j.setHasMultipleAddresses((i==null?void 0:i.length)>1)},this.setStatus=(i,r)=>{se.setStatus(i,r),ae.isConnected()?J.setConnectionStatus("connected"):J.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=i=>v.getAccountProp("address",i),this.setConnectors=i=>{const r=[...ae.getConnectors(),...i];ae.setConnectors(r)},this.fetchIdentity=i=>re.fetchIdentity(i),this.getReownName=i=>cm.getNamesForAddress(i),this.getConnectors=()=>ae.getConnectors(),this.getConnectorImage=i=>nm.getConnectorImage(i),this.setConnectedWalletInfo=(i,r)=>{const n=rt.getProviderId(r),o=i?{...i,type:n}:void 0;se.setConnectedWalletInfo(o,r)},this.getIsConnectedState=()=>!!v.state.activeCaipAddress,this.addAddressLabel=(i,r,n)=>{se.addAddressLabel(i,r,n)},this.removeAddressLabel=(i,r)=>{se.removeAddressLabel(i,r)},this.getAddress=i=>v.state.activeChain===i||!i?se.state.address:v.getAccountProp("address",i),this.setApprovedCaipNetworksData=i=>v.setApprovedCaipNetworksData(i),this.resetNetwork=i=>{v.resetNetwork(i)},this.addConnector=i=>{ae.addConnector(i)},this.resetWcConnection=()=>{Ve.resetWcConnection()},this.setAddressExplorerUrl=(i,r)=>{se.setAddressExplorerUrl(i,r)},this.setSmartAccountDeployed=(i,r)=>{se.setSmartAccountDeployed(i,r)},this.setSmartAccountEnabledNetworks=(i,r)=>{v.setSmartAccountEnabledNetworks(i,r)},this.setPreferredAccountType=(i,r)=>{se.setPreferredAccountType(i,r)},this.setEIP6963Enabled=i=>{j.setEIP6963Enabled(i)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=[...new Set((t=this.caipNetworks)==null?void 0:t.map(i=>i.chainNamespace))],this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.initialize(e),this.sendInitializeEvent(e)}async initialize(e){this.initControllers(e),await this.initChainAdapters(),await this.injectModalUi(),await this.syncExistingConnection(),Oi.set({initialized:!0})}sendInitializeEvent(e){var i;const{...t}=e;delete t.adapters,Ke.sendEvent({type:"track",event:"INITIALIZE",properties:{...t,networks:e.networks.map(r=>r.id),siweConfig:{options:((i=e.siweConfig)==null?void 0:i.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&Jt.setThemeMode(e.themeMode),e.themeVariables&&Jt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");v.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&v.setActiveCaipNetwork(t)}initializeConnectionController(e){Ve.setWcBasic(e.basic??!1)}initializeConnectorController(){ae.initialize(this.chainNamespaces)}initializeOptionsController(e){var r;j.setDebug(e.debug!==!1),j.setEnableWalletConnect(e.enableWalletConnect!==!1),j.setEnableWalletGuide(e.enableWalletGuide!==!1),j.setEnableWallets(e.enableWallets!==!1),j.setEIP6963Enabled(e.enableEIP6963!==!1),j.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),j.setEnableAuthLogger(e.enableAuthLogger!==!1),j.setCustomRpcUrls(e.customRpcUrls),j.setSdkVersion(e.sdkVersion),j.setProjectId(e.projectId),j.setEnableEmbedded(e.enableEmbedded),j.setAllWallets(e.allWallets),j.setIncludeWalletIds(e.includeWalletIds),j.setExcludeWalletIds(e.excludeWalletIds),j.setFeaturedWalletIds(e.featuredWalletIds),j.setTokens(e.tokens),j.setTermsConditionsUrl(e.termsConditionsUrl),j.setPrivacyPolicyUrl(e.privacyPolicyUrl),j.setCustomWallets(e.customWallets),j.setFeatures(e.features),j.setAllowUnsupportedChain(e.allowUnsupportedChain),j.setDefaultAccountTypes(e.defaultAccountTypes),j.setUniversalProviderConfigOverride(e.universalProviderConfigOverride);const t=this.getDefaultMetaData();if(!e.metadata&&t&&(e.metadata=t),j.setMetadata(e.metadata),j.setDisableAppend(e.disableAppend),j.setEnableEmbedded(e.enableEmbedded),j.setSIWX(e.siwx),!e.projectId){dc.open(nc.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((r=e.adapters)==null?void 0:r.find(n=>n.namespace===te.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");j.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,t,i,r;return typeof window<"u"&&typeof document<"u"?{name:((t=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:t.textContent)||"",description:((i=document.querySelector('meta[property="og:description"]'))==null?void 0:i.content)||"",url:window.location.origin,icons:[((r=document.querySelector('link[rel~="icon"]'))==null?void 0:r.href)||""]}:null}setUnsupportedNetwork(e){const t=this.getActiveChainNamespace();if(t){const i=On.getUnsupportedNetwork(`${t}:${e}`);v.setActiveCaipNetwork(i)}}getDefaultNetwork(){return On.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return On.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return On.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const t=e.networks.find(r=>{var n;return r.id===((n=e.defaultNetwork)==null?void 0:n.id)});return t?On.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var n;const e=v.state.activeChain,t=this.getAdapter(e),i=(n=this.getCaipNetwork(e))==null?void 0:n.id;if(!t)throw new Error("Adapter not found");const r=await t.connectWalletConnect(i);this.close(),this.setClientId((r==null?void 0:r.clientId)||null),J.setConnectedNamespaces([...v.state.chains.keys()]),this.chainNamespaces.forEach(o=>{ae.setConnectorId(Hi.CONNECTOR_TYPE_WALLET_CONNECT,o)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:t,type:i,provider:r,chain:n,caipNetwork:o})=>{var g,p,f,b,m,w,E;const a=v.state.activeChain,c=n||a,l=this.getAdapter(c);if(n&&n!==a&&!o){const A=(g=this.caipNetworks)==null?void 0:g.find(_=>_.chainNamespace===n);A&&this.setCaipNetwork(A)}if(!l)throw new Error("Adapter not found");const h=this.getCaipNetwork(c),u=await l.connect({id:e,info:t,type:i,provider:r,chainId:(o==null?void 0:o.id)||(h==null?void 0:h.id),rpcUrl:((b=(f=(p=o==null?void 0:o.rpcUrls)==null?void 0:p.default)==null?void 0:f.http)==null?void 0:b[0])||((E=(w=(m=h==null?void 0:h.rpcUrls)==null?void 0:m.default)==null?void 0:w.http)==null?void 0:E[0])});if(!u)return;J.addConnectedNamespace(c),this.syncProvider({...u,chainNamespace:c}),await this.syncAccount({...u,chainNamespace:c});const{accounts:d}=await l.getAccounts({namespace:c,id:e});this.setAllAccounts(d,c)},reconnectExternal:async({id:e,info:t,type:i,provider:r})=>{var a;const n=v.state.activeChain,o=this.getAdapter(n);o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:t,type:i,provider:r,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),J.addConnectedNamespace(n))},disconnect:async e=>{const t=e||v.state.activeChain,i=this.getAdapter(t),r=rt.getProvider(t),n=rt.getProviderId(t);await(i==null?void 0:i.disconnect({provider:r,providerType:n})),J.removeConnectedNamespace(t),rt.resetChain(t),this.setUser(void 0,t),this.setStatus("disconnected",t),this.hasSwitchedToPreferredAccountTypeOnConnect=!1},checkInstalled:e=>e?e.some(t=>{var i;return!!((i=window.ethereum)!=null&&i[String(t)])}):!!window.ethereum,signMessage:async e=>{const t=this.getAdapter(v.state.activeChain),i=await(t==null?void 0:t.signMessage({message:e,address:se.state.address,provider:rt.getProvider(v.state.activeChain)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{if(e.chainNamespace===te.CHAIN.EVM){const t=this.getAdapter(v.state.activeChain),i=rt.getProvider(v.state.activeChain),r=await(t==null?void 0:t.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}));return(r==null?void 0:r.hash)||""}return""},estimateGas:async e=>{if(e.chainNamespace===te.CHAIN.EVM){const t=this.getAdapter(v.state.activeChain),i=rt.getProvider(v.state.activeChain),r=this.getCaipNetwork();if(!r)throw new Error("CaipNetwork is undefined");const n=await(t==null?void 0:t.estimateGas({...e,provider:i,caipNetwork:r}));return(n==null?void 0:n.gas)||0n}return 0n},getEnsAvatar:async()=>{var i;const e=this.getAdapter(v.state.activeChain),t=await(e==null?void 0:e.getProfile({address:se.state.address,chainId:Number((i=this.getCaipNetwork())==null?void 0:i.id)}));return(t==null?void 0:t.profileImage)||!1},getEnsAddress:async e=>{const t=this.getAdapter(v.state.activeChain),i=this.getCaipNetwork();if(!i)return!1;const r=await(t==null?void 0:t.getEnsAddress({name:e,caipNetwork:i}));return(r==null?void 0:r.address)||!1},writeContract:async e=>{const t=this.getAdapter(v.state.activeChain),i=this.getCaipNetwork(),r=this.getCaipAddress(),n=rt.getProvider(v.state.activeChain);if(!i||!r)throw new Error("CaipNetwork or CaipAddress is undefined");const o=await(t==null?void 0:t.writeContract({...e,caipNetwork:i,provider:n,caipAddress:r}));return o==null?void 0:o.hash},parseUnits:(e,t)=>{const i=this.getAdapter(v.state.activeChain);return(i==null?void 0:i.parseUnits({value:e,decimals:t}))??0n},formatUnits:(e,t)=>{const i=this.getAdapter(v.state.activeChain);return(i==null?void 0:i.formatUnits({value:e,decimals:t}))??"0"},getCapabilities:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.getCapabilities(e))},grantPermissions:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.grantPermissions(e))},revokePermissions:async e=>{const t=this.getAdapter(v.state.activeChain);return t!=null&&t.revokePermissions?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.walletGetAssets(e))??{}}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Ve.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){var t,i,r,n,o;if(rt.getProviderId(v.state.activeChain)===Hi.CONNECTOR_TYPE_WALLET_CONNECT){const a=(i=(t=this.universalProvider)==null?void 0:t.session)==null?void 0:i.namespaces;return{supportsAllNetworks:((o=(n=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:n.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const t=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=rt.getProvider(t),n=rt.getProviderId(t);if(e.chainNamespace===v.state.activeChain){const o=this.getAdapter(t);await(o==null?void 0:o.switchNetwork({caipNetwork:e,provider:r,providerType:n}))}else if(this.setCaipNetwork(e),n===Hi.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(t);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(t=>{const i=t.chains||[],r=t.accounts.map(n=>{const{chainId:o,chainNamespace:a}=zi.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...i,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((t,i)=>{var n;const r=e==null?void 0:e.find(o=>o.namespace===i);return r?(t[i]=r,t[i].namespace=i,t[i].construct({namespace:i,projectId:(n=this.options)==null?void 0:n.projectId,networks:this.caipNetworks})):t[i]=new f8({namespace:i,networks:this.caipNetworks}),t},{})}async initChainAdapter(e){var t;this.onConnectors(e),this.listenAdapter(e),(t=this.chainAdapters)==null||t[e].syncConnectors(this.options,this),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){const t=this.getAdapter(e);t==null||t.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const t=this.getAdapter(e);if(!t)return;const i=J.getConnectionStatus();i==="connected"?this.setStatus("connecting",e):i==="disconnected"?(J.clearAddressCache(),this.setStatus(i,e)):this.setStatus(i,e),t.on("switchNetwork",({address:r,chainId:n})=>{var l;const o=(l=this.caipNetworks)==null?void 0:l.find(h=>h.id===n||h.caipNetworkId===n),a=v.state.activeChain===e,c=v.getAccountProp("address",e);if(o){const h=a&&r?r:c;h&&this.syncAccount({address:h,chainId:n,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),t.on("disconnect",this.disconnect.bind(this,e)),t.on("pendingTransactions",()=>{const r=se.state.address,n=v.state.activeCaipNetwork;!r||!(n!=null&&n.id)||this.updateNativeBalance(r,n.id,n.chainNamespace)}),t.on("accountChanged",({address:r,chainId:n})=>{var a,c;const o=v.state.activeChain===e;o&&n?this.syncAccount({address:r,chainId:n,chainNamespace:e}):o&&((a=v.state.activeCaipNetwork)!=null&&a.id)?this.syncAccount({address:r,chainId:(c=v.state.activeCaipNetwork)==null?void 0:c.id,chainNamespace:e}):this.syncAccountInfo(r,n,e)})}async createUniversalProviderForAdapter(e){var t,i,r;await this.getUniversalProvider(),this.universalProvider&&((r=(i=(t=this.chainAdapters)==null?void 0:t[e])==null?void 0:i.setUniversalProvider)==null||r.call(i,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{const t=ae.getConnectorId(e);switch(this.setStatus("connecting",e),t){case te.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case te.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(t){console.warn("AppKit couldn't sync existing connection",t),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){var o,a,c;const t=this.getAdapter(e),i=ae.getConnectorId(e),r=this.getCaipNetwork(e),n=ae.getConnectors(e).find(l=>l.id===i);try{if(!t||!n)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(r!=null&&r.id))throw new Error("CaipNetwork not found");const l=await(t==null?void 0:t.syncConnection({namespace:e,id:n.id,chainId:r.id,rpcUrl:(c=(a=(o=r==null?void 0:r.rpcUrls)==null?void 0:o.default)==null?void 0:a.http)==null?void 0:c[0]}));if(l){const h=await(t==null?void 0:t.getAccounts({namespace:e,id:n.id}));h&&h.accounts.length>0?this.setAllAccounts(h.accounts,e):this.setAllAccounts([ce.createAccount(e,l.address,"eoa")],e),this.syncProvider({...l,chainNamespace:e}),await this.syncAccount({...l,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async t=>{var a,c,l,h,u;const i=this.getAdapter(t),r=((h=(l=(c=(a=this.universalProvider)==null?void 0:a.session)==null?void 0:c.namespaces)==null?void 0:l[t])==null?void 0:h.accounts)||[],n=(u=v.state.activeCaipNetwork)==null?void 0:u.id,o=r.find(d=>{const{chainId:g}=zi.parseCaipAddress(d);return g===(n==null?void 0:n.toString())})||r[0];if(o){const d=zi.validateCaipAddress(o),{chainId:g,address:p}=zi.parseCaipAddress(d);if(rt.setProviderId(t,Hi.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&v.state.activeCaipNetwork&&(i==null?void 0:i.namespace)!==te.CHAIN.EVM){const f=i==null?void 0:i.getWalletConnectProvider({caipNetworks:this.caipNetworks,provider:this.universalProvider,activeCaipNetwork:v.state.activeCaipNetwork});rt.setProvider(t,f)}else rt.setProvider(t,this.universalProvider);ae.setConnectorId(te.CONNECTOR_ID.WALLET_CONNECT,t),J.addConnectedNamespace(t),this.syncWalletConnectAccounts(t),await this.syncAccount({address:p,chainId:g,chainNamespace:t})}else this.setStatus("disconnected",t);await v.setApprovedCaipNetworksData(t)});await Promise.all(e)}syncWalletConnectAccounts(e){var i,r,n,o,a;const t=(a=(o=(n=(r=(i=this.universalProvider)==null?void 0:i.session)==null?void 0:r.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const{address:l}=zi.parseCaipAddress(c);return l}).filter((c,l,h)=>h.indexOf(c)===l);t&&this.setAllAccounts(t.map(c=>ce.createAccount(e,c,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:i,chainNamespace:r}){rt.setProviderId(r,e),rt.setProvider(r,t),ae.setConnectorId(i,r)}async syncAccount(e){var u,d,g,p,f,b;const t=e.chainNamespace===v.state.activeChain,i=v.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:n,chainNamespace:o}=e,{chainId:a}=J.getActiveNetworkProps(),c=n||a,l=((u=v.state.activeCaipNetwork)==null?void 0:u.name)===te.UNSUPPORTED_NETWORK_NAME,h=v.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!h)&&c){let m=(d=this.caipNetworks)==null?void 0:d.find(A=>A.id.toString()===c.toString()),w=(g=this.caipNetworks)==null?void 0:g.find(A=>A.chainNamespace===o);if(!h&&!m&&!w){const A=this.getApprovedCaipNetworkIds()||[],_=A.find(P=>{var x;return((x=zi.parseCaipNetworkId(P))==null?void 0:x.chainId)===c.toString()}),S=A.find(P=>{var x;return((x=zi.parseCaipNetworkId(P))==null?void 0:x.chainNamespace)===o});m=(p=this.caipNetworks)==null?void 0:p.find(P=>P.caipNetworkId===_),w=(f=this.caipNetworks)==null?void 0:f.find(P=>P.caipNetworkId===S||"deprecatedCaipNetworkId"in P&&P.deprecatedCaipNetworkId===S)}const E=m||w;(E==null?void 0:E.chainNamespace)===v.state.activeChain?j.state.enableNetworkSwitch&&!j.state.allowUnsupportedChain&&((b=v.state.activeCaipNetwork)==null?void 0:b.name)===te.UNSUPPORTED_NETWORK_NAME?v.showUnsupportedChainUI():this.setCaipNetwork(E):t||i&&this.setCaipNetworkOfNamespace(i,o),this.syncConnectedWalletInfo(o),Tb.isLowerCaseMatch(r,se.state.address)||this.syncAccountInfo(r,E==null?void 0:E.id,o),t?await this.syncBalance({address:r,chainId:E==null?void 0:E.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:i==null?void 0:i.id,chainNamespace:o})}}async syncAccountInfo(e,t,i){const r=this.getCaipAddress(i),n=t||(r==null?void 0:r.split(":")[1]);if(!n)return;const o=`${i}:${n}:${e}`;this.setCaipAddress(o,i),await this.syncIdentity({address:e,chainId:n,chainNamespace:i})}async syncReownName(e,t){try{const i=await this.getReownName(e);if(i[0]){const r=i[0];this.setProfileName(r.name,t)}else this.setProfileName(null,t)}catch{this.setProfileName(null,t)}}syncConnectedWalletInfo(e){var r;const t=ae.getConnectorId(e),i=rt.getProviderId(e);if(i===Hi.CONNECTOR_TYPE_ANNOUNCED||i===Hi.CONNECTOR_TYPE_INJECTED){if(t){const n=this.getConnectors().find(o=>o.id===t);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(i===Hi.CONNECTOR_TYPE_WALLET_CONNECT){const n=rt.getProvider(e);n!=null&&n.session&&this.setConnectedWalletInfo({...n.session.peer.metadata,name:n.session.peer.metadata.name,icon:(r=n.session.peer.metadata.icons)==null?void 0:r[0]},e)}else if(t)if(t===te.CONNECTOR_ID.COINBASE){const n=this.getConnectors().find(o=>o.id===te.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(n)},e)}else this.setConnectedWalletInfo({name:t},e)}async syncBalance(e){!rm.getNetworksByNamespace(this.caipNetworks,e.chainNamespace).find(i=>{var r;return i.id.toString()===((r=e.chainId)==null?void 0:r.toString())})||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async updateNativeBalance(e,t,i){const r=this.getAdapter(i);if(r){const n=await r.getBalance({address:e,chainId:t,caipNetwork:this.getCaipNetwork(i),tokens:this.options.tokens});this.setBalance(n.balance,n.symbol,i)}}async initializeUniversalAdapter(){var i,r,n,o,a,c,l,h,u,d;const e=o8.createLogger((g,...p)=>{g&&this.handleAlertError(g),console.error(...p)}),t={projectId:(i=this.options)==null?void 0:i.projectId,metadata:{name:(r=this.options)!=null&&r.metadata?(n=this.options)==null?void 0:n.metadata.name:"",description:(o=this.options)!=null&&o.metadata?(a=this.options)==null?void 0:a.metadata.description:"",url:(c=this.options)!=null&&c.metadata?(l=this.options)==null?void 0:l.metadata.url:"",icons:(h=this.options)!=null&&h.metadata?(u=this.options)==null?void 0:u.metadata.icons:[""]},logger:e};j.setManualWCControl(!!((d=this.options)!=null&&d.manualWCControl)),this.universalProvider=this.options.universalProvider??await Ku.init(t),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{Ve.setUri(e)}),this.universalProvider.on("connect",Ve.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),Ve.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{var r;const t=(r=this.caipNetworks)==null?void 0:r.find(n=>n.id==e),i=this.getCaipNetwork();if(!t){this.setUnsupportedNetwork(e);return}(i==null?void 0:i.id)!==(t==null?void 0:t.id)&&this.setCaipNetwork(t)}),this.universalProvider.on("session_event",e=>{if($b.isSessionEventData(e)){const{name:t,data:i}=e.params.event;t==="accountsChanged"&&Array.isArray(i)&&ce.isCaipAddress(i[0])&&this.syncAccount(zi.parseCaipAddress(i[0]))}}))}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&ce.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){Ke.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const t=Object.entries(nc.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[i,r]=t??[],{message:n,alertErrorKey:o}=r??{};if(i&&n&&!this.reportedAlertErrors[i]){const a=nc.ALERT_ERRORS[o];a&&(dc.open(a,"error"),this.reportedAlertErrors[i]=!0)}}getAdapter(e){var t;if(e)return(t=this.chainAdapters)==null?void 0:t[e]}createAdapter(e){var r;if(!e)return;const t=e.namespace;if(!t)return;this.createClients();const i=e;i.namespace=t,i.construct({namespace:t,projectId:(r=this.options)==null?void 0:r.projectId,networks:this.caipNetworks}),this.chainNamespaces.includes(t)||this.chainNamespaces.push(t),this.chainAdapters&&(this.chainAdapters[t]=i)}async open(e){await this.injectModalUi(),e!=null&&e.uri&&Ve.setUri(e.uri),await wt.open(e)}async close(){await this.injectModalUi(),wt.close()}setLoading(e,t){wt.setLoading(e,t)}async disconnect(e){await Ve.disconnect(e)}getError(){return""}getChainId(){var e;return(e=v.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e){var i;const t=(i=this.caipNetworks)==null?void 0:i.find(r=>r.id===e.id);if(!t){dc.open(nc.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await v.switchActiveNetwork(t)}getWalletProvider(){return v.state.activeChain?rt.state.providers[v.state.activeChain]:null}getWalletProviderType(){return rt.getProviderId(v.state.activeChain)}subscribeProviders(e){return rt.subscribeProviders(e)}getThemeMode(){return Jt.state.themeMode}getThemeVariables(){return Jt.state.themeVariables}setThemeMode(e){Jt.setThemeMode(e),Pb(Jt.state.themeMode)}setTermsConditionsUrl(e){j.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){j.setPrivacyPolicyUrl(e)}setThemeVariables(e){Jt.setThemeVariables(e),h8(Jt.state.themeVariables)}subscribeTheme(e){return Jt.subscribe(e)}getWalletInfo(){return se.state.connectedWalletInfo}getAccount(e){const t=ae.getAuthConnector(e),i=v.getAccountData(e);if(i)return{allAccounts:i.allAccounts,caipAddress:i.caipAddress,address:ce.getPlainAddress(i.caipAddress),isConnected:!!i.caipAddress,status:i.status,embeddedWalletInfo:t?{user:i.user,authProvider:i.socialProvider||"email",accountType:i.preferredAccountType,isSmartAccountDeployed:!!i.smartAccountDeployed}:void 0}}subscribeAccount(e,t){const i=()=>{const r=this.getAccount(t);r&&e(r)};t?v.subscribeChainProp("accountState",i,t):v.subscribe(i),ae.subscribe(i)}subscribeNetwork(e){return v.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t==null?void 0:t.id,caipNetworkId:t==null?void 0:t.caipNetworkId})})}subscribeWalletInfo(e){return se.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){se.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){v.subscribeKey("activeCaipNetwork",e)}getState(){return Oi.state}subscribeState(e){return Oi.subscribe(e)}showErrorMessage(e){Lt.showError(e)}showSuccessMessage(e){Lt.showSuccess(e)}getEvent(){return{...Ke.state}}subscribeEvents(e){return Ke.subscribe(e)}replace(e){De.replace(e)}redirect(e){De.push(e)}popTransactionStack(e){De.popTransactionStack(e)}isOpen(){return wt.state.open}isTransactionStackEmpty(){return De.state.transactionStack.length===0}isTransactionShouldReplaceView(){var e;return(e=De.state.transactionStack[De.state.transactionStack.length-1])==null?void 0:e.replace}static getInstance(){return this.instance}updateFeatures(e){j.setFeatures(e)}updateOptions(e){const i={...j.state||{},...e};j.setOptions(i)}setConnectMethodsOrder(e){j.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){j.setWalletFeaturesOrder(e)}setCollapseWallets(e){j.setCollapseWallets(e)}setSocialsOrder(e){j.setSocialsOrder(e)}getConnectMethodsOrder(){return uu.getConnectOrderMethod(j.state.features,ae.getConnectors())}removeAdapter(e){var n;const t=this.getIsConnectedState(),i=this.getAdapter(e);if(!i||!this.chainAdapters||t)return;const r=(n=this.caipNetworks)==null?void 0:n.filter(o=>o.chainNamespace!==e);v.removeAdapter(e),ae.removeAdapter(e),this.chainNamespaces=this.chainNamespaces.filter(o=>o!==e),this.caipNetworks=r,i.removeAllEventListeners(),Reflect.deleteProperty(this.chainAdapters,e)}addAdapter(e,t){const i=e.namespace;if(!this.connectionControllerClient||!this.networkControllerClient||!this.chainAdapters||!i)return;const r=this.extendCaipNetworks({...this.options,networks:t});this.caipNetworks=[...this.caipNetworks||[],...r],this.createAdapter(e),this.initChainAdapter(i),v.addAdapter(e,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient},r)}addNetwork(e,t){var r;if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const i=this.extendCaipNetwork(t,this.options);v.addNetwork(i),this.caipNetworks&&!((r=this.caipNetworks)!=null&&r.find(n=>n.id===i.id))&&this.caipNetworks.push(i)}removeNetwork(e,t){var n;if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);if(!((n=this.caipNetworks)==null?void 0:n.find(o=>o.id===t)))throw new Error(`Network with ID ${t} not found`);if(!this.caipNetworks)return;const r=this.caipNetworks.filter(o=>o.chainNamespace===e&&o.id!==t);if(!(r!=null&&r.length))throw new Error("Cannot remove last network for a namespace");v.removeNetwork(e,t),this.caipNetworks=[...r]}}let Jf=!1;class y8 extends w8{async open(e){ae.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&Ve.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!Jf&&ce.isClient()){if(await Zo(()=>import("./basic-ChNCp6rI.js"),__vite__mapDeps([13,10,11,14,15,1,2,16,5,6,7,8,9])),await Zo(()=>import("./w3m-modal-DdptuLHe.js"),__vite__mapDeps([17,10,11,14,15,1,2,5,6,7,8,9])),!document.querySelector("w3m-modal")){const t=document.createElement("w3m-modal");!j.state.disableAppend&&!j.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",t)}Jf=!0}}}const m8="1.7.2";function b8(s){return new y8({...s,basic:!0,sdkVersion:`html-core-${m8}`})}function v8(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const h=s.charAt(l),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let h=0,u=0,d=0;const g=l.length;for(;d!==g&&l[d]===0;)d++,h++;const p=(g-d)*n+1>>>0,f=new Uint8Array(p);for(;d!==g;){let w=l[d],E=0;for(let A=p-1;(w!==0||E<u)&&A!==-1;A--,E++)w+=256*f[A]>>>0,f[A]=w%t>>>0,w=w/t>>>0;if(w!==0)throw new Error("Non-zero carry");u=E,d++}let b=p-u;for(;b!==p&&f[b]===0;)b++;let m=i.repeat(h);for(;b<p;++b)m+=s.charAt(f[b]);return m}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;l[h]===i;)u++,h++;const g=(l.length-h)*r+1>>>0,p=new Uint8Array(g);for(;h<l.length;){const w=l.charCodeAt(h);if(w>255)return;let E=e[w];if(E===255)return;let A=0;for(let _=g-1;(E!==0||A<d)&&_!==-1;_--,A++)E+=t*p[_]>>>0,p[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=A,h++}let f=g-d;for(;f!==g&&p[f]===0;)f++;const b=new Uint8Array(u+(g-f));let m=u;for(;f!==g;)b[m++]=p[f++];return b}function c(l){const h=a(l);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var I8="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const uh=v8(I8);class Rn extends Error{constructor(){super(),Object.setPrototypeOf(this,Rn.prototype)}}class Xf extends Error{constructor(e){super(`WalletConnect Adapter - Method ${e} is not supported by the wallet`),this.name="WalletConnectFeatureNotSupportedError"}}function E8(s){let e=[s];return s===vt.Mainnet||s===vt.Deprecated_Mainnet?(e=[vt.Mainnet,vt.Deprecated_Mainnet],s===vt.Deprecated_Mainnet&&console.warn(Lc.mainnet)):(s===vt.Deprecated_Devnet||s===vt.Devnet)&&(e=[vt.Devnet,vt.Deprecated_Devnet],console.warn(Lc.devnet)),e}const Lc={mainnet:`You are using a deprecated chain ID for Solana Mainnet, please use ${vt.Mainnet} instead.`,devnet:`You are using a deprecated chain ID for Solana Devnet, please use ${vt.Devnet} instead.`,wallet:"The connected wallet is using a deprecated chain ID for Solana. Please, contact them to upgrade. You can learn more at https://github.com/ChainAgnostic/namespaces/blob/main/solana/caip10.md#chain-ids"};function ew(s,e){var i;const t=(i=s.namespaces.solana)==null?void 0:i.accounts.map(r=>`solana:${r.split(":")[1]}`);if(e===vt.Mainnet)return t!=null&&t.find(r=>r===vt.Mainnet)?vt.Mainnet:(console.warn(Lc.wallet),vt.Deprecated_Mainnet);if(e===vt.Devnet)return t!=null&&t.find(r=>r===vt.Devnet)?vt.Devnet:(console.warn(Lc.wallet),vt.Deprecated_Devnet);throw Error("WalletConnect Solana Adapter: Unable to get a default chain from the session.")}function A8(s){return{optionalNamespaces:{solana:{chains:E8(s),methods:[xs.signTransaction,xs.signMessage],events:[]}}}}class Gu extends Error{constructor(){super("QR Code Modal was closed by user"),Object.setPrototypeOf(this,Gu.prototype),this.name="QRCodeModalError"}}class N8{constructor(e){$t(this,"_UniversalProvider");$t(this,"_session");$t(this,"_modal");$t(this,"_projectId");$t(this,"_network");$t(this,"_ConnectQueueResolver");if(this.initClient(e.options),this._network=e.network,!e.options.projectId)throw Error("WalletConnect Adapter: Project ID is undefined");this._projectId=e.options.projectId}async connect(){var r,n,o,a,c,l;if(this._UniversalProvider||await new Promise(h=>{this._ConnectQueueResolver=h}),!this._UniversalProvider)throw new Error("WalletConnect Adapter - Universal Provider was undefined while calling 'connect()'");if(this._UniversalProvider.session){this._session=this._UniversalProvider.session;const h=ew(this._session,this._network);return this._network=h,this._UniversalProvider.setDefaultChain(h),{publicKey:this.publicKey}}await this.initModal();const e=A8(this._network);(r=this._modal)==null||r.open();const t=new AbortController,i=t.signal;(n=this._modal)==null||n.subscribeState(h=>{h.open||t.abort(new Gu)});try{const h=await Promise.race([(o=this._UniversalProvider)==null?void 0:o.connect(e),new Promise((d,g)=>{i.addEventListener("abort",()=>{g(i.reason)})})]);if((a=this._modal)==null||a.close(),this._session=h,!h)throw new Hc;const u=ew(h,this._network);return this._network=u,(c=this._UniversalProvider)==null||c.setDefaultChain(u),{publicKey:this.publicKey}}catch(h){throw(l=this._modal)==null||l.close(),h}}async disconnect(){var e;if((e=this._UniversalProvider)!=null&&e.session){if(await this.initModal(),!this._modal)throw Error("WalletConnect Adapter -Modal is undefined: unable to disconnect");await this.client.disconnect(),this._session=void 0}else throw new Rn}get client(){if(this._UniversalProvider)return this._UniversalProvider;throw new Rn}get session(){if(!this._session)throw new Rn;return this._session}get publicKey(){var e,t,i;if((e=this._UniversalProvider)!=null&&e.session&&this._session){const{address:r}=TI(((i=(t=this._session)==null?void 0:t.namespaces.solana)==null?void 0:i.accounts[0])??"");return new di(r)}throw new Rn}async signTransaction(e){this.checkIfWalletSupportsMethod(xs.signTransaction);const t=$i(e),i=t?{}:e,{signature:r,transaction:n}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:xs.signTransaction,params:{...i,transaction:this.serialize(e)}}});return n?this.deserialize(n,t):(e.addSignature(this.publicKey,T.Buffer.from(uh.decode(r))),e)}async signMessage(e){this.checkIfWalletSupportsMethod(xs.signMessage);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:xs.signMessage,params:{pubkey:this.publicKey.toString(),message:uh.encode(e)}}});return uh.decode(t)}async signAndSendTransaction(e){this.checkIfWalletSupportsMethod(xs.signAndSendTransaction);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:xs.signAndSendTransaction,params:{transaction:this.serialize(e)}}});return t}async signAllTransactions(e){try{this.checkIfWalletSupportsMethod(xs.signAllTransactions);const t=e.map(r=>this.serialize(r)),{transactions:i}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:xs.signAllTransactions,params:{transactions:t}}});return e.map((r,n)=>$i(r)?this.deserialize(i[n]??"",!0):this.deserialize(i[n]??""))}catch(t){if(t instanceof Xf){const i=e.map(n=>this.signTransaction(n));return await Promise.all(i)}throw t}}async initClient(e){const t=await Gx.init(e);this._UniversalProvider=t,this._ConnectQueueResolver&&this._ConnectQueueResolver(!0)}async initModal(){if(!this._modal){if(!this._UniversalProvider)throw new Error("WalletConnect Adapter - cannot init modal when Universal Provider is undefined");this._modal=b8({projectId:this._projectId,universalProvider:this._UniversalProvider,networks:[du,pu,u8],manualWCControl:!0})}}serialize(e){return T.Buffer.from(e.serialize({verifySignatures:!1})).toString("base64")}deserialize(e,t=!1){return t?vc.deserialize(T.Buffer.from(e,"base64")):Ic.from(T.Buffer.from(e,"base64"))}checkIfWalletSupportsMethod(e){var t;if(!((t=this.session.namespaces.solana)!=null&&t.methods.includes(e)))throw new Xf(e)}}const _8="WalletConnect";class C8 extends mu{constructor(t){super();$t(this,"name",_8);$t(this,"url","https://walletconnect.org");$t(this,"icon","data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjE4NSIgdmlld0JveD0iMCAwIDMwMCAxODUiIHdpZHRoPSIzMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTYxLjQzODU0MjkgMzYuMjU2MjYxMmM0OC45MTEyMjQxLTQ3Ljg4ODE2NjMgMTI4LjIxMTk4NzEtNDcuODg4MTY2MyAxNzcuMTIzMjA5MSAwbDUuODg2NTQ1IDUuNzYzNDE3NGMyLjQ0NTU2MSAyLjM5NDQwODEgMi40NDU1NjEgNi4yNzY1MTEyIDAgOC42NzA5MjA0bC0yMC4xMzY2OTUgMTkuNzE1NTAzYy0xLjIyMjc4MSAxLjE5NzIwNTEtMy4yMDUzIDEuMTk3MjA1MS00LjQyODA4MSAwbC04LjEwMDU4NC03LjkzMTE0NzljLTM0LjEyMTY5Mi0zMy40MDc5ODE3LTg5LjQ0Mzg4Ni0zMy40MDc5ODE3LTEyMy41NjU1Nzg4IDBsLTguNjc1MDU2MiA4LjQ5MzYwNTFjLTEuMjIyNzgxNiAxLjE5NzIwNDEtMy4yMDUzMDEgMS4xOTcyMDQxLTQuNDI4MDgwNiAwbC0yMC4xMzY2OTQ5LTE5LjcxNTUwMzFjLTIuNDQ1NTYxMi0yLjM5NDQwOTItMi40NDU1NjEyLTYuMjc2NTEyMiAwLTguNjcwOTIwNHptMjE4Ljc2Nzc5NjEgNDAuNzczNzQ0OSAxNy45MjE2OTcgMTcuNTQ2ODk3YzIuNDQ1NTQ5IDIuMzk0Mzk2OSAyLjQ0NTU2MyA2LjI3NjQ3NjkuMDAwMDMxIDguNjcwODg5OWwtODAuODEwMTcxIDc5LjEyMTEzNGMtMi40NDU1NDQgMi4zOTQ0MjYtNi40MTA1ODIgMi4zOTQ0NTMtOC44NTYxNi4wMDAwNjItLjAwMDAxLS4wMDAwMS0uMDAwMDIyLS4wMDAwMjItLjAwMDAzMi0uMDAwMDMybC01Ny4zNTQxNDMtNTYuMTU0NTcyYy0uNjExMzktLjU5ODYwMi0xLjYwMjY1LS41OTg2MDItMi4yMTQwNCAwLS4wMDAwMDQuMDAwMDA0LS4wMDAwMDcuMDAwMDA4LS4wMDAwMTEuMDAwMDExbC01Ny4zNTI5MjEyIDU2LjE1NDUzMWMtMi40NDU1MzY4IDIuMzk0NDMyLTYuNDEwNTc1NSAyLjM5NDQ3Mi04Ljg1NjE2MTIuMDAwMDg3LS4wMDAwMTQzLS4wMDAwMTQtLjAwMDAyOTYtLjAwMDAyOC0uMDAwMDQ0OS0uMDAwMDQ0bC04MC44MTI0MTk0My03OS4xMjIxODVjLTIuNDQ1NTYwMjEtMi4zOTQ0MDgtMi40NDU1NjAyMS02LjI3NjUxMTUgMC04LjY3MDkxOTdsMTcuOTIxNzI5NjMtMTcuNTQ2ODY3M2MyLjQ0NTU2MDItMi4zOTQ0MDgyIDYuNDEwNTk4OS0yLjM5NDQwODIgOC44NTYxNjAyIDBsNTcuMzU0OTc3NSA1Ni4xNTUzNTdjLjYxMTM5MDguNTk4NjAyIDEuNjAyNjQ5LjU5ODYwMiAyLjIxNDAzOTggMCAuMDAwMDA5Mi0uMDAwMDA5LjAwMDAxNzQtLjAwMDAxNy4wMDAwMjY1LS4wMDAwMjRsNTcuMzUyMTAzMS01Ni4xNTUzMzNjMi40NDU1MDUtMi4zOTQ0NjMzIDYuNDEwNTQ0LTIuMzk0NTUzMSA4Ljg1NjE2MS0uMDAwMi4wMDAwMzQuMDAwMDMzNi4wMDAwNjguMDAwMDY3My4wMDAxMDEuMDAwMTAxbDU3LjM1NDkwMiA1Ni4xNTU0MzJjLjYxMTM5LjU5ODYwMSAxLjYwMjY1LjU5ODYwMSAyLjIxNDA0IDBsNTcuMzUzOTc1LTU2LjE1NDMyNDljMi40NDU1NjEtMi4zOTQ0MDkyIDYuNDEwNTk5LTIuMzk0NDA5MiA4Ljg1NjE2IDB6IiBmaWxsPSIjM2I5OWZjIi8+PC9zdmc+");$t(this,"supportedTransactionVersions",new Set(["legacy",0]));$t(this,"_publicKey");$t(this,"_connecting");$t(this,"_wallet");$t(this,"_config");$t(this,"_readyState");$t(this,"_onDisconnect");this._publicKey=null,this._connecting=!1,this._config=t,this._wallet=null,this._readyState=typeof window>"u"?de.Unsupported:de.Loadable,this._onDisconnect=this.disconnect.bind(this)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==de.Loadable)throw new or;this._connecting=!0,this._wallet=new N8({network:this._config.network===Xo.Mainnet?Nc.Mainnet:Nc.Devnet,options:this._config.options});const{publicKey:t}=await this._wallet.connect();this._publicKey=t,this.emit("connect",t),this._wallet.client.on("session_delete",this._onDisconnect)}catch(t){throw t.constructor.name==="QRCodeModalError"||t instanceof Error&&t.name==="QRCodeModalError"?new i0:(this._connecting=!1,t)}finally{this._connecting=!1}}async disconnect(){const t=this._wallet;if(t){t.client.off("session_delete",this._onDisconnect),this._publicKey=null;try{t.client.session&&await t.disconnect()}catch(i){console.error("WalletConnectWalletAdapter: disconnect error",i),this.emit("error",new ha(i==null?void 0:i.message,i))}}this.emit("disconnect")}async signTransaction(t){try{const i=this._wallet;if(!i)throw new Ge;try{return await i.signTransaction(t)}catch(r){throw new at(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signMessage(t){try{const i=this._wallet;if(!i)throw new Ge;try{return await i.signMessage(t)}catch(r){throw new ua(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signAndSendTransaction(t){try{const i=this._wallet;if(!i)throw new Ge;try{return await i.signAndSendTransaction(t)}catch(r){throw new at(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signAllTransactions(t){try{const i=this._wallet;if(!i)throw new Ge;try{return await i.signAllTransactions(t)}catch(r){throw new at(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}}const S8={icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgdmlld0JveD0iMCAwIDI1NiAyNTYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8yMDM1XzExMDYpIj4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IiM1NEZGRjUiLz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjBfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTEzLjQ4MDYgMTk4LjYwNUMtMjkuMzI3NiAzMTkuMDQzIDE5OS42NjEgMjg1LjAyNyAzMTkuNTA3IDI1Mi45NjRDNDQyLjE2NSAyMTIuMjU5IDM1Ny4zODYgMzIuODI2OSAyNjkuNDE1IDI4Ljg1NThDMTgxLjQ0MyAyNC44ODQ3IDI4MC4zMjIgMTExLjgyNCAyMDUuNTk1IDEzNi42NTZDMTMwLjg2OCAxNjEuNDg3IDY2Ljk5MDcgNDguMDU4MyAxMy40ODA2IDE5OC42MDVaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjxnIGZpbHRlcj0idXJsKCNmaWx0ZXIxX2ZfMjAzNV8xMTA2KSI+CjxwYXRoIGQ9Ik04NS41MTE4IC00NS44MjI1QzYzLjA1NjIgLTEwNy4xNzYgLTE2LjkxODkgLTIzLjk5NTMgLTU0LjA5OTUgMjUuMjY0M0MtODkuNTY1MiA3OC44NDc5IDMuMDA5MzcgMTI1LjE1MiAzOS4zMjA4IDEwMC4wMzdDNzUuNjMyMyA3NC45MjI3IDcuNzc0NDggNzAuMDM2MyAyOS4zNzA4IDM3LjM3ODVDNTAuOTY3MSA0LjcyMDc2IDExMy41ODEgMzAuODY5NSA4NS41MTE4IC00NS44MjI1WiIgZmlsbD0iIzAwRkZGMCIgZmlsbC1vcGFjaXR5PSIwLjY3Ii8+CjwvZz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjJfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTk2LjQ3OTYgMjI1LjQyNEM2NS44NTAyIDEyMi4zNjMgLTY2LjA4MTggMTc2LjYzNyAtMTI4LjIxOSAyMTYuNjU3Qy0xODcuOTkgMjY0LjA0MiAtNDYuMDcxMSA0MDAuMzQ4IDEyLjg3MjUgMzkzLjM3NkM3MS44MTYxIDM4Ni40MDMgLTM0LjQxMTggMzI3LjA2NSAxLjk4NzAyIDI5OC4xN0MzOC4zODU4IDI2OS4yNzYgMTM0Ljc2NiAzNTQuMjQ5IDk2LjQ3OTYgMjI1LjQyNFoiIGZpbGw9IiM5RDgxRkYiLz4KPC9nPgo8ZyBmaWx0ZXI9InVybCgjZmlsdGVyM19mXzIwMzVfMTEwNikiPgo8cGF0aCBkPSJNMjgyLjEyIC0xMDcuMzUzQzIxNi4wNDcgLTE4Ni4wMzEgMTIxLjQ2MyAtMTIwLjk3IDgyLjQyOTYgLTc4LjYwNDdDNDguMjczOSAtMzAuNjQ0NiAyMjQuMjc1IDU3LjIzMTIgMjczLjEyMSA0Mi4xNzE0QzMyMS45NjggMjcuMTExNSAyMDYuNTEyIC00LjA1MDM4IDIyNy4yOTcgLTMzLjI4NzlDMjQ4LjA4MiAtNjIuNTI1NSAzNjQuNzEyIC05LjAwNTY2IDI4Mi4xMiAtMTA3LjM1M1oiIGZpbGw9IiM0RDk0RkYiLz4KPC9nPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkzLjE4OSAxNTIuODM2SDEzNi42NzRMODcuMjA4NiAxMDMuMDUxTDEzNy4zMSA1My4yNjYzTDE1MC45NTUgNDBIMTA1LjgxOUw0OC4zMzU5IDk3Ljc3NzNDNDUuNDM0OSAxMDAuNjg5IDQ1LjQ0OTggMTA1LjQwMiA0OC4zNjU2IDEwOC4yOTlMOTMuMTg5IDE1Mi44MzZaTTExOS4zMyAxMDMuMTY4SDExOC45OTVMMTE5LjMyNiAxMDMuMTY0TDExOS4zMyAxMDMuMTY4Wk0xMTkuMzMgMTAzLjE2OEwxNjguNzkxIDE1Mi45NDlMMTE4LjY5IDIwMi43MzRMMTA1LjA0NSAyMTZIMTUwLjE4TDIwNy42NjQgMTU4LjIyNkMyMTAuNTY1IDE1NS4zMTQgMjEwLjU1IDE1MC42MDIgMjA3LjYzNCAxNDcuNzA1TDE2Mi44MTEgMTAzLjE2OEgxMTkuMzNaIiBmaWxsPSJibGFjayIvPgo8L2c+CjxkZWZzPgo8ZmlsdGVyIGlkPSJmaWx0ZXIwX2ZfMjAzNV8xMTA2IiB4PSItOTAuMjQxMSIgeT0iLTY5LjczNjkiIHdpZHRoPSI1NjkuNTU4IiBoZWlnaHQ9IjQ1MS40MzEiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyMV9mXzIwMzVfMTEwNiIgeD0iLTE2MC41MTEiIHk9Ii0xNjUuOTg3IiB3aWR0aD0iMzUxLjU5NiIgaGVpZ2h0PSIzNzEuNTA3IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxmaWx0ZXIgaWQ9ImZpbHRlcjJfZl8yMDM1XzExMDYiIHg9Ii0yNDEuMDc4IiB5PSI2Ny42NDIiIHdpZHRoPSI0NDQuODUxIiBoZWlnaHQ9IjQyNC40NTIiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyM19mXzIwMzVfMTEwNiIgeD0iLTIwLjM5NjgiIHk9Ii0yNDIuNzU4IiB3aWR0aD0iNDMwLjE5MSIgaGVpZ2h0PSIzODUuMTA1IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxjbGlwUGF0aCBpZD0iY2xpcDBfMjAzNV8xMTA2Ij4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==",name:"Bitget Wallet"},T8=[S8],P8=s=>T8.find(e=>e.name.toLocaleLowerCase().includes(s.name.toLocaleLowerCase()))||s,$8=(s,e,t)=>e[s]||t[s],tw=(s,e)=>$8(s,P8(e),e);class Si extends Vv{constructor(e,t){super(),this.adapter=e,this.connection=t}getAdapter(){return this.adapter}getName(){return tw("name",this.adapter)}getUrl(){return this.adapter.url}async connect(){if(this.isConnected())return this.getAddresses();const e=await new Promise((t,i)=>{this.adapter.on("connect",()=>{this.adapter.off("connect"),this.adapter.off("error"),t(this.getAddresses())}),this.adapter.on("error",r=>{this.adapter.off("connect"),this.adapter.off("error"),i(r)}),this.adapter.connect().catch(i)});return this.emit("connect"),this.adapter.on("disconnect",()=>this.emit("disconnect")),e}getNetworkInfo(){return{}}isConnected(){return this.adapter.connected}async disconnect(){this.isConnected()&&(await new Promise((e,t)=>{this.adapter.on("disconnect",()=>{this.adapter.off("disconnect"),this.adapter.off("error"),e(void 0)}),this.adapter.on("error",i=>{this.adapter.off("disconnect"),this.adapter.off("error"),t(i)}),this.adapter.disconnect().catch(t)}),this.adapter.removeAllListeners(),this.emit("disconnect"))}getChainId(){return pd}getAddress(){var e;return(e=this.adapter.publicKey)==null?void 0:e.toString()}getAddresses(){const e=this.getAddress();return e?[e]:[]}setMainAddress(){throw new Error("Not supported")}getBalance(){throw new Error("Not supported")}async signTransaction(e){if(!this.adapter.signTransaction||!this.adapter.signAllTransactions)throw new Error("Not supported");return Array.isArray(e)?this.adapter.signAllTransactions(e):this.adapter.signTransaction(e)}async sendTransaction(e){var n;const{transaction:t}=e,i=Array.isArray(t)?t:[t];if(i.length===0)throw new Error("Empty transactions array");const r=[];for(const o of i){const a=await this.adapter.sendTransaction(o,this.connection,{...e.options});r.push(a)}return await this.connection.confirmTransaction(r[0],(n=e.options)==null?void 0:n.commitment),{id:r[0],data:r.length===1?r[0]:r}}async signAndSendTransaction(e){return this.sendTransaction(e)}signMessage(e){if(!this.adapter.signMessage)throw new Error("Not supported");return this.adapter.signMessage(e)}getIcon(){return tw("icon",this.adapter)}getWalletState(){const e=this.adapter.readyState;if(!(e in gd))throw new Error(`Unknown wallet state ${e}`);return gd[e]}getFeatures(){const e=[Ra.SendTransaction,Ra.SignAndSendTransaction];return this.adapter.signTransaction&&this.adapter.signAllTransactions&&e.push(Ra.SignTransaction),this.adapter.signMessage&&e.push(Ra.SignMessage),e}supportsChain(e){return e===pd}}function M8(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const h=s.charAt(l),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let h=0,u=0,d=0;const g=l.length;for(;d!==g&&l[d]===0;)d++,h++;const p=(g-d)*n+1>>>0,f=new Uint8Array(p);for(;d!==g;){let w=l[d],E=0;for(let A=p-1;(w!==0||E<u)&&A!==-1;A--,E++)w+=256*f[A]>>>0,f[A]=w%t>>>0,w=w/t>>>0;if(w!==0)throw new Error("Non-zero carry");u=E,d++}let b=p-u;for(;b!==p&&f[b]===0;)b++;let m=i.repeat(h);for(;b<p;++b)m+=s.charAt(f[b]);return m}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;l[h]===i;)u++,h++;const g=(l.length-h)*r+1>>>0,p=new Uint8Array(g);for(;h<l.length;){const w=l.charCodeAt(h);if(w>255)return;let E=e[w];if(E===255)return;let A=0;for(let _=g-1;(E!==0||A<d)&&_!==-1;_--,A++)E+=t*p[_]>>>0,p[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=A,h++}let f=g-d;for(;f!==g&&p[f]===0;)f++;const b=new Uint8Array(u+(g-f));let m=u;for(;f!==g;)b[m++]=p[f++];return b}function c(l){const h=a(l);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var O8="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const x8=M8(O8);var Z=function(s,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!i:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(s):i?i.value:e.get(s)},pt=function(s,e,t,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(s,t):r?r.value=t:e.set(s,t),t},Ut,as,Tr,Pr,Ir,qo,zc,Ne,Fc,gu,bc,fu,Qo,wu,sw,iw,rw,nw;class D8 extends bw{get name(){return Z(this,Ne,"f").name}get url(){return"https://github.com/solana-labs/wallet-standard"}get icon(){return Z(this,Ne,"f").icon}get readyState(){return Z(this,Fc,"f")}get publicKey(){return Z(this,Tr,"f")}get connecting(){return Z(this,Pr,"f")}get supportedTransactionVersions(){return Z(this,zc,"f")}get wallet(){return Z(this,Ne,"f")}get standard(){return!0}constructor({wallet:e}){super(),Ut.add(this),as.set(this,void 0),Tr.set(this,void 0),Pr.set(this,void 0),Ir.set(this,void 0),qo.set(this,void 0),zc.set(this,void 0),Ne.set(this,void 0),Fc.set(this,typeof window>"u"||typeof document>"u"?de.Unsupported:de.Installed),wu.set(this,t=>{if("accounts"in t){const i=Z(this,Ne,"f").accounts[0];Z(this,as,"f")&&!Z(this,Ir,"f")&&i!==Z(this,as,"f")&&(i?Z(this,Ut,"m",bc).call(this,i):(this.emit("error",new mw),Z(this,Ut,"m",fu).call(this)))}"features"in t&&Z(this,Ut,"m",Qo).call(this)}),pt(this,Ne,e,"f"),pt(this,as,null,"f"),pt(this,Tr,null,"f"),pt(this,Pr,!1,"f"),pt(this,Ir,!1,"f"),pt(this,qo,Z(this,Ne,"f").features[Iw].on("change",Z(this,wu,"f")),"f"),Z(this,Ut,"m",Qo).call(this)}destroy(){pt(this,as,null,"f"),pt(this,Tr,null,"f"),pt(this,Pr,!1,"f"),pt(this,Ir,!1,"f");const e=Z(this,qo,"f");e&&(pt(this,qo,null,"f"),e())}async autoConnect(){return Z(this,Ut,"m",gu).call(this,{silent:!0})}async connect(){return Z(this,Ut,"m",gu).call(this)}async disconnect(){if(md in Z(this,Ne,"f").features)try{pt(this,Ir,!0,"f"),await Z(this,Ne,"f").features[md].disconnect()}catch(e){this.emit("error",new ha(e==null?void 0:e.message,e))}finally{pt(this,Ir,!1,"f")}Z(this,Ut,"m",fu).call(this)}async sendTransaction(e,t,i={}){try{const r=Z(this,as,"f");if(!r)throw new Ge;let n;if(Gi in Z(this,Ne,"f").features)if(r.features.includes(Gi))n=Gi;else if(Rt in Z(this,Ne,"f").features&&r.features.includes(Rt))n=Rt;else throw new ks;else if(Rt in Z(this,Ne,"f").features){if(!r.features.includes(Rt))throw new ks;n=Rt}else throw new xn;const o=E0(t.rpcEndpoint);if(!r.chains.includes(o))throw new _r;try{const{signers:a,...c}=i;let l;if($i(e)?(a!=null&&a.length&&e.sign(a),l=e.serialize()):(e=await this.prepareTransaction(e,t,c),a!=null&&a.length&&e.partialSign(...a),l=new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))),n===Gi){const[h]=await Z(this,Ne,"f").features[Gi].signAndSendTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:vl(c.preflightCommitment||t.commitment),skipPreflight:c.skipPreflight,maxRetries:c.maxRetries,minContextSlot:c.minContextSlot}});return x8.encode(h.signature)}else{const[h]=await Z(this,Ne,"f").features[Rt].signTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:vl(c.preflightCommitment||t.commitment),minContextSlot:c.minContextSlot}});return await t.sendRawTransaction(h.signedTransaction,{...c,preflightCommitment:vl(c.preflightCommitment||t.commitment)})}}catch(a){throw a instanceof Ft?a:new _r(a==null?void 0:a.message,a)}}catch(r){throw this.emit("error",r),r}}}as=new WeakMap,Tr=new WeakMap,Pr=new WeakMap,Ir=new WeakMap,qo=new WeakMap,zc=new WeakMap,Ne=new WeakMap,Fc=new WeakMap,wu=new WeakMap,Ut=new WeakSet,gu=async function(e){try{if(this.connected||this.connecting)return;if(Z(this,Fc,"f")!==de.Installed)throw new or;if(pt(this,Pr,!0,"f"),!Z(this,Ne,"f").accounts.length)try{await Z(this,Ne,"f").features[vw].connect(e)}catch(i){throw new Hc(i==null?void 0:i.message,i)}const t=Z(this,Ne,"f").accounts[0];if(!t)throw new ks;Z(this,Ut,"m",bc).call(this,t)}catch(t){throw this.emit("error",t),t}finally{pt(this,Pr,!1,"f")}},bc=function(e){let t;try{t=new di(e.address)}catch(i){throw new Ur(i==null?void 0:i.message,i)}pt(this,as,e,"f"),pt(this,Tr,t,"f"),Z(this,Ut,"m",Qo).call(this),this.emit("connect",t)},fu=function(){pt(this,as,null,"f"),pt(this,Tr,null,"f"),Z(this,Ut,"m",Qo).call(this),this.emit("disconnect")},Qo=function(){var t,i;const e=Gi in Z(this,Ne,"f").features?Z(this,Ne,"f").features[Gi].supportedTransactionVersions:Z(this,Ne,"f").features[Rt].supportedTransactionVersions;pt(this,zc,Qv(e,["legacy"])?null:new Set(e),"f"),Rt in Z(this,Ne,"f").features&&((t=Z(this,as,"f"))!=null&&t.features.includes(Rt))?(this.signTransaction=Z(this,Ut,"m",sw),this.signAllTransactions=Z(this,Ut,"m",iw)):(delete this.signTransaction,delete this.signAllTransactions),go in Z(this,Ne,"f").features&&((i=Z(this,as,"f"))!=null&&i.features.includes(go))?this.signMessage=Z(this,Ut,"m",rw):delete this.signMessage,ml in Z(this,Ne,"f").features?this.signIn=Z(this,Ut,"m",nw):delete this.signIn},sw=async function(e){try{const t=Z(this,as,"f");if(!t)throw new Ge;if(!(Rt in Z(this,Ne,"f").features))throw new xn;if(!t.features.includes(Rt))throw new ks;try{const r=(await Z(this,Ne,"f").features[Rt].signTransaction({account:t,transaction:$i(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return $i(e)?vc.deserialize(r):Ic.from(r)}catch(i){throw i instanceof Ft?i:new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},iw=async function(e){try{const t=Z(this,as,"f");if(!t)throw new Ge;if(!(Rt in Z(this,Ne,"f").features))throw new xn;if(!t.features.includes(Rt))throw new ks;try{const i=await Z(this,Ne,"f").features[Rt].signTransaction(...e.map(r=>({account:t,transaction:$i(r)?r.serialize():new Uint8Array(r.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((r,n)=>{const o=i[n].signedTransaction;return $i(r)?vc.deserialize(o):Ic.from(o)})}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},rw=async function(e){try{const t=Z(this,as,"f");if(!t)throw new Ge;if(!(go in Z(this,Ne,"f").features))throw new xn;if(!t.features.includes(go))throw new ks;try{return(await Z(this,Ne,"f").features[go].signMessage({account:t,message:e}))[0].signature}catch(i){throw new ua(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},nw=async function(e={}){try{if(!(ml in Z(this,Ne,"f").features))throw new xn;let t;try{[t]=await Z(this,Ne,"f").features[ml].signIn(e)}catch(i){throw new yd(i==null?void 0:i.message,i)}if(!t)throw new yd;return Z(this,Ut,"m",bc).call(this,t.account),t}catch(t){throw this.emit("error",t),t}};function k8(s){return Zv().get().filter(r0).map(e=>new Si(new D8({wallet:e}),s))}function j8(s){return s.includes("rpcpool.com")?"triton":s.includes("helius-rpc.com")?"helius":s.includes("rpc.ankr.com")?"ankr":"unknown"}async function R8(s,e,t,i){const r=i.transaction.transaction,n=o=>o.programId.toString()!=="ComputeBudget111111111111111111111111111111";if(ac(r)){const o=(await Promise.all(r.message.addressTableLookups.map(c=>s.getAddressLookupTable(c.accountKey)))).map(c=>c.value).filter(c=>c!==null),a=aw.decompile(r.message,{addressLookupTableAccounts:o});a.recentBlockhash=e,r.message.recentBlockhash=e,a.instructions=a.instructions.filter(n),r.message=a.compileToV0Message(o),a.instructions.push(...await ow(s,r)),r.message=a.compileToV0Message(o),r.sign(i.transaction.signers??[])}else r.recentBlockhash=e,r.lastValidBlockHeight=t,r.instructions=r.instructions.filter(n),r.add(...await ow(s,r)),i.transaction.signers&&r.partialSign(...i.transaction.signers);return r}async function ow(s,e,t){var E,A;let i=2e5,r=0;const n=wl.setComputeUnitLimit({units:3e5});let o;if(ac(e)){const _=(await Promise.all(e.message.addressTableLookups.map(P=>s.getAddressLookupTable(P.accountKey)))).map(P=>P.value).filter(P=>P!==null),S=aw.decompile(e.message,{addressLookupTableAccounts:_});S.instructions=[n,...S.instructions],o=new vc(S.compileToV0Message(_)),o.signatures=[...e.signatures]}else{const _=new Ic;_.recentBlockhash=e.recentBlockhash,_.feePayer=e.feePayer,_.instructions=[n,...e.instructions],_.signatures=[...e.signatures],o=_}e:for(;;){if(ac(o)&&!o.message.recentBlockhash){const{blockhash:S}=await s.getLatestBlockhash(t);o.message.recentBlockhash=S}const _=await(ac(o)?s.simulateTransaction(o,{commitment:t,replaceRecentBlockhash:!0}):s.simulateTransaction(o));if(_.value.err){if(U8(_.value)){if(r<5){r++,await dh(1e3);continue e}}else if(r<3){r++,await dh(1e3);continue e}throw new Error(`Simulation failed: ${JSON.stringify(_.value.err)}
|
|
898
|
+
`,oc={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};function Sa(s){return{formatters:void 0,fees:void 0,serializers:void 0,...s}}const du=Sa({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"}),pu=Sa({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"}),u8=Sa({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"});Sa({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});Sa({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 d8={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"]},$b={getMethodsByChainNamespace(s){return d8[s]||[]},createDefaultNamespace(s){return{methods:this.getMethodsByChainNamespace(s),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(s,e){if(!e)return{...s};const t={...s},i=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>i.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>i.add(r)),e.events&&Object.keys(e.events).forEach(r=>i.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[n]=r.split(":");n&&i.add(n)}),i.forEach(r=>{t[r]||(t[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,n])=>{t[r]&&(t[r].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([r,n])=>{t[r]&&(t[r].chains=n)}),e.events&&Object.entries(e.events).forEach(([r,n])=>{t[r]&&(t[r].events=n)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,c]=n.split(":");!a||!c||!t[a]||(t[a].rpcMap||(t[a].rpcMap={}),r.has(a)||(t[a].rpcMap={},r.add(a)),t[a].rpcMap[c]=o)})}return t},createNamespaces(s,e){const t=s.reduce((i,r)=>{const{id:n,chainNamespace:o,rpcUrls:a}=r,c=a.default.http[0];i[o]||(i[o]=this.createDefaultNamespace(o));const l=`${o}:${n}`,h=i[o];switch(h.chains.push(l),l){case du.caipNetworkId:h.chains.push(du.deprecatedCaipNetworkId);break;case pu.caipNetworkId:h.chains.push(pu.deprecatedCaipNetworkId);break}return h!=null&&h.rpcMap&&c&&(h.rpcMap[n]=c),i},{});return this.applyNamespaceOverrides(t,e)},resolveReownName:async s=>{var i;const e=await cm.resolveName(s);return((i=(Object.values(e==null?void 0:e.addresses)||[])[0])==null?void 0:i.address)||!1},getChainsFromNamespaces(s={}){return Object.values(s).flatMap(e=>{const t=e.chains||[],i=e.accounts.map(r=>{const[n,o]=r.split(":");return`${n}:${o}`});return Array.from(new Set([...t,...i]))})},isSessionEventData(s){return typeof s=="object"&&s!==null&&"id"in s&&"topic"in s&&"params"in s&&typeof s.params=="object"&&s.params!==null&&"chainId"in s.params&&"event"in s.params&&typeof s.params.event=="object"&&s.params.event!==null}};class Mb{constructor({provider:e,caipNetworks:t,namespace:i}){this.id=te.CONNECTOR_ID.WALLET_CONNECT,this.name=Rc.ConnectorNamesMap[te.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Rc.ConnectorImageIds[te.CONNECTOR_ID.WALLET_CONNECT],this.caipNetworks=t,this.provider=e,this.chain=i}get chains(){return this.caipNetworks}async connectWalletConnect(){if(!await this.authenticate()){const t=j.state.universalProviderConfigOverride,i=$b.createNamespaces(this.caipNetworks,t);await this.provider.connect({optionalNamespaces:i})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(t=>t.caipNetworkId);return Wo.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:p8})}}const p8=["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 g8{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,e&&this.construct(e)}construct(e){this.caipNetworks=e.networks,this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.caipNetworks||[]}setAuthProvider(e){this.addConnector({id:te.CONNECTOR_ID.AUTH,type:"AUTH",name:te.CONNECTOR_NAMES.AUTH,provider:e,imageId:Rc.ConnectorImageIds[te.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(i=>t.has(i.id)?!1:(t.add(i.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,t){se.setStatus(e,t)}on(e,t){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(t)}off(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,t){const i=this.eventListeners.get(e);i&&i.forEach(r=>r(t))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:t,providerType:i}=e;if(!e.provider)return;const r="provider"in e.provider?e.provider.provider:e.provider;if(i==="WALLET_CONNECT"){r.setDefaultChain(t.caipNetworkId);return}if(r&&i==="AUTH"){const n=r;await n.switchNetwork(t.caipNetworkId);const o=await n.getUser({chainId:t.caipNetworkId,preferredAccountType:j.state.defaultAccountTypes[t.chainNamespace]});this.emit("switchNetwork",o)}}getWalletConnectConnector(){const e=this.connectors.find(t=>t instanceof Mb);if(!e)throw new Error("WalletConnectConnector not found");return e}}class f8 extends g8{setUniversalProvider(e){this.addConnector(new Mb({provider:e,caipNetworks:this.caipNetworks||[],namespace:this.namespace}))}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){var r,n,o,a;const t=this.provider,i=((a=(o=(n=(r=t==null?void 0:t.session)==null?void 0:r.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const[,,l]=c.split(":");return l}).filter((c,l,h)=>h.indexOf(c)===l))||[];return Promise.resolve({accounts:i.map(c=>ce.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var n,o,a,c,l;if(!(e.caipNetwork&&ls.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(se.state.balanceLoading&&e.chainId===((c=v.state.activeCaipNetwork)==null?void 0:c.id))return{balance:se.state.balance||"0.00",symbol:se.state.balanceSymbol||""};const r=(await se.fetchTokenBalance()).find(h=>{var u,d;return h.chainId===`${(u=e.caipNetwork)==null?void 0:u.chainNamespace}:${e.chainId}`&&h.symbol===((d=e.caipNetwork)==null?void 0:d.nativeCurrency.symbol)});return{balance:(r==null?void 0:r.quantity.numeric)||"0.00",symbol:(r==null?void 0:r.symbol)||((l=e.caipNetwork)==null?void 0:l.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,c;const{provider:t,message:i,address:r}=e;if(!t)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return((o=v.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===te.CHAIN.SOLANA?n=(await t.request({method:"solana_signMessage",params:{message:Im.encode(new TextEncoder().encode(i)),pubkey:r}},(a=v.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:n=await t.request({method:"personal_sign",params:[i,r]},(c=v.state.activeCaipNetwork)==null?void 0:c.caipNetworkId),{signature:n}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async getProfile(){return Promise.resolve({profileImage:"",profileName:""})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}async getEnsAddress(){return Promise.resolve({address:!1})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){var r,n,o,a,c,l;const{caipNetwork:t}=e,i=this.getWalletConnectConnector();if(t.chainNamespace===te.CHAIN.EVM)try{await((r=i.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:wd(t.id)}]}))}catch(h){if(h.code===oc.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||h.code===oc.ERROR_INVALID_CHAIN_ID||h.code===oc.ERROR_CODE_DEFAULT||((o=(n=h==null?void 0:h.data)==null?void 0:n.originalError)==null?void 0:o.code)===oc.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=i.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:wd(t.id),rpcUrls:[(a=t==null?void 0:t.rpcUrls.chainDefault)==null?void 0:a.http],chainName:t.name,nativeCurrency:t.nativeCurrency,blockExplorerUrls:[(c=t.blockExplorers)==null?void 0:c.default.url]}]}))}catch{throw new Error("Chain is not supported")}}i.provider.setDefaultChain(t.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(i=>i.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}class w8{constructor(e){var t;this.hasSwitchedToPreferredAccountTypeOnConnect=!1,this.chainNamespaces=[],this.reportedAlertErrors={},this.getCaipNetwork=i=>{var r,n;if(i){const o=(r=v.getNetworkData(i))==null?void 0:r.caipNetwork;return o||((n=v.getRequestedCaipNetworks(i).filter(a=>a.chainNamespace===i))==null?void 0:n[0])}return v.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const i=this.getCaipNetwork();if(i)return i.id},this.getCaipNetworks=i=>v.getRequestedCaipNetworks(i),this.getActiveChainNamespace=()=>v.state.activeChain,this.setRequestedCaipNetworks=(i,r)=>{v.setRequestedCaipNetworks(i,r)},this.getApprovedCaipNetworkIds=()=>v.getAllApprovedCaipNetworkIds(),this.getCaipAddress=i=>v.state.activeChain===i||!i?v.state.activeCaipAddress:v.getAccountProp("caipAddress",i),this.setClientId=i=>{re.setClientId(i)},this.getProvider=i=>rt.getProvider(i),this.getProviderType=i=>rt.getProviderId(i),this.getPreferredAccountType=()=>se.state.preferredAccountType,this.setCaipAddress=(i,r)=>{se.setCaipAddress(i,r)},this.setBalance=(i,r,n)=>{se.setBalance(i,r,n)},this.setProfileName=(i,r)=>{se.setProfileName(i,r)},this.setProfileImage=(i,r)=>{se.setProfileImage(i,r)},this.setUser=(i,r)=>{se.setUser(i,r),j.state.enableEmbedded&&wt.close()},this.resetAccount=i=>{se.resetAccount(i)},this.setCaipNetwork=i=>{v.setActiveCaipNetwork(i)},this.setCaipNetworkOfNamespace=(i,r)=>{v.setChainNetworkData(r,{caipNetwork:i})},this.setAllAccounts=(i,r)=>{se.setAllAccounts(i,r),j.setHasMultipleAddresses((i==null?void 0:i.length)>1)},this.setStatus=(i,r)=>{se.setStatus(i,r),ae.isConnected()?J.setConnectionStatus("connected"):J.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=i=>v.getAccountProp("address",i),this.setConnectors=i=>{const r=[...ae.getConnectors(),...i];ae.setConnectors(r)},this.fetchIdentity=i=>re.fetchIdentity(i),this.getReownName=i=>cm.getNamesForAddress(i),this.getConnectors=()=>ae.getConnectors(),this.getConnectorImage=i=>nm.getConnectorImage(i),this.setConnectedWalletInfo=(i,r)=>{const n=rt.getProviderId(r),o=i?{...i,type:n}:void 0;se.setConnectedWalletInfo(o,r)},this.getIsConnectedState=()=>!!v.state.activeCaipAddress,this.addAddressLabel=(i,r,n)=>{se.addAddressLabel(i,r,n)},this.removeAddressLabel=(i,r)=>{se.removeAddressLabel(i,r)},this.getAddress=i=>v.state.activeChain===i||!i?se.state.address:v.getAccountProp("address",i),this.setApprovedCaipNetworksData=i=>v.setApprovedCaipNetworksData(i),this.resetNetwork=i=>{v.resetNetwork(i)},this.addConnector=i=>{ae.addConnector(i)},this.resetWcConnection=()=>{Ve.resetWcConnection()},this.setAddressExplorerUrl=(i,r)=>{se.setAddressExplorerUrl(i,r)},this.setSmartAccountDeployed=(i,r)=>{se.setSmartAccountDeployed(i,r)},this.setSmartAccountEnabledNetworks=(i,r)=>{v.setSmartAccountEnabledNetworks(i,r)},this.setPreferredAccountType=(i,r)=>{se.setPreferredAccountType(i,r)},this.setEIP6963Enabled=i=>{j.setEIP6963Enabled(i)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=[...new Set((t=this.caipNetworks)==null?void 0:t.map(i=>i.chainNamespace))],this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.initialize(e),this.sendInitializeEvent(e)}async initialize(e){this.initControllers(e),await this.initChainAdapters(),await this.injectModalUi(),await this.syncExistingConnection(),Oi.set({initialized:!0})}sendInitializeEvent(e){var i;const{...t}=e;delete t.adapters,Ke.sendEvent({type:"track",event:"INITIALIZE",properties:{...t,networks:e.networks.map(r=>r.id),siweConfig:{options:((i=e.siweConfig)==null?void 0:i.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&Jt.setThemeMode(e.themeMode),e.themeVariables&&Jt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");v.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&v.setActiveCaipNetwork(t)}initializeConnectionController(e){Ve.setWcBasic(e.basic??!1)}initializeConnectorController(){ae.initialize(this.chainNamespaces)}initializeOptionsController(e){var r;j.setDebug(e.debug!==!1),j.setEnableWalletConnect(e.enableWalletConnect!==!1),j.setEnableWalletGuide(e.enableWalletGuide!==!1),j.setEnableWallets(e.enableWallets!==!1),j.setEIP6963Enabled(e.enableEIP6963!==!1),j.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),j.setEnableAuthLogger(e.enableAuthLogger!==!1),j.setCustomRpcUrls(e.customRpcUrls),j.setSdkVersion(e.sdkVersion),j.setProjectId(e.projectId),j.setEnableEmbedded(e.enableEmbedded),j.setAllWallets(e.allWallets),j.setIncludeWalletIds(e.includeWalletIds),j.setExcludeWalletIds(e.excludeWalletIds),j.setFeaturedWalletIds(e.featuredWalletIds),j.setTokens(e.tokens),j.setTermsConditionsUrl(e.termsConditionsUrl),j.setPrivacyPolicyUrl(e.privacyPolicyUrl),j.setCustomWallets(e.customWallets),j.setFeatures(e.features),j.setAllowUnsupportedChain(e.allowUnsupportedChain),j.setDefaultAccountTypes(e.defaultAccountTypes),j.setUniversalProviderConfigOverride(e.universalProviderConfigOverride);const t=this.getDefaultMetaData();if(!e.metadata&&t&&(e.metadata=t),j.setMetadata(e.metadata),j.setDisableAppend(e.disableAppend),j.setEnableEmbedded(e.enableEmbedded),j.setSIWX(e.siwx),!e.projectId){dc.open(nc.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((r=e.adapters)==null?void 0:r.find(n=>n.namespace===te.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");j.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,t,i,r;return typeof window<"u"&&typeof document<"u"?{name:((t=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:t.textContent)||"",description:((i=document.querySelector('meta[property="og:description"]'))==null?void 0:i.content)||"",url:window.location.origin,icons:[((r=document.querySelector('link[rel~="icon"]'))==null?void 0:r.href)||""]}:null}setUnsupportedNetwork(e){const t=this.getActiveChainNamespace();if(t){const i=On.getUnsupportedNetwork(`${t}:${e}`);v.setActiveCaipNetwork(i)}}getDefaultNetwork(){return On.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return On.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return On.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const t=e.networks.find(r=>{var n;return r.id===((n=e.defaultNetwork)==null?void 0:n.id)});return t?On.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var n;const e=v.state.activeChain,t=this.getAdapter(e),i=(n=this.getCaipNetwork(e))==null?void 0:n.id;if(!t)throw new Error("Adapter not found");const r=await t.connectWalletConnect(i);this.close(),this.setClientId((r==null?void 0:r.clientId)||null),J.setConnectedNamespaces([...v.state.chains.keys()]),this.chainNamespaces.forEach(o=>{ae.setConnectorId(Hi.CONNECTOR_TYPE_WALLET_CONNECT,o)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:t,type:i,provider:r,chain:n,caipNetwork:o})=>{var g,p,f,b,m,w,E;const a=v.state.activeChain,c=n||a,l=this.getAdapter(c);if(n&&n!==a&&!o){const A=(g=this.caipNetworks)==null?void 0:g.find(_=>_.chainNamespace===n);A&&this.setCaipNetwork(A)}if(!l)throw new Error("Adapter not found");const h=this.getCaipNetwork(c),u=await l.connect({id:e,info:t,type:i,provider:r,chainId:(o==null?void 0:o.id)||(h==null?void 0:h.id),rpcUrl:((b=(f=(p=o==null?void 0:o.rpcUrls)==null?void 0:p.default)==null?void 0:f.http)==null?void 0:b[0])||((E=(w=(m=h==null?void 0:h.rpcUrls)==null?void 0:m.default)==null?void 0:w.http)==null?void 0:E[0])});if(!u)return;J.addConnectedNamespace(c),this.syncProvider({...u,chainNamespace:c}),await this.syncAccount({...u,chainNamespace:c});const{accounts:d}=await l.getAccounts({namespace:c,id:e});this.setAllAccounts(d,c)},reconnectExternal:async({id:e,info:t,type:i,provider:r})=>{var a;const n=v.state.activeChain,o=this.getAdapter(n);o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:t,type:i,provider:r,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),J.addConnectedNamespace(n))},disconnect:async e=>{const t=e||v.state.activeChain,i=this.getAdapter(t),r=rt.getProvider(t),n=rt.getProviderId(t);await(i==null?void 0:i.disconnect({provider:r,providerType:n})),J.removeConnectedNamespace(t),rt.resetChain(t),this.setUser(void 0,t),this.setStatus("disconnected",t),this.hasSwitchedToPreferredAccountTypeOnConnect=!1},checkInstalled:e=>e?e.some(t=>{var i;return!!((i=window.ethereum)!=null&&i[String(t)])}):!!window.ethereum,signMessage:async e=>{const t=this.getAdapter(v.state.activeChain),i=await(t==null?void 0:t.signMessage({message:e,address:se.state.address,provider:rt.getProvider(v.state.activeChain)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{if(e.chainNamespace===te.CHAIN.EVM){const t=this.getAdapter(v.state.activeChain),i=rt.getProvider(v.state.activeChain),r=await(t==null?void 0:t.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}));return(r==null?void 0:r.hash)||""}return""},estimateGas:async e=>{if(e.chainNamespace===te.CHAIN.EVM){const t=this.getAdapter(v.state.activeChain),i=rt.getProvider(v.state.activeChain),r=this.getCaipNetwork();if(!r)throw new Error("CaipNetwork is undefined");const n=await(t==null?void 0:t.estimateGas({...e,provider:i,caipNetwork:r}));return(n==null?void 0:n.gas)||0n}return 0n},getEnsAvatar:async()=>{var i;const e=this.getAdapter(v.state.activeChain),t=await(e==null?void 0:e.getProfile({address:se.state.address,chainId:Number((i=this.getCaipNetwork())==null?void 0:i.id)}));return(t==null?void 0:t.profileImage)||!1},getEnsAddress:async e=>{const t=this.getAdapter(v.state.activeChain),i=this.getCaipNetwork();if(!i)return!1;const r=await(t==null?void 0:t.getEnsAddress({name:e,caipNetwork:i}));return(r==null?void 0:r.address)||!1},writeContract:async e=>{const t=this.getAdapter(v.state.activeChain),i=this.getCaipNetwork(),r=this.getCaipAddress(),n=rt.getProvider(v.state.activeChain);if(!i||!r)throw new Error("CaipNetwork or CaipAddress is undefined");const o=await(t==null?void 0:t.writeContract({...e,caipNetwork:i,provider:n,caipAddress:r}));return o==null?void 0:o.hash},parseUnits:(e,t)=>{const i=this.getAdapter(v.state.activeChain);return(i==null?void 0:i.parseUnits({value:e,decimals:t}))??0n},formatUnits:(e,t)=>{const i=this.getAdapter(v.state.activeChain);return(i==null?void 0:i.formatUnits({value:e,decimals:t}))??"0"},getCapabilities:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.getCapabilities(e))},grantPermissions:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.grantPermissions(e))},revokePermissions:async e=>{const t=this.getAdapter(v.state.activeChain);return t!=null&&t.revokePermissions?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>{const t=this.getAdapter(v.state.activeChain);return await(t==null?void 0:t.walletGetAssets(e))??{}}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Ve.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){var t,i,r,n,o;if(rt.getProviderId(v.state.activeChain)===Hi.CONNECTOR_TYPE_WALLET_CONNECT){const a=(i=(t=this.universalProvider)==null?void 0:t.session)==null?void 0:i.namespaces;return{supportsAllNetworks:((o=(n=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:n.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const t=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=rt.getProvider(t),n=rt.getProviderId(t);if(e.chainNamespace===v.state.activeChain){const o=this.getAdapter(t);await(o==null?void 0:o.switchNetwork({caipNetwork:e,provider:r,providerType:n}))}else if(this.setCaipNetwork(e),n===Hi.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(t);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(t=>{const i=t.chains||[],r=t.accounts.map(n=>{const{chainId:o,chainNamespace:a}=zi.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...i,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((t,i)=>{var n;const r=e==null?void 0:e.find(o=>o.namespace===i);return r?(t[i]=r,t[i].namespace=i,t[i].construct({namespace:i,projectId:(n=this.options)==null?void 0:n.projectId,networks:this.caipNetworks})):t[i]=new f8({namespace:i,networks:this.caipNetworks}),t},{})}async initChainAdapter(e){var t;this.onConnectors(e),this.listenAdapter(e),(t=this.chainAdapters)==null||t[e].syncConnectors(this.options,this),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){const t=this.getAdapter(e);t==null||t.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const t=this.getAdapter(e);if(!t)return;const i=J.getConnectionStatus();i==="connected"?this.setStatus("connecting",e):i==="disconnected"?(J.clearAddressCache(),this.setStatus(i,e)):this.setStatus(i,e),t.on("switchNetwork",({address:r,chainId:n})=>{var l;const o=(l=this.caipNetworks)==null?void 0:l.find(h=>h.id===n||h.caipNetworkId===n),a=v.state.activeChain===e,c=v.getAccountProp("address",e);if(o){const h=a&&r?r:c;h&&this.syncAccount({address:h,chainId:n,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),t.on("disconnect",this.disconnect.bind(this,e)),t.on("pendingTransactions",()=>{const r=se.state.address,n=v.state.activeCaipNetwork;!r||!(n!=null&&n.id)||this.updateNativeBalance(r,n.id,n.chainNamespace)}),t.on("accountChanged",({address:r,chainId:n})=>{var a,c;const o=v.state.activeChain===e;o&&n?this.syncAccount({address:r,chainId:n,chainNamespace:e}):o&&((a=v.state.activeCaipNetwork)!=null&&a.id)?this.syncAccount({address:r,chainId:(c=v.state.activeCaipNetwork)==null?void 0:c.id,chainNamespace:e}):this.syncAccountInfo(r,n,e)})}async createUniversalProviderForAdapter(e){var t,i,r;await this.getUniversalProvider(),this.universalProvider&&((r=(i=(t=this.chainAdapters)==null?void 0:t[e])==null?void 0:i.setUniversalProvider)==null||r.call(i,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{const t=ae.getConnectorId(e);switch(this.setStatus("connecting",e),t){case te.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case te.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(t){console.warn("AppKit couldn't sync existing connection",t),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){var o,a,c;const t=this.getAdapter(e),i=ae.getConnectorId(e),r=this.getCaipNetwork(e),n=ae.getConnectors(e).find(l=>l.id===i);try{if(!t||!n)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(r!=null&&r.id))throw new Error("CaipNetwork not found");const l=await(t==null?void 0:t.syncConnection({namespace:e,id:n.id,chainId:r.id,rpcUrl:(c=(a=(o=r==null?void 0:r.rpcUrls)==null?void 0:o.default)==null?void 0:a.http)==null?void 0:c[0]}));if(l){const h=await(t==null?void 0:t.getAccounts({namespace:e,id:n.id}));h&&h.accounts.length>0?this.setAllAccounts(h.accounts,e):this.setAllAccounts([ce.createAccount(e,l.address,"eoa")],e),this.syncProvider({...l,chainNamespace:e}),await this.syncAccount({...l,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async t=>{var a,c,l,h,u;const i=this.getAdapter(t),r=((h=(l=(c=(a=this.universalProvider)==null?void 0:a.session)==null?void 0:c.namespaces)==null?void 0:l[t])==null?void 0:h.accounts)||[],n=(u=v.state.activeCaipNetwork)==null?void 0:u.id,o=r.find(d=>{const{chainId:g}=zi.parseCaipAddress(d);return g===(n==null?void 0:n.toString())})||r[0];if(o){const d=zi.validateCaipAddress(o),{chainId:g,address:p}=zi.parseCaipAddress(d);if(rt.setProviderId(t,Hi.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&v.state.activeCaipNetwork&&(i==null?void 0:i.namespace)!==te.CHAIN.EVM){const f=i==null?void 0:i.getWalletConnectProvider({caipNetworks:this.caipNetworks,provider:this.universalProvider,activeCaipNetwork:v.state.activeCaipNetwork});rt.setProvider(t,f)}else rt.setProvider(t,this.universalProvider);ae.setConnectorId(te.CONNECTOR_ID.WALLET_CONNECT,t),J.addConnectedNamespace(t),this.syncWalletConnectAccounts(t),await this.syncAccount({address:p,chainId:g,chainNamespace:t})}else this.setStatus("disconnected",t);await v.setApprovedCaipNetworksData(t)});await Promise.all(e)}syncWalletConnectAccounts(e){var i,r,n,o,a;const t=(a=(o=(n=(r=(i=this.universalProvider)==null?void 0:i.session)==null?void 0:r.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const{address:l}=zi.parseCaipAddress(c);return l}).filter((c,l,h)=>h.indexOf(c)===l);t&&this.setAllAccounts(t.map(c=>ce.createAccount(e,c,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:i,chainNamespace:r}){rt.setProviderId(r,e),rt.setProvider(r,t),ae.setConnectorId(i,r)}async syncAccount(e){var u,d,g,p,f,b;const t=e.chainNamespace===v.state.activeChain,i=v.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:n,chainNamespace:o}=e,{chainId:a}=J.getActiveNetworkProps(),c=n||a,l=((u=v.state.activeCaipNetwork)==null?void 0:u.name)===te.UNSUPPORTED_NETWORK_NAME,h=v.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!h)&&c){let m=(d=this.caipNetworks)==null?void 0:d.find(A=>A.id.toString()===c.toString()),w=(g=this.caipNetworks)==null?void 0:g.find(A=>A.chainNamespace===o);if(!h&&!m&&!w){const A=this.getApprovedCaipNetworkIds()||[],_=A.find(P=>{var x;return((x=zi.parseCaipNetworkId(P))==null?void 0:x.chainId)===c.toString()}),S=A.find(P=>{var x;return((x=zi.parseCaipNetworkId(P))==null?void 0:x.chainNamespace)===o});m=(p=this.caipNetworks)==null?void 0:p.find(P=>P.caipNetworkId===_),w=(f=this.caipNetworks)==null?void 0:f.find(P=>P.caipNetworkId===S||"deprecatedCaipNetworkId"in P&&P.deprecatedCaipNetworkId===S)}const E=m||w;(E==null?void 0:E.chainNamespace)===v.state.activeChain?j.state.enableNetworkSwitch&&!j.state.allowUnsupportedChain&&((b=v.state.activeCaipNetwork)==null?void 0:b.name)===te.UNSUPPORTED_NETWORK_NAME?v.showUnsupportedChainUI():this.setCaipNetwork(E):t||i&&this.setCaipNetworkOfNamespace(i,o),this.syncConnectedWalletInfo(o),Tb.isLowerCaseMatch(r,se.state.address)||this.syncAccountInfo(r,E==null?void 0:E.id,o),t?await this.syncBalance({address:r,chainId:E==null?void 0:E.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:i==null?void 0:i.id,chainNamespace:o})}}async syncAccountInfo(e,t,i){const r=this.getCaipAddress(i),n=t||(r==null?void 0:r.split(":")[1]);if(!n)return;const o=`${i}:${n}:${e}`;this.setCaipAddress(o,i),await this.syncIdentity({address:e,chainId:n,chainNamespace:i})}async syncReownName(e,t){try{const i=await this.getReownName(e);if(i[0]){const r=i[0];this.setProfileName(r.name,t)}else this.setProfileName(null,t)}catch{this.setProfileName(null,t)}}syncConnectedWalletInfo(e){var r;const t=ae.getConnectorId(e),i=rt.getProviderId(e);if(i===Hi.CONNECTOR_TYPE_ANNOUNCED||i===Hi.CONNECTOR_TYPE_INJECTED){if(t){const n=this.getConnectors().find(o=>o.id===t);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(i===Hi.CONNECTOR_TYPE_WALLET_CONNECT){const n=rt.getProvider(e);n!=null&&n.session&&this.setConnectedWalletInfo({...n.session.peer.metadata,name:n.session.peer.metadata.name,icon:(r=n.session.peer.metadata.icons)==null?void 0:r[0]},e)}else if(t)if(t===te.CONNECTOR_ID.COINBASE){const n=this.getConnectors().find(o=>o.id===te.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(n)},e)}else this.setConnectedWalletInfo({name:t},e)}async syncBalance(e){!rm.getNetworksByNamespace(this.caipNetworks,e.chainNamespace).find(i=>{var r;return i.id.toString()===((r=e.chainId)==null?void 0:r.toString())})||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async updateNativeBalance(e,t,i){const r=this.getAdapter(i);if(r){const n=await r.getBalance({address:e,chainId:t,caipNetwork:this.getCaipNetwork(i),tokens:this.options.tokens});this.setBalance(n.balance,n.symbol,i)}}async initializeUniversalAdapter(){var i,r,n,o,a,c,l,h,u,d;const e=o8.createLogger((g,...p)=>{g&&this.handleAlertError(g),console.error(...p)}),t={projectId:(i=this.options)==null?void 0:i.projectId,metadata:{name:(r=this.options)!=null&&r.metadata?(n=this.options)==null?void 0:n.metadata.name:"",description:(o=this.options)!=null&&o.metadata?(a=this.options)==null?void 0:a.metadata.description:"",url:(c=this.options)!=null&&c.metadata?(l=this.options)==null?void 0:l.metadata.url:"",icons:(h=this.options)!=null&&h.metadata?(u=this.options)==null?void 0:u.metadata.icons:[""]},logger:e};j.setManualWCControl(!!((d=this.options)!=null&&d.manualWCControl)),this.universalProvider=this.options.universalProvider??await Ku.init(t),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{Ve.setUri(e)}),this.universalProvider.on("connect",Ve.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),Ve.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{var r;const t=(r=this.caipNetworks)==null?void 0:r.find(n=>n.id==e),i=this.getCaipNetwork();if(!t){this.setUnsupportedNetwork(e);return}(i==null?void 0:i.id)!==(t==null?void 0:t.id)&&this.setCaipNetwork(t)}),this.universalProvider.on("session_event",e=>{if($b.isSessionEventData(e)){const{name:t,data:i}=e.params.event;t==="accountsChanged"&&Array.isArray(i)&&ce.isCaipAddress(i[0])&&this.syncAccount(zi.parseCaipAddress(i[0]))}}))}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&ce.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){Ke.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const t=Object.entries(nc.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[i,r]=t??[],{message:n,alertErrorKey:o}=r??{};if(i&&n&&!this.reportedAlertErrors[i]){const a=nc.ALERT_ERRORS[o];a&&(dc.open(a,"error"),this.reportedAlertErrors[i]=!0)}}getAdapter(e){var t;if(e)return(t=this.chainAdapters)==null?void 0:t[e]}createAdapter(e){var r;if(!e)return;const t=e.namespace;if(!t)return;this.createClients();const i=e;i.namespace=t,i.construct({namespace:t,projectId:(r=this.options)==null?void 0:r.projectId,networks:this.caipNetworks}),this.chainNamespaces.includes(t)||this.chainNamespaces.push(t),this.chainAdapters&&(this.chainAdapters[t]=i)}async open(e){await this.injectModalUi(),e!=null&&e.uri&&Ve.setUri(e.uri),await wt.open(e)}async close(){await this.injectModalUi(),wt.close()}setLoading(e,t){wt.setLoading(e,t)}async disconnect(e){await Ve.disconnect(e)}getError(){return""}getChainId(){var e;return(e=v.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e){var i;const t=(i=this.caipNetworks)==null?void 0:i.find(r=>r.id===e.id);if(!t){dc.open(nc.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await v.switchActiveNetwork(t)}getWalletProvider(){return v.state.activeChain?rt.state.providers[v.state.activeChain]:null}getWalletProviderType(){return rt.getProviderId(v.state.activeChain)}subscribeProviders(e){return rt.subscribeProviders(e)}getThemeMode(){return Jt.state.themeMode}getThemeVariables(){return Jt.state.themeVariables}setThemeMode(e){Jt.setThemeMode(e),Pb(Jt.state.themeMode)}setTermsConditionsUrl(e){j.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){j.setPrivacyPolicyUrl(e)}setThemeVariables(e){Jt.setThemeVariables(e),h8(Jt.state.themeVariables)}subscribeTheme(e){return Jt.subscribe(e)}getWalletInfo(){return se.state.connectedWalletInfo}getAccount(e){const t=ae.getAuthConnector(e),i=v.getAccountData(e);if(i)return{allAccounts:i.allAccounts,caipAddress:i.caipAddress,address:ce.getPlainAddress(i.caipAddress),isConnected:!!i.caipAddress,status:i.status,embeddedWalletInfo:t?{user:i.user,authProvider:i.socialProvider||"email",accountType:i.preferredAccountType,isSmartAccountDeployed:!!i.smartAccountDeployed}:void 0}}subscribeAccount(e,t){const i=()=>{const r=this.getAccount(t);r&&e(r)};t?v.subscribeChainProp("accountState",i,t):v.subscribe(i),ae.subscribe(i)}subscribeNetwork(e){return v.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t==null?void 0:t.id,caipNetworkId:t==null?void 0:t.caipNetworkId})})}subscribeWalletInfo(e){return se.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){se.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){v.subscribeKey("activeCaipNetwork",e)}getState(){return Oi.state}subscribeState(e){return Oi.subscribe(e)}showErrorMessage(e){Lt.showError(e)}showSuccessMessage(e){Lt.showSuccess(e)}getEvent(){return{...Ke.state}}subscribeEvents(e){return Ke.subscribe(e)}replace(e){De.replace(e)}redirect(e){De.push(e)}popTransactionStack(e){De.popTransactionStack(e)}isOpen(){return wt.state.open}isTransactionStackEmpty(){return De.state.transactionStack.length===0}isTransactionShouldReplaceView(){var e;return(e=De.state.transactionStack[De.state.transactionStack.length-1])==null?void 0:e.replace}static getInstance(){return this.instance}updateFeatures(e){j.setFeatures(e)}updateOptions(e){const i={...j.state||{},...e};j.setOptions(i)}setConnectMethodsOrder(e){j.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){j.setWalletFeaturesOrder(e)}setCollapseWallets(e){j.setCollapseWallets(e)}setSocialsOrder(e){j.setSocialsOrder(e)}getConnectMethodsOrder(){return uu.getConnectOrderMethod(j.state.features,ae.getConnectors())}removeAdapter(e){var n;const t=this.getIsConnectedState(),i=this.getAdapter(e);if(!i||!this.chainAdapters||t)return;const r=(n=this.caipNetworks)==null?void 0:n.filter(o=>o.chainNamespace!==e);v.removeAdapter(e),ae.removeAdapter(e),this.chainNamespaces=this.chainNamespaces.filter(o=>o!==e),this.caipNetworks=r,i.removeAllEventListeners(),Reflect.deleteProperty(this.chainAdapters,e)}addAdapter(e,t){const i=e.namespace;if(!this.connectionControllerClient||!this.networkControllerClient||!this.chainAdapters||!i)return;const r=this.extendCaipNetworks({...this.options,networks:t});this.caipNetworks=[...this.caipNetworks||[],...r],this.createAdapter(e),this.initChainAdapter(i),v.addAdapter(e,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient},r)}addNetwork(e,t){var r;if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const i=this.extendCaipNetwork(t,this.options);v.addNetwork(i),this.caipNetworks&&!((r=this.caipNetworks)!=null&&r.find(n=>n.id===i.id))&&this.caipNetworks.push(i)}removeNetwork(e,t){var n;if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);if(!((n=this.caipNetworks)==null?void 0:n.find(o=>o.id===t)))throw new Error(`Network with ID ${t} not found`);if(!this.caipNetworks)return;const r=this.caipNetworks.filter(o=>o.chainNamespace===e&&o.id!==t);if(!(r!=null&&r.length))throw new Error("Cannot remove last network for a namespace");v.removeNetwork(e,t),this.caipNetworks=[...r]}}let Jf=!1;class y8 extends w8{async open(e){ae.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&Ve.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!Jf&&ce.isClient()){if(await Zo(()=>import("./basic-PUjrTVXb.js"),__vite__mapDeps([13,10,11,14,15,1,2,16,5,6,7,8,9])),await Zo(()=>import("./w3m-modal-DD9Jgepz.js"),__vite__mapDeps([17,10,11,14,15,1,2,5,6,7,8,9])),!document.querySelector("w3m-modal")){const t=document.createElement("w3m-modal");!j.state.disableAppend&&!j.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",t)}Jf=!0}}}const m8="1.7.2";function b8(s){return new y8({...s,basic:!0,sdkVersion:`html-core-${m8}`})}function v8(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const h=s.charAt(l),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let h=0,u=0,d=0;const g=l.length;for(;d!==g&&l[d]===0;)d++,h++;const p=(g-d)*n+1>>>0,f=new Uint8Array(p);for(;d!==g;){let w=l[d],E=0;for(let A=p-1;(w!==0||E<u)&&A!==-1;A--,E++)w+=256*f[A]>>>0,f[A]=w%t>>>0,w=w/t>>>0;if(w!==0)throw new Error("Non-zero carry");u=E,d++}let b=p-u;for(;b!==p&&f[b]===0;)b++;let m=i.repeat(h);for(;b<p;++b)m+=s.charAt(f[b]);return m}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;l[h]===i;)u++,h++;const g=(l.length-h)*r+1>>>0,p=new Uint8Array(g);for(;h<l.length;){const w=l.charCodeAt(h);if(w>255)return;let E=e[w];if(E===255)return;let A=0;for(let _=g-1;(E!==0||A<d)&&_!==-1;_--,A++)E+=t*p[_]>>>0,p[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=A,h++}let f=g-d;for(;f!==g&&p[f]===0;)f++;const b=new Uint8Array(u+(g-f));let m=u;for(;f!==g;)b[m++]=p[f++];return b}function c(l){const h=a(l);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var I8="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const uh=v8(I8);class Rn extends Error{constructor(){super(),Object.setPrototypeOf(this,Rn.prototype)}}class Xf extends Error{constructor(e){super(`WalletConnect Adapter - Method ${e} is not supported by the wallet`),this.name="WalletConnectFeatureNotSupportedError"}}function E8(s){let e=[s];return s===vt.Mainnet||s===vt.Deprecated_Mainnet?(e=[vt.Mainnet,vt.Deprecated_Mainnet],s===vt.Deprecated_Mainnet&&console.warn(Lc.mainnet)):(s===vt.Deprecated_Devnet||s===vt.Devnet)&&(e=[vt.Devnet,vt.Deprecated_Devnet],console.warn(Lc.devnet)),e}const Lc={mainnet:`You are using a deprecated chain ID for Solana Mainnet, please use ${vt.Mainnet} instead.`,devnet:`You are using a deprecated chain ID for Solana Devnet, please use ${vt.Devnet} instead.`,wallet:"The connected wallet is using a deprecated chain ID for Solana. Please, contact them to upgrade. You can learn more at https://github.com/ChainAgnostic/namespaces/blob/main/solana/caip10.md#chain-ids"};function ew(s,e){var i;const t=(i=s.namespaces.solana)==null?void 0:i.accounts.map(r=>`solana:${r.split(":")[1]}`);if(e===vt.Mainnet)return t!=null&&t.find(r=>r===vt.Mainnet)?vt.Mainnet:(console.warn(Lc.wallet),vt.Deprecated_Mainnet);if(e===vt.Devnet)return t!=null&&t.find(r=>r===vt.Devnet)?vt.Devnet:(console.warn(Lc.wallet),vt.Deprecated_Devnet);throw Error("WalletConnect Solana Adapter: Unable to get a default chain from the session.")}function A8(s){return{optionalNamespaces:{solana:{chains:E8(s),methods:[xs.signTransaction,xs.signMessage],events:[]}}}}class Gu extends Error{constructor(){super("QR Code Modal was closed by user"),Object.setPrototypeOf(this,Gu.prototype),this.name="QRCodeModalError"}}class N8{constructor(e){$t(this,"_UniversalProvider");$t(this,"_session");$t(this,"_modal");$t(this,"_projectId");$t(this,"_network");$t(this,"_ConnectQueueResolver");if(this.initClient(e.options),this._network=e.network,!e.options.projectId)throw Error("WalletConnect Adapter: Project ID is undefined");this._projectId=e.options.projectId}async connect(){var r,n,o,a,c,l;if(this._UniversalProvider||await new Promise(h=>{this._ConnectQueueResolver=h}),!this._UniversalProvider)throw new Error("WalletConnect Adapter - Universal Provider was undefined while calling 'connect()'");if(this._UniversalProvider.session){this._session=this._UniversalProvider.session;const h=ew(this._session,this._network);return this._network=h,this._UniversalProvider.setDefaultChain(h),{publicKey:this.publicKey}}await this.initModal();const e=A8(this._network);(r=this._modal)==null||r.open();const t=new AbortController,i=t.signal;(n=this._modal)==null||n.subscribeState(h=>{h.open||t.abort(new Gu)});try{const h=await Promise.race([(o=this._UniversalProvider)==null?void 0:o.connect(e),new Promise((d,g)=>{i.addEventListener("abort",()=>{g(i.reason)})})]);if((a=this._modal)==null||a.close(),this._session=h,!h)throw new Hc;const u=ew(h,this._network);return this._network=u,(c=this._UniversalProvider)==null||c.setDefaultChain(u),{publicKey:this.publicKey}}catch(h){throw(l=this._modal)==null||l.close(),h}}async disconnect(){var e;if((e=this._UniversalProvider)!=null&&e.session){if(await this.initModal(),!this._modal)throw Error("WalletConnect Adapter -Modal is undefined: unable to disconnect");await this.client.disconnect(),this._session=void 0}else throw new Rn}get client(){if(this._UniversalProvider)return this._UniversalProvider;throw new Rn}get session(){if(!this._session)throw new Rn;return this._session}get publicKey(){var e,t,i;if((e=this._UniversalProvider)!=null&&e.session&&this._session){const{address:r}=TI(((i=(t=this._session)==null?void 0:t.namespaces.solana)==null?void 0:i.accounts[0])??"");return new di(r)}throw new Rn}async signTransaction(e){this.checkIfWalletSupportsMethod(xs.signTransaction);const t=$i(e),i=t?{}:e,{signature:r,transaction:n}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:xs.signTransaction,params:{...i,transaction:this.serialize(e)}}});return n?this.deserialize(n,t):(e.addSignature(this.publicKey,T.Buffer.from(uh.decode(r))),e)}async signMessage(e){this.checkIfWalletSupportsMethod(xs.signMessage);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:xs.signMessage,params:{pubkey:this.publicKey.toString(),message:uh.encode(e)}}});return uh.decode(t)}async signAndSendTransaction(e){this.checkIfWalletSupportsMethod(xs.signAndSendTransaction);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:xs.signAndSendTransaction,params:{transaction:this.serialize(e)}}});return t}async signAllTransactions(e){try{this.checkIfWalletSupportsMethod(xs.signAllTransactions);const t=e.map(r=>this.serialize(r)),{transactions:i}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:xs.signAllTransactions,params:{transactions:t}}});return e.map((r,n)=>$i(r)?this.deserialize(i[n]??"",!0):this.deserialize(i[n]??""))}catch(t){if(t instanceof Xf){const i=e.map(n=>this.signTransaction(n));return await Promise.all(i)}throw t}}async initClient(e){const t=await Gx.init(e);this._UniversalProvider=t,this._ConnectQueueResolver&&this._ConnectQueueResolver(!0)}async initModal(){if(!this._modal){if(!this._UniversalProvider)throw new Error("WalletConnect Adapter - cannot init modal when Universal Provider is undefined");this._modal=b8({projectId:this._projectId,universalProvider:this._UniversalProvider,networks:[du,pu,u8],manualWCControl:!0})}}serialize(e){return T.Buffer.from(e.serialize({verifySignatures:!1})).toString("base64")}deserialize(e,t=!1){return t?vc.deserialize(T.Buffer.from(e,"base64")):Ic.from(T.Buffer.from(e,"base64"))}checkIfWalletSupportsMethod(e){var t;if(!((t=this.session.namespaces.solana)!=null&&t.methods.includes(e)))throw new Xf(e)}}const _8="WalletConnect";class C8 extends mu{constructor(t){super();$t(this,"name",_8);$t(this,"url","https://walletconnect.org");$t(this,"icon","data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjE4NSIgdmlld0JveD0iMCAwIDMwMCAxODUiIHdpZHRoPSIzMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTYxLjQzODU0MjkgMzYuMjU2MjYxMmM0OC45MTEyMjQxLTQ3Ljg4ODE2NjMgMTI4LjIxMTk4NzEtNDcuODg4MTY2MyAxNzcuMTIzMjA5MSAwbDUuODg2NTQ1IDUuNzYzNDE3NGMyLjQ0NTU2MSAyLjM5NDQwODEgMi40NDU1NjEgNi4yNzY1MTEyIDAgOC42NzA5MjA0bC0yMC4xMzY2OTUgMTkuNzE1NTAzYy0xLjIyMjc4MSAxLjE5NzIwNTEtMy4yMDUzIDEuMTk3MjA1MS00LjQyODA4MSAwbC04LjEwMDU4NC03LjkzMTE0NzljLTM0LjEyMTY5Mi0zMy40MDc5ODE3LTg5LjQ0Mzg4Ni0zMy40MDc5ODE3LTEyMy41NjU1Nzg4IDBsLTguNjc1MDU2MiA4LjQ5MzYwNTFjLTEuMjIyNzgxNiAxLjE5NzIwNDEtMy4yMDUzMDEgMS4xOTcyMDQxLTQuNDI4MDgwNiAwbC0yMC4xMzY2OTQ5LTE5LjcxNTUwMzFjLTIuNDQ1NTYxMi0yLjM5NDQwOTItMi40NDU1NjEyLTYuMjc2NTEyMiAwLTguNjcwOTIwNHptMjE4Ljc2Nzc5NjEgNDAuNzczNzQ0OSAxNy45MjE2OTcgMTcuNTQ2ODk3YzIuNDQ1NTQ5IDIuMzk0Mzk2OSAyLjQ0NTU2MyA2LjI3NjQ3NjkuMDAwMDMxIDguNjcwODg5OWwtODAuODEwMTcxIDc5LjEyMTEzNGMtMi40NDU1NDQgMi4zOTQ0MjYtNi40MTA1ODIgMi4zOTQ0NTMtOC44NTYxNi4wMDAwNjItLjAwMDAxLS4wMDAwMS0uMDAwMDIyLS4wMDAwMjItLjAwMDAzMi0uMDAwMDMybC01Ny4zNTQxNDMtNTYuMTU0NTcyYy0uNjExMzktLjU5ODYwMi0xLjYwMjY1LS41OTg2MDItMi4yMTQwNCAwLS4wMDAwMDQuMDAwMDA0LS4wMDAwMDcuMDAwMDA4LS4wMDAwMTEuMDAwMDExbC01Ny4zNTI5MjEyIDU2LjE1NDUzMWMtMi40NDU1MzY4IDIuMzk0NDMyLTYuNDEwNTc1NSAyLjM5NDQ3Mi04Ljg1NjE2MTIuMDAwMDg3LS4wMDAwMTQzLS4wMDAwMTQtLjAwMDAyOTYtLjAwMDAyOC0uMDAwMDQ0OS0uMDAwMDQ0bC04MC44MTI0MTk0My03OS4xMjIxODVjLTIuNDQ1NTYwMjEtMi4zOTQ0MDgtMi40NDU1NjAyMS02LjI3NjUxMTUgMC04LjY3MDkxOTdsMTcuOTIxNzI5NjMtMTcuNTQ2ODY3M2MyLjQ0NTU2MDItMi4zOTQ0MDgyIDYuNDEwNTk4OS0yLjM5NDQwODIgOC44NTYxNjAyIDBsNTcuMzU0OTc3NSA1Ni4xNTUzNTdjLjYxMTM5MDguNTk4NjAyIDEuNjAyNjQ5LjU5ODYwMiAyLjIxNDAzOTggMCAuMDAwMDA5Mi0uMDAwMDA5LjAwMDAxNzQtLjAwMDAxNy4wMDAwMjY1LS4wMDAwMjRsNTcuMzUyMTAzMS01Ni4xNTUzMzNjMi40NDU1MDUtMi4zOTQ0NjMzIDYuNDEwNTQ0LTIuMzk0NTUzMSA4Ljg1NjE2MS0uMDAwMi4wMDAwMzQuMDAwMDMzNi4wMDAwNjguMDAwMDY3My4wMDAxMDEuMDAwMTAxbDU3LjM1NDkwMiA1Ni4xNTU0MzJjLjYxMTM5LjU5ODYwMSAxLjYwMjY1LjU5ODYwMSAyLjIxNDA0IDBsNTcuMzUzOTc1LTU2LjE1NDMyNDljMi40NDU1NjEtMi4zOTQ0MDkyIDYuNDEwNTk5LTIuMzk0NDA5MiA4Ljg1NjE2IDB6IiBmaWxsPSIjM2I5OWZjIi8+PC9zdmc+");$t(this,"supportedTransactionVersions",new Set(["legacy",0]));$t(this,"_publicKey");$t(this,"_connecting");$t(this,"_wallet");$t(this,"_config");$t(this,"_readyState");$t(this,"_onDisconnect");this._publicKey=null,this._connecting=!1,this._config=t,this._wallet=null,this._readyState=typeof window>"u"?de.Unsupported:de.Loadable,this._onDisconnect=this.disconnect.bind(this)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==de.Loadable)throw new or;this._connecting=!0,this._wallet=new N8({network:this._config.network===Xo.Mainnet?Nc.Mainnet:Nc.Devnet,options:this._config.options});const{publicKey:t}=await this._wallet.connect();this._publicKey=t,this.emit("connect",t),this._wallet.client.on("session_delete",this._onDisconnect)}catch(t){throw t.constructor.name==="QRCodeModalError"||t instanceof Error&&t.name==="QRCodeModalError"?new i0:(this._connecting=!1,t)}finally{this._connecting=!1}}async disconnect(){const t=this._wallet;if(t){t.client.off("session_delete",this._onDisconnect),this._publicKey=null;try{t.client.session&&await t.disconnect()}catch(i){console.error("WalletConnectWalletAdapter: disconnect error",i),this.emit("error",new ha(i==null?void 0:i.message,i))}}this.emit("disconnect")}async signTransaction(t){try{const i=this._wallet;if(!i)throw new Ge;try{return await i.signTransaction(t)}catch(r){throw new at(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signMessage(t){try{const i=this._wallet;if(!i)throw new Ge;try{return await i.signMessage(t)}catch(r){throw new ua(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signAndSendTransaction(t){try{const i=this._wallet;if(!i)throw new Ge;try{return await i.signAndSendTransaction(t)}catch(r){throw new at(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}async signAllTransactions(t){try{const i=this._wallet;if(!i)throw new Ge;try{return await i.signAllTransactions(t)}catch(r){throw new at(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}}const S8={icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgdmlld0JveD0iMCAwIDI1NiAyNTYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8yMDM1XzExMDYpIj4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IiM1NEZGRjUiLz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjBfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTEzLjQ4MDYgMTk4LjYwNUMtMjkuMzI3NiAzMTkuMDQzIDE5OS42NjEgMjg1LjAyNyAzMTkuNTA3IDI1Mi45NjRDNDQyLjE2NSAyMTIuMjU5IDM1Ny4zODYgMzIuODI2OSAyNjkuNDE1IDI4Ljg1NThDMTgxLjQ0MyAyNC44ODQ3IDI4MC4zMjIgMTExLjgyNCAyMDUuNTk1IDEzNi42NTZDMTMwLjg2OCAxNjEuNDg3IDY2Ljk5MDcgNDguMDU4MyAxMy40ODA2IDE5OC42MDVaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjxnIGZpbHRlcj0idXJsKCNmaWx0ZXIxX2ZfMjAzNV8xMTA2KSI+CjxwYXRoIGQ9Ik04NS41MTE4IC00NS44MjI1QzYzLjA1NjIgLTEwNy4xNzYgLTE2LjkxODkgLTIzLjk5NTMgLTU0LjA5OTUgMjUuMjY0M0MtODkuNTY1MiA3OC44NDc5IDMuMDA5MzcgMTI1LjE1MiAzOS4zMjA4IDEwMC4wMzdDNzUuNjMyMyA3NC45MjI3IDcuNzc0NDggNzAuMDM2MyAyOS4zNzA4IDM3LjM3ODVDNTAuOTY3MSA0LjcyMDc2IDExMy41ODEgMzAuODY5NSA4NS41MTE4IC00NS44MjI1WiIgZmlsbD0iIzAwRkZGMCIgZmlsbC1vcGFjaXR5PSIwLjY3Ii8+CjwvZz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjJfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTk2LjQ3OTYgMjI1LjQyNEM2NS44NTAyIDEyMi4zNjMgLTY2LjA4MTggMTc2LjYzNyAtMTI4LjIxOSAyMTYuNjU3Qy0xODcuOTkgMjY0LjA0MiAtNDYuMDcxMSA0MDAuMzQ4IDEyLjg3MjUgMzkzLjM3NkM3MS44MTYxIDM4Ni40MDMgLTM0LjQxMTggMzI3LjA2NSAxLjk4NzAyIDI5OC4xN0MzOC4zODU4IDI2OS4yNzYgMTM0Ljc2NiAzNTQuMjQ5IDk2LjQ3OTYgMjI1LjQyNFoiIGZpbGw9IiM5RDgxRkYiLz4KPC9nPgo8ZyBmaWx0ZXI9InVybCgjZmlsdGVyM19mXzIwMzVfMTEwNikiPgo8cGF0aCBkPSJNMjgyLjEyIC0xMDcuMzUzQzIxNi4wNDcgLTE4Ni4wMzEgMTIxLjQ2MyAtMTIwLjk3IDgyLjQyOTYgLTc4LjYwNDdDNDguMjczOSAtMzAuNjQ0NiAyMjQuMjc1IDU3LjIzMTIgMjczLjEyMSA0Mi4xNzE0QzMyMS45NjggMjcuMTExNSAyMDYuNTEyIC00LjA1MDM4IDIyNy4yOTcgLTMzLjI4NzlDMjQ4LjA4MiAtNjIuNTI1NSAzNjQuNzEyIC05LjAwNTY2IDI4Mi4xMiAtMTA3LjM1M1oiIGZpbGw9IiM0RDk0RkYiLz4KPC9nPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkzLjE4OSAxNTIuODM2SDEzNi42NzRMODcuMjA4NiAxMDMuMDUxTDEzNy4zMSA1My4yNjYzTDE1MC45NTUgNDBIMTA1LjgxOUw0OC4zMzU5IDk3Ljc3NzNDNDUuNDM0OSAxMDAuNjg5IDQ1LjQ0OTggMTA1LjQwMiA0OC4zNjU2IDEwOC4yOTlMOTMuMTg5IDE1Mi44MzZaTTExOS4zMyAxMDMuMTY4SDExOC45OTVMMTE5LjMyNiAxMDMuMTY0TDExOS4zMyAxMDMuMTY4Wk0xMTkuMzMgMTAzLjE2OEwxNjguNzkxIDE1Mi45NDlMMTE4LjY5IDIwMi43MzRMMTA1LjA0NSAyMTZIMTUwLjE4TDIwNy42NjQgMTU4LjIyNkMyMTAuNTY1IDE1NS4zMTQgMjEwLjU1IDE1MC42MDIgMjA3LjYzNCAxNDcuNzA1TDE2Mi44MTEgMTAzLjE2OEgxMTkuMzNaIiBmaWxsPSJibGFjayIvPgo8L2c+CjxkZWZzPgo8ZmlsdGVyIGlkPSJmaWx0ZXIwX2ZfMjAzNV8xMTA2IiB4PSItOTAuMjQxMSIgeT0iLTY5LjczNjkiIHdpZHRoPSI1NjkuNTU4IiBoZWlnaHQ9IjQ1MS40MzEiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyMV9mXzIwMzVfMTEwNiIgeD0iLTE2MC41MTEiIHk9Ii0xNjUuOTg3IiB3aWR0aD0iMzUxLjU5NiIgaGVpZ2h0PSIzNzEuNTA3IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxmaWx0ZXIgaWQ9ImZpbHRlcjJfZl8yMDM1XzExMDYiIHg9Ii0yNDEuMDc4IiB5PSI2Ny42NDIiIHdpZHRoPSI0NDQuODUxIiBoZWlnaHQ9IjQyNC40NTIiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyM19mXzIwMzVfMTEwNiIgeD0iLTIwLjM5NjgiIHk9Ii0yNDIuNzU4IiB3aWR0aD0iNDMwLjE5MSIgaGVpZ2h0PSIzODUuMTA1IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxjbGlwUGF0aCBpZD0iY2xpcDBfMjAzNV8xMTA2Ij4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==",name:"Bitget Wallet"},T8=[S8],P8=s=>T8.find(e=>e.name.toLocaleLowerCase().includes(s.name.toLocaleLowerCase()))||s,$8=(s,e,t)=>e[s]||t[s],tw=(s,e)=>$8(s,P8(e),e);class Si extends Vv{constructor(e,t){super(),this.adapter=e,this.connection=t}getAdapter(){return this.adapter}getName(){return tw("name",this.adapter)}getUrl(){return this.adapter.url}async connect(){if(this.isConnected())return this.getAddresses();const e=await new Promise((t,i)=>{this.adapter.on("connect",()=>{this.adapter.off("connect"),this.adapter.off("error"),t(this.getAddresses())}),this.adapter.on("error",r=>{this.adapter.off("connect"),this.adapter.off("error"),i(r)}),this.adapter.connect().catch(i)});return this.emit("connect"),this.adapter.on("disconnect",()=>this.emit("disconnect")),e}getNetworkInfo(){return{}}isConnected(){return this.adapter.connected}async disconnect(){this.isConnected()&&(await new Promise((e,t)=>{this.adapter.on("disconnect",()=>{this.adapter.off("disconnect"),this.adapter.off("error"),e(void 0)}),this.adapter.on("error",i=>{this.adapter.off("disconnect"),this.adapter.off("error"),t(i)}),this.adapter.disconnect().catch(t)}),this.adapter.removeAllListeners(),this.emit("disconnect"))}getChainId(){return pd}getAddress(){var e;return(e=this.adapter.publicKey)==null?void 0:e.toString()}getAddresses(){const e=this.getAddress();return e?[e]:[]}setMainAddress(){throw new Error("Not supported")}getBalance(){throw new Error("Not supported")}async signTransaction(e){if(!this.adapter.signTransaction||!this.adapter.signAllTransactions)throw new Error("Not supported");return Array.isArray(e)?this.adapter.signAllTransactions(e):this.adapter.signTransaction(e)}async sendTransaction(e){var n;const{transaction:t}=e,i=Array.isArray(t)?t:[t];if(i.length===0)throw new Error("Empty transactions array");const r=[];for(const o of i){const a=await this.adapter.sendTransaction(o,this.connection,{...e.options});r.push(a)}return await this.connection.confirmTransaction(r[0],(n=e.options)==null?void 0:n.commitment),{id:r[0],data:r.length===1?r[0]:r}}async signAndSendTransaction(e){return this.sendTransaction(e)}signMessage(e){if(!this.adapter.signMessage)throw new Error("Not supported");return this.adapter.signMessage(e)}getIcon(){return tw("icon",this.adapter)}getWalletState(){const e=this.adapter.readyState;if(!(e in gd))throw new Error(`Unknown wallet state ${e}`);return gd[e]}getFeatures(){const e=[Ra.SendTransaction,Ra.SignAndSendTransaction];return this.adapter.signTransaction&&this.adapter.signAllTransactions&&e.push(Ra.SignTransaction),this.adapter.signMessage&&e.push(Ra.SignMessage),e}supportsChain(e){return e===pd}}function M8(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const h=s.charAt(l),u=h.charCodeAt(0);if(e[u]!==255)throw new TypeError(h+" is ambiguous");e[u]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let h=0,u=0,d=0;const g=l.length;for(;d!==g&&l[d]===0;)d++,h++;const p=(g-d)*n+1>>>0,f=new Uint8Array(p);for(;d!==g;){let w=l[d],E=0;for(let A=p-1;(w!==0||E<u)&&A!==-1;A--,E++)w+=256*f[A]>>>0,f[A]=w%t>>>0,w=w/t>>>0;if(w!==0)throw new Error("Non-zero carry");u=E,d++}let b=p-u;for(;b!==p&&f[b]===0;)b++;let m=i.repeat(h);for(;b<p;++b)m+=s.charAt(f[b]);return m}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,u=0,d=0;for(;l[h]===i;)u++,h++;const g=(l.length-h)*r+1>>>0,p=new Uint8Array(g);for(;h<l.length;){const w=l.charCodeAt(h);if(w>255)return;let E=e[w];if(E===255)return;let A=0;for(let _=g-1;(E!==0||A<d)&&_!==-1;_--,A++)E+=t*p[_]>>>0,p[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=A,h++}let f=g-d;for(;f!==g&&p[f]===0;)f++;const b=new Uint8Array(u+(g-f));let m=u;for(;f!==g;)b[m++]=p[f++];return b}function c(l){const h=a(l);if(h)return h;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var O8="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const x8=M8(O8);var Z=function(s,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!i:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(s):i?i.value:e.get(s)},pt=function(s,e,t,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(s,t):r?r.value=t:e.set(s,t),t},Ut,as,Tr,Pr,Ir,qo,zc,Ne,Fc,gu,bc,fu,Qo,wu,sw,iw,rw,nw;class D8 extends bw{get name(){return Z(this,Ne,"f").name}get url(){return"https://github.com/solana-labs/wallet-standard"}get icon(){return Z(this,Ne,"f").icon}get readyState(){return Z(this,Fc,"f")}get publicKey(){return Z(this,Tr,"f")}get connecting(){return Z(this,Pr,"f")}get supportedTransactionVersions(){return Z(this,zc,"f")}get wallet(){return Z(this,Ne,"f")}get standard(){return!0}constructor({wallet:e}){super(),Ut.add(this),as.set(this,void 0),Tr.set(this,void 0),Pr.set(this,void 0),Ir.set(this,void 0),qo.set(this,void 0),zc.set(this,void 0),Ne.set(this,void 0),Fc.set(this,typeof window>"u"||typeof document>"u"?de.Unsupported:de.Installed),wu.set(this,t=>{if("accounts"in t){const i=Z(this,Ne,"f").accounts[0];Z(this,as,"f")&&!Z(this,Ir,"f")&&i!==Z(this,as,"f")&&(i?Z(this,Ut,"m",bc).call(this,i):(this.emit("error",new mw),Z(this,Ut,"m",fu).call(this)))}"features"in t&&Z(this,Ut,"m",Qo).call(this)}),pt(this,Ne,e,"f"),pt(this,as,null,"f"),pt(this,Tr,null,"f"),pt(this,Pr,!1,"f"),pt(this,Ir,!1,"f"),pt(this,qo,Z(this,Ne,"f").features[Iw].on("change",Z(this,wu,"f")),"f"),Z(this,Ut,"m",Qo).call(this)}destroy(){pt(this,as,null,"f"),pt(this,Tr,null,"f"),pt(this,Pr,!1,"f"),pt(this,Ir,!1,"f");const e=Z(this,qo,"f");e&&(pt(this,qo,null,"f"),e())}async autoConnect(){return Z(this,Ut,"m",gu).call(this,{silent:!0})}async connect(){return Z(this,Ut,"m",gu).call(this)}async disconnect(){if(md in Z(this,Ne,"f").features)try{pt(this,Ir,!0,"f"),await Z(this,Ne,"f").features[md].disconnect()}catch(e){this.emit("error",new ha(e==null?void 0:e.message,e))}finally{pt(this,Ir,!1,"f")}Z(this,Ut,"m",fu).call(this)}async sendTransaction(e,t,i={}){try{const r=Z(this,as,"f");if(!r)throw new Ge;let n;if(Gi in Z(this,Ne,"f").features)if(r.features.includes(Gi))n=Gi;else if(Rt in Z(this,Ne,"f").features&&r.features.includes(Rt))n=Rt;else throw new ks;else if(Rt in Z(this,Ne,"f").features){if(!r.features.includes(Rt))throw new ks;n=Rt}else throw new xn;const o=E0(t.rpcEndpoint);if(!r.chains.includes(o))throw new _r;try{const{signers:a,...c}=i;let l;if($i(e)?(a!=null&&a.length&&e.sign(a),l=e.serialize()):(e=await this.prepareTransaction(e,t,c),a!=null&&a.length&&e.partialSign(...a),l=new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))),n===Gi){const[h]=await Z(this,Ne,"f").features[Gi].signAndSendTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:vl(c.preflightCommitment||t.commitment),skipPreflight:c.skipPreflight,maxRetries:c.maxRetries,minContextSlot:c.minContextSlot}});return x8.encode(h.signature)}else{const[h]=await Z(this,Ne,"f").features[Rt].signTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:vl(c.preflightCommitment||t.commitment),minContextSlot:c.minContextSlot}});return await t.sendRawTransaction(h.signedTransaction,{...c,preflightCommitment:vl(c.preflightCommitment||t.commitment)})}}catch(a){throw a instanceof Ft?a:new _r(a==null?void 0:a.message,a)}}catch(r){throw this.emit("error",r),r}}}as=new WeakMap,Tr=new WeakMap,Pr=new WeakMap,Ir=new WeakMap,qo=new WeakMap,zc=new WeakMap,Ne=new WeakMap,Fc=new WeakMap,wu=new WeakMap,Ut=new WeakSet,gu=async function(e){try{if(this.connected||this.connecting)return;if(Z(this,Fc,"f")!==de.Installed)throw new or;if(pt(this,Pr,!0,"f"),!Z(this,Ne,"f").accounts.length)try{await Z(this,Ne,"f").features[vw].connect(e)}catch(i){throw new Hc(i==null?void 0:i.message,i)}const t=Z(this,Ne,"f").accounts[0];if(!t)throw new ks;Z(this,Ut,"m",bc).call(this,t)}catch(t){throw this.emit("error",t),t}finally{pt(this,Pr,!1,"f")}},bc=function(e){let t;try{t=new di(e.address)}catch(i){throw new Ur(i==null?void 0:i.message,i)}pt(this,as,e,"f"),pt(this,Tr,t,"f"),Z(this,Ut,"m",Qo).call(this),this.emit("connect",t)},fu=function(){pt(this,as,null,"f"),pt(this,Tr,null,"f"),Z(this,Ut,"m",Qo).call(this),this.emit("disconnect")},Qo=function(){var t,i;const e=Gi in Z(this,Ne,"f").features?Z(this,Ne,"f").features[Gi].supportedTransactionVersions:Z(this,Ne,"f").features[Rt].supportedTransactionVersions;pt(this,zc,Qv(e,["legacy"])?null:new Set(e),"f"),Rt in Z(this,Ne,"f").features&&((t=Z(this,as,"f"))!=null&&t.features.includes(Rt))?(this.signTransaction=Z(this,Ut,"m",sw),this.signAllTransactions=Z(this,Ut,"m",iw)):(delete this.signTransaction,delete this.signAllTransactions),go in Z(this,Ne,"f").features&&((i=Z(this,as,"f"))!=null&&i.features.includes(go))?this.signMessage=Z(this,Ut,"m",rw):delete this.signMessage,ml in Z(this,Ne,"f").features?this.signIn=Z(this,Ut,"m",nw):delete this.signIn},sw=async function(e){try{const t=Z(this,as,"f");if(!t)throw new Ge;if(!(Rt in Z(this,Ne,"f").features))throw new xn;if(!t.features.includes(Rt))throw new ks;try{const r=(await Z(this,Ne,"f").features[Rt].signTransaction({account:t,transaction:$i(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return $i(e)?vc.deserialize(r):Ic.from(r)}catch(i){throw i instanceof Ft?i:new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},iw=async function(e){try{const t=Z(this,as,"f");if(!t)throw new Ge;if(!(Rt in Z(this,Ne,"f").features))throw new xn;if(!t.features.includes(Rt))throw new ks;try{const i=await Z(this,Ne,"f").features[Rt].signTransaction(...e.map(r=>({account:t,transaction:$i(r)?r.serialize():new Uint8Array(r.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((r,n)=>{const o=i[n].signedTransaction;return $i(r)?vc.deserialize(o):Ic.from(o)})}catch(i){throw new at(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},rw=async function(e){try{const t=Z(this,as,"f");if(!t)throw new Ge;if(!(go in Z(this,Ne,"f").features))throw new xn;if(!t.features.includes(go))throw new ks;try{return(await Z(this,Ne,"f").features[go].signMessage({account:t,message:e}))[0].signature}catch(i){throw new ua(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},nw=async function(e={}){try{if(!(ml in Z(this,Ne,"f").features))throw new xn;let t;try{[t]=await Z(this,Ne,"f").features[ml].signIn(e)}catch(i){throw new yd(i==null?void 0:i.message,i)}if(!t)throw new yd;return Z(this,Ut,"m",bc).call(this,t.account),t}catch(t){throw this.emit("error",t),t}};function k8(s){return Zv().get().filter(r0).map(e=>new Si(new D8({wallet:e}),s))}function j8(s){return s.includes("rpcpool.com")?"triton":s.includes("helius-rpc.com")?"helius":s.includes("rpc.ankr.com")?"ankr":"unknown"}async function R8(s,e,t,i){const r=i.transaction.transaction,n=o=>o.programId.toString()!=="ComputeBudget111111111111111111111111111111";if(ac(r)){const o=(await Promise.all(r.message.addressTableLookups.map(c=>s.getAddressLookupTable(c.accountKey)))).map(c=>c.value).filter(c=>c!==null),a=aw.decompile(r.message,{addressLookupTableAccounts:o});a.recentBlockhash=e,r.message.recentBlockhash=e,a.instructions=a.instructions.filter(n),r.message=a.compileToV0Message(o),a.instructions.push(...await ow(s,r)),r.message=a.compileToV0Message(o),r.sign(i.transaction.signers??[])}else r.recentBlockhash=e,r.lastValidBlockHeight=t,r.instructions=r.instructions.filter(n),r.add(...await ow(s,r)),i.transaction.signers&&r.partialSign(...i.transaction.signers);return r}async function ow(s,e,t){var E,A;let i=2e5,r=0;const n=wl.setComputeUnitLimit({units:3e5});let o;if(ac(e)){const _=(await Promise.all(e.message.addressTableLookups.map(P=>s.getAddressLookupTable(P.accountKey)))).map(P=>P.value).filter(P=>P!==null),S=aw.decompile(e.message,{addressLookupTableAccounts:_});S.instructions=[...S.instructions,n],o=new vc(S.compileToV0Message(_)),o.signatures=[...e.signatures]}else{const _=new Ic;_.recentBlockhash=e.recentBlockhash,_.feePayer=e.feePayer,_.instructions=[...e.instructions,n],_.signatures=[...e.signatures],o=_}e:for(;;){if(ac(o)&&!o.message.recentBlockhash){const{blockhash:S}=await s.getLatestBlockhash(t);o.message.recentBlockhash=S}const _=await(ac(o)?s.simulateTransaction(o,{commitment:t,replaceRecentBlockhash:!0}):s.simulateTransaction(o));if(_.value.err){if(U8(_.value)){if(r<5){r++,await dh(1e3);continue e}}else if(r<3){r++,await dh(1e3);continue e}throw new Error(`Simulation failed: ${JSON.stringify(_.value.err)}
|
|
899
899
|
Logs:
|
|
900
900
|
${(_.value.logs||[]).join(`
|
|
901
901
|
`)}`)}else{_.value.unitsConsumed&&(i=_.value.unitsConsumed);break}}const a=Math.floor(i*1.2),c=[];c.push(wl.setComputeUnitLimit({units:a}));const l=((A=(E=Ti.transactionSettings)==null?void 0:E.Solana)==null?void 0:A.priorityFee)||{},{percentile:h=.9,percentileMultiple:u=1,min:d=1e5,max:g=1e8}=l,p=async _=>{if(_==="triton")try{return{fee:await Jv(s,e,h,u,d,g),methodUsed:"triton"}}catch(S){console.warn("Failed to determine priority fee using Triton RPC:",S)}try{return{fee:await Xv(s,e,h,u,d,g),methodUsed:"default"}}catch(S){return console.warn("Failed to determine priority fee using Triton RPC:",S),{fee:d,methodUsed:"minimum"}}},f=j8(s.rpcEndpoint),{fee:b,methodUsed:m}=await p(f),w=b/1e6/Gv*a;return console.table({"RPC Provider":f,"Method used":m,"Percentile used":h,"Multiple used":u,"Compute budget":a,"Priority fee":b,"Max fee in SOL":w}),c.push(wl.setComputeUnitPrice({microLamports:b})),c}function U8(s){const e={};if(s.err==="BlockhashNotFound"&&(e.BlockhashNotFound="Blockhash not found during simulation. Trying again."),s.logs)for(const t of s.logs)t.includes("SlippageToleranceExceeded")&&(e.SlippageToleranceExceeded="Slippage failure during simulation. Trying again."),t.includes("RequireGteViolated")&&(e.RequireGteViolated="Swap instruction failure during simulation. Trying again.");return Kv(e)?!1:(console.table(e),!0)}const L8=s=>s.getName().toLowerCase().replaceAll("wallet","").trim();function z8(s){if(s==="Solana"){const e=Ti.isMainnet?"mainnet-beta":"devnet",t=new ph(Ti.rpcs.Solana||Yv(e));return{...k8(t).reduce((i,r)=>(i[L8(r)]=r,i),{}),bitget:new Si(new o0,t),clover:new Si(new c0,t),coin98:new Si(new d0,t),solong:new Si(new m0,t),torus:new Si(new v0,t),nightly:new Si(new bd,t),...Ti.ui.walletConnectProjectId?{walletConnect:new Si(new C8({network:Ti.isMainnet?Xo.Mainnet:Xo.Devnet,options:{projectId:Ti.ui.walletConnectProjectId,customStoragePrefix:"wh-connect-solana-adapter"}}),t)}:{}}}else if(s==="Fogo"){if(!Ti.rpcs.Fogo)throw new Error("Fogo RPC not found");const e=new ph(Ti.rpcs.Fogo);return{nightly:new Si(new bd,e)}}throw new Error(`Unsupported chain: ${s}`)}async function F8(s,e,t){if(!e)throw new Error("Wallet not found");const i=Ti.rpcs[s.chain];if(!i)throw new Error(`${s.chain} RPC not found`);const r=(t==null?void 0:t.commitment)??"finalized",n=new ph(i),{blockhash:o,lastValidBlockHeight:a}=await n.getLatestBlockhash(r),c=await R8(n,o,a,s);let l=null,h=null,u=1,d="";const p=(await e.signTransaction(c)).serialize(),f={skipPreflight:!0,maxRetries:0,preFlightCommitment:r};d=await n.sendRawTransaction(p,f),l=n.confirmTransaction({signature:d,blockhash:o,lastValidBlockHeight:a},r);try{for(;!h&&(h=await Promise.race([l,new Promise(m=>setTimeout(()=>{m(null)},5e3))]),!h);){console.log(`Tx not confirmed after ${5e3*u++}ms, resending`);try{await n.sendRawTransaction(p,f)}catch(m){console.error("Failed to resend transaction:",m)}}}catch(b){if(b instanceof Error&&b.name==="TransactionExpiredBlockheightExceededError")for(let E=0;E<5;++E){try{if(await n.getTransaction(d,{commitment:"confirmed",maxSupportedTransactionVersion:0}))return d}catch{}await dh(2e3)}throw b}if(h.value.err){let b=`Transaction failed: ${h.value.err}`;if(typeof h.value.err=="object")try{b=`Transaction failed: ${JSON.stringify(h.value.err,(m,w)=>typeof w=="bigint"?w.toString():w)}`}catch{b="Transaction failed: Unknown error"}throw new Error(`Transaction failed: ${b}`)}return d}const NF=Object.freeze(Object.defineProperty({__proto__:null,fetchOptions:z8,signAndSendTransaction:F8},Symbol.toStringTag,{value:"Module"}));export{le as A,p6 as B,ae as C,sk as D,Ke as E,uF as F,Ig as G,lI as H,wm as I,VD as J,ik as K,dF as L,wt as M,hF as N,j as O,rl as P,gF as Q,De as R,J as S,Jt as T,pF as U,NF as V,uu as W,ce as a,mc as b,nm as c,Ve as d,EF as e,te as f,Qs as g,Lt as h,ls as i,v as j,AF as k,dc as l,l8 as m,Wo as n,se as o,vF as p,u6 as q,IF as r,Nd as s,Pw as t,X0 as u,d6 as v,hI as w,h6 as x,Vc as y,f6 as z};
|