@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
|
@@ -0,0 +1,900 @@
|
|
|
1
|
+
"use strict";var Bb=Object.defineProperty;var Hb=(s,e,t)=>e in s?Bb(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Nt=(s,e,t)=>Hb(s,typeof e!="symbol"?e+"":e,t);const N=require("./web3-COTIsLs8.js"),tt=require("./index-BoquY9R2.js"),Wb=require("./util-G2vxTeU2.js"),Vb=require("./wallets-5qGJd8Hk.js"),Oa=require("./unsignedTransaction-C6Qp42VS.js"),Tu=require("./signer-H7atraks.js"),u=require("./index.es-D6S74vhi.js"),k=require("./lit-element-Df-39D6h.js");require("./browser-ponyfill-Dn6gsMYK.js");const wn=require("./http-D_Zdp_wT.js");class Dt extends Error{constructor(e,t){super(e),this.error=t}}class Li extends Dt{constructor(){super(...arguments),this.name="WalletNotReadyError"}}class Kb extends Dt{constructor(){super(...arguments),this.name="WalletLoadError"}}class un extends Dt{constructor(){super(...arguments),this.name="WalletConfigError"}}class cc extends Dt{constructor(){super(...arguments),this.name="WalletConnectionError"}}class wf extends Dt{constructor(){super(...arguments),this.name="WalletDisconnectedError"}}class ko extends Dt{constructor(){super(...arguments),this.name="WalletDisconnectionError"}}class As extends Dt{constructor(){super(...arguments),this.name="WalletAccountError"}}class wr extends Dt{constructor(){super(...arguments),this.name="WalletPublicKeyError"}}class Ke extends Dt{constructor(){super(...arguments),this.name="WalletNotConnectedError"}}class rr extends Dt{constructor(){super(...arguments),this.name="WalletSendTransactionError"}}class rt extends Dt{constructor(){super(...arguments),this.name="WalletSignTransactionError"}}class jo extends Dt{constructor(){super(...arguments),this.name="WalletSignMessageError"}}class Pu extends Dt{constructor(){super(...arguments),this.name="WalletSignInError"}}class Gb extends Dt{constructor(){super(...arguments),this.name="WalletWindowClosedError"}}var pe;(function(s){s.Installed="Installed",s.NotDetected="NotDetected",s.Loadable="Loadable",s.Unsupported="Unsupported"})(pe||(pe={}));class yf extends N.EventEmitter{get connected(){return!!this.publicKey}async autoConnect(){await this.connect()}async prepareTransaction(e,t,i={}){const r=this.publicKey;if(!r)throw new Ke;return e.feePayer=e.feePayer||r,e.recentBlockhash=e.recentBlockhash||(await t.getLatestBlockhash({commitment:i.preflightCommitment,minContextSlot:i.minContextSlot})).blockhash,e}}function Ro(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 di(s){return"version"in s}class $h extends yf{async sendTransaction(e,t,i={}){let r=!0;try{if(di(e)){if(!this.supportedTransactionVersions)throw new rr("Sending versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(e.version))throw new rr(`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 rt?(r=!1,n):new rr(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 rt?(r=!1,n):new rr(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(di(i)){if(!this.supportedTransactionVersions)throw new rt("Signing versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(i.version))throw new rt(`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 Uo extends $h{}const Pi="solana:signAndSendTransaction",Oc="solana:signIn",Ln="solana:signMessage",Mt="solana:signTransaction",mf="standard:connect",$u="standard:disconnect",bf="standard:events";function Yb(s){return mf in s.features&&bf in s.features&&(Pi in s.features||Mt in s.features)}var No;(function(s){s.Mainnet="mainnet-beta",s.Testnet="testnet",s.Devnet="devnet"})(No||(No={}));const Qb="Bitget";class Jb extends Uo{constructor(e={}){super(),this.name=Qb,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"?pe.Unsupported:pe.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==pe.Unsupported&&Ro(()=>{var t,i;return(i=(t=window.bitkeep)==null?void 0:t.solana)!=null&&i.isBitKeep?(this._readyState=pe.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!==pe.Installed)throw new Li;this._connecting=!0;const e=window.bitkeep.solana;let t;try{t=await e.getAccount()}catch(r){throw new As(r==null?void 0:r.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new wr(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 ko(t==null?void 0:t.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(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 Ke;try{return await t.signAllTransactions(e)||e}catch(i){throw new rt(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 Ke;try{const{signature:i}=await t.signMessage(e);return i}catch(i){throw new rt(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const Zb="Clover";class Xb extends Uo{constructor(e={}){super(),this.name=Zb,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"?pe.Unsupported:pe.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==pe.Unsupported&&Ro(()=>{var t;return(t=window.clover_solana)!=null&&t.isCloverWallet?(this._readyState=pe.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!==pe.Installed)throw new Li;this._connecting=!0;const e=window.clover_solana;let t;try{t=await e.getAccount()}catch(r){throw new As(r==null?void 0:r.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new wr(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 Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(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 Ke;try{return await t.signAllTransactions(e)||e}catch(i){throw new rt(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 Ke;try{const{signature:i}=await t.signMessage(e);return Uint8Array.from(i)}catch(i){throw new jo(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}function ev(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),d=h.charCodeAt(0);if(e[d]!==255)throw new TypeError(h+" is ambiguous");e[d]=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,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,h++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let y=l[p],A=0;for(let _=g-1;(y!==0||A<d)&&_!==-1;_--,A++)y+=256*w[_]>>>0,w[_]=y%t>>>0,y=y/t>>>0;if(y!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(h);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,d=0,p=0;for(;l[h]===i;)d++,h++;const f=(l.length-h)*r+1>>>0,g=new Uint8Array(f);for(;h<l.length;){const y=l.charCodeAt(h);if(y>255)return;let A=e[y];if(A===255)return;let _=0;for(let C=f-1;(A!==0||_<p)&&C!==-1;C--,_++)A+=t*g[C]>>>0,g[C]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=_,h++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 tv="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const xc=ev(tv),sv="Coin98";class iv extends Uo{constructor(e={}){super(),this.name=sv,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"?pe.Unsupported:pe.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==pe.Unsupported&&Ro(()=>{var t;return(t=window.coin98)!=null&&t.sol?(this._readyState=pe.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!==pe.Installed)throw new Li;this._connecting=!0;const e=window.coin98.sol;let t;try{t=(await e.connect())[0]}catch(r){throw new As(r==null?void 0:r.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new wr(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 ko(t==null?void 0:t.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{const i=await t.request({method:"sol_sign",params:[e]}),r=new N.PublicKey(i.publicKey),n=xc.decode(i.signature);return e.addSignature(r,N.dist.Buffer.from(n)),e}catch(i){throw new rt(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 Ke;try{const i=await t.request({method:"sol_signAllTransactions",params:[e]}),r=new N.PublicKey(i.publicKey),n=i.signatures;return e.map((o,a)=>{const c=xc.decode(n[a]);return o.addSignature(r,N.dist.Buffer.from(c)),o})}catch(i){throw new rt(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 Ke;try{const i=await t.request({method:"sol_signMessage",params:[e]});return xc.decode(i.signature)}catch(i){throw new jo(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const rv="Nightly";class Mu extends Uo{constructor(){super(),this.name=rv,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"?pe.Unsupported:pe.NotDetected,this._connecting=!1,this._publicKey=null,this._wallet=null,this._readyState!==pe.Unsupported&&Ro(()=>{var e;return(e=window==null?void 0:window.nightly)!=null&&e.solana?(this._readyState=pe.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!==pe.Installed)throw new Li;this._connecting=!0;const e=window.nightly.solana;try{await e.connect()}catch(i){throw new cc(i==null?void 0:i.message,i)}if(e.publicKey.toString()==="11111111111111111111111111111111")throw new As;let t;try{t=new N.PublicKey(e.publicKey.toBytes())}catch(i){throw new wr(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 wf)}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)}catch(i){throw new rt(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 Ke;try{return await t.signAllTransactions(e)}catch(i){throw new rt(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 Ke;try{return t.signMessage(new TextDecoder().decode(e))}catch(i){throw new rt(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const Ou="solana:mainnet",nv="solana:devnet",ov="solana:testnet",av="solana:localnet",cv="Solong";class lv extends $h{constructor(e={}){super(),this.name=cv,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"?pe.Unsupported:pe.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==pe.Unsupported&&Ro(()=>window.solong?(this._readyState=pe.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!==pe.Installed)throw new Li;this._connecting=!0;const e=window.solong;let t;try{t=await e.selectAccount()}catch(r){throw new As(r==null?void 0:r.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new wr(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 Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}const hv="Torus";class uv extends Uo{constructor({params:e={showTorusButton:!1}}={params:{showTorusButton:!1}}){super(),this.name=hv,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"?pe.Unsupported:pe.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!==pe.Loadable)throw new Li;this._connecting=!0;let e;try{e=(await Promise.resolve().then(()=>require("./solanaEmbed.esm-D8vtESE6.js"))).default}catch(n){throw new Kb(n==null?void 0:n.message,n)}let t;try{t=window.torus||new e}catch(n){throw new un(n==null?void 0:n.message,n)}if(!t.isInitialized)try{await t.init(this._params)}catch(n){throw new cc(n==null?void 0:n.message,n)}let i;try{i=await t.login()}catch(n){throw new As(n==null?void 0:n.message,n)}let r;try{r=new N.PublicKey(i[0])}catch(n){throw new wr(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 ko(t==null?void 0:t.message,t))}}this.emit("disconnect")}async sendTransaction(e,t,i={}){try{const r=this._wallet;if(!r)throw new Ke;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 Dt?n:new rr(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 Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(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 Ke;try{return await t.signAllTransactions(e)||e}catch(i){throw new rt(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 Ke;try{return await t.signMessage(e)}catch(i){throw new jo(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}}}function Dc(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 dv="https://api.mainnet-beta.solana.com";function pv(s){return s.includes(dv)?Ou:/\bdevnet\b/i.test(s)?nv:/\btestnet\b/i.test(s)?ov:/\blocalhost\b/i.test(s)||/\b127\.0\.0\.1\b/.test(s)?av:Ou}var Ba;(function(s){s.Mainnet="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",s.Devnet="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",s.Deprecated_Mainnet="solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",s.Deprecated_Devnet="solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"})(Ba||(Ba={}));var Is;(function(s){s.signTransaction="solana_signTransaction",s.signMessage="solana_signMessage",s.signAndSendTransaction="solana_signAndSendTransaction",s.signAndSendAllTransactions="solana_signAndSendAllTransactions",s.signAllTransactions="solana_signAllTransactions"})(Is||(Is={}));const gt={Mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Deprecated_Mainnet:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",Deprecated_Devnet:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"};var gv=Object.defineProperty,fv=(s,e,t)=>e in s?gv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,xu=(s,e,t)=>fv(s,typeof e!="symbol"?e+"":e,t);let wv=class extends u.IEvents{constructor(e){super(),this.opts=e,xu(this,"protocol","wc"),xu(this,"version",2)}};var yv=Object.defineProperty,mv=(s,e,t)=>e in s?yv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,bv=(s,e,t)=>mv(s,e+"",t);let vv=class extends u.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,bv(this,"records",new Map)}},Iv=class{constructor(e,t){this.logger=e,this.core=t}},Ev=class extends u.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},Av=class extends u.IEvents{constructor(e){super()}},Nv=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},_v=class extends u.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},Cv=class extends u.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},Sv=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},Tv=class{constructor(e,t){this.projectId=e,this.logger=t}},Pv=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};function _o(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function Du(s){return _o(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const vf="2.23.2";let zn={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${vf}`},lc=class Cl extends Error{constructor(e,t={}){var a;const i=(()=>{var c;return t.cause instanceof Cl?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),r=t.cause instanceof Cl&&t.cause.docsPath||t.docsPath,n=(a=zn.getDocsUrl)==null?void 0:a.call(zn,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...zn.version?[`Version: ${zn.version}`]:[]].join(`
|
|
2
|
+
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=vf}walk(e){return If(this,e)}};function If(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?If(s.cause,e):e?null:s}let Ef=class extends lc{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 Sn(s,{dir:e,size:t=32}={}){return typeof s=="string"?$v(s,{dir:e,size:t}):Mv(s,{dir:e,size:t})}function $v(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new Ef({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function Mv(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new Ef({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 Ov=class extends lc{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"})}},xv=class extends lc{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function Tn(s,{size:e}){if(Du(s)>e)throw new xv({givenSize:Du(s),maxSize:e})}function Sl(s,e={}){const{signed:t}=e;e.size&&Tn(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 Dv(s,e={}){return Number(Sl(s,e))}const kv=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Tl(s,e={}){return typeof s=="number"||typeof s=="bigint"?Nf(s,e):typeof s=="string"?Uv(s,e):typeof s=="boolean"?jv(s,e):Af(s,e)}function jv(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(Tn(t,{size:e.size}),Sn(t,{size:e.size})):t}function Af(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=kv[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(Tn(i,{size:e.size}),Sn(i,{dir:"right",size:e.size})):i}function Nf(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 Ov({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?Sn(a,{size:i}):a}const Rv=new TextEncoder;function Uv(s,e={}){const t=Rv.encode(s);return Af(t,e)}const Lv=new TextEncoder;function zv(s,e={}){return typeof s=="number"||typeof s=="bigint"?qv(s,e):typeof s=="boolean"?Fv(s,e):_o(s)?_f(s,e):Cf(s,e)}function Fv(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(Tn(t,{size:e.size}),Sn(t,{size:e.size})):t}const si={zero:48,nine:57,A:65,F:70,a:97,f:102};function ku(s){if(s>=si.zero&&s<=si.nine)return s-si.zero;if(s>=si.A&&s<=si.F)return s-(si.A-10);if(s>=si.a&&s<=si.f)return s-(si.a-10)}function _f(s,e={}){let t=s;e.size&&(Tn(t,{size:e.size}),t=Sn(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=ku(i.charCodeAt(a++)),l=ku(i.charCodeAt(a++));if(c===void 0||l===void 0)throw new lc(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function qv(s,e){const t=Nf(s,e);return _f(t)}function Cf(s,e={}){const t=Lv.encode(s);return typeof e.size=="number"?(Tn(t,{size:e.size}),Sn(t,{dir:"right",size:e.size})):t}function Ha(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Bv(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Lo(s,...e){if(!Bv(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 Hv(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ha(s.outputLen),Ha(s.blockLen)}function Pl(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 Sf(s,e){Lo(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),ju=BigInt(32);function Wv(s,e=!1){return e?{h:Number(s&la),l:Number(s>>ju&la)}:{h:Number(s>>ju&la)|0,l:Number(s&la)|0}}function Vv(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}=Wv(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const Kv=(s,e,t)=>s<<t|e>>>32-t,Gv=(s,e,t)=>e<<t|s>>>32-t,Yv=(s,e,t)=>e<<t-32|s>>>64-t,Qv=(s,e,t)=>s<<t-32|e>>>64-t,Nr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Jv(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Zv(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Xv(s,e){return s<<32-e|s>>>e}const Ru=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function e0(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Uu(s){for(let e=0;e<s.length;e++)s[e]=e0(s[e])}function t0(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Mh(s){return typeof s=="string"&&(s=t0(s)),Lo(s),s}function s0(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Lo(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 Tf=class{clone(){return this._cloneInto()}};function Pf(s){const e=i=>s().update(Mh(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function i0(s=32){if(Nr&&typeof Nr.getRandomValues=="function")return Nr.getRandomValues(new Uint8Array(s));if(Nr&&typeof Nr.randomBytes=="function")return Nr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const $f=[],Mf=[],Of=[],r0=BigInt(0),Fn=BigInt(1),n0=BigInt(2),o0=BigInt(7),a0=BigInt(256),c0=BigInt(113);for(let s=0,e=Fn,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],$f.push(2*(5*i+t)),Mf.push((s+1)*(s+2)/2%64);let r=r0;for(let n=0;n<7;n++)e=(e<<Fn^(e>>o0)*c0)%a0,e&n0&&(r^=Fn<<(Fn<<BigInt(n))-Fn);Of.push(r)}const[l0,h0]=Vv(Of,!0),Lu=(s,e,t)=>t>32?Yv(s,e,t):Kv(s,e,t),zu=(s,e,t)=>t>32?Qv(s,e,t):Gv(s,e,t);function u0(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],d=Lu(l,h,1)^t[a],p=zu(l,h,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Mf[o],c=Lu(r,n,a),l=zu(r,n,a),h=$f[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]^=l0[i],s[1]^=h0[i]}t.fill(0)}let d0=class xf extends Tf{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,Ha(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Jv(this.state)}keccak(){Ru||Uu(this.state32),u0(this.state32,this.rounds),Ru||Uu(this.state32),this.posOut=0,this.pos=0}update(e){Pl(this);const{blockLen:t,state:i}=this;e=Mh(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){Pl(this,!1),Lo(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 Ha(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Sf(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 xf(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 p0=(s,e,t)=>Pf(()=>new d0(e,s,t)),g0=p0(1,136,256/8);function Df(s,e){const t=e||"hex",i=g0(_o(s,{strict:!1})?zv(s):s);return t==="bytes"?i:Tl(i)}let f0=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 kc=new f0(8192);function w0(s,e){if(kc.has(`${s}.${e}`))return kc.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=Df(Cf(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 kc.set(`${s}.${e}`,n),n}function y0(s){const e=Df(`0x${s.substring(4)}`).substring(26);return w0(`0x${e}`)}async function m0({hash:s,signature:e}){const t=_o(s)?s:Tl(s),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-D-DmPYcJ.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:h,v:d,yParity:p}=e,f=Number(p??d),g=Fu(f);return new i.Signature(Sl(l),Sl(h)).addRecoveryBit(g)}const o=_o(e)?e:Tl(e),a=Dv(`0x${o.slice(130)}`),c=Fu(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Fu(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 b0({hash:s,signature:e}){return y0(await m0({hash:s,signature:e}))}var kf=tt.requireElliptic();const jf=":";function yn(s){const[e,t]=s.split(jf);return{namespace:e,reference:t}}function v0(s){const[e,t,i]=s.split(jf);return{namespace:e,reference:t,address:i}}function Rf(s,e){return s.includes(":")?[s]:e.chains||[]}const I0="ReactNative",ls={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},E0="js";function Wa(){return typeof N.dist.process<"u"&&typeof N.dist.process.versions<"u"&&typeof N.dist.process.versions.node<"u"}function zi(){return!u.getDocument_1()&&!!u.getNavigator_1()&&navigator.product===I0}function A0(){return zi()&&typeof N.dist.global<"u"&&typeof(N.dist.global==null?void 0:N.dist.global.Platform)<"u"&&(N.dist.global==null?void 0:N.dist.global.Platform.OS)==="android"}function N0(){return zi()&&typeof N.dist.global<"u"&&typeof(N.dist.global==null?void 0:N.dist.global.Platform)<"u"&&(N.dist.global==null?void 0:N.dist.global.Platform.OS)==="ios"}function zo(){return!Wa()&&!!u.getNavigator_1()&&!!u.getDocument_1()}function Fo(){return zi()?ls.reactNative:Wa()?ls.node:zo()?ls.browser:ls.unknown}function qu(){var s;try{return zi()&&typeof N.dist.global<"u"&&typeof(N.dist.global==null?void 0:N.dist.global.Application)<"u"?(s=N.dist.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function _0(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 Uf(){return u.getWindowMetadata_1()||{name:"",description:"",url:"",icons:[""]}}function C0(){if(Fo()===ls.reactNative&&typeof N.dist.global<"u"&&typeof(N.dist.global==null?void 0:N.dist.global.Platform)<"u"){const{OS:t,Version:i}=N.dist.global.Platform;return[t,i].join("-")}const s=u.detect();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 S0(){var s;const e=Fo();return e===ls.browser?[e,((s=u.getLocation_1())==null?void 0:s.host)||"unknown"].join(":"):e}function Lf(s,e,t){const i=C0(),r=S0();return[[s,e].join("-"),[E0,t].join("-"),i,r].join("/")}function T0({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=t.split("?"),h=Lf(s,e,i),d={auth:r,ua:h,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=_0(l[1]||"",d);return l[0]+"?"+p}function nr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function zf(s){return Object.fromEntries(s.entries())}function Ff(s){return new Map(Object.entries(s))}function Ji(s=u.cjs.FIVE_MINUTES,e){const t=u.cjs.toMiliseconds(s||u.cjs.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 $i(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 qf(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 P0(s){return qf("topic",s)}function $0(s){return qf("id",s)}function Bf(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 dt(s,e){return u.cjs.fromMiliseconds(Date.now()+u.cjs.toMiliseconds(s))}function Ci(s){return Date.now()>=u.cjs.toMiliseconds(s)}function Pe(s,e){return`${s}${e?`:${e}`:""}`}function xa(s=[],e=[]){return[...new Set([...s,...e])]}async function M0({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=O0(n,s,e),a=Fo();if(a===ls.browser){if(!((i=u.getDocument_1())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}x0(o)}else a===ls.reactNative&&typeof(N.dist.global==null?void 0:N.dist.global.Linking)<"u"&&await N.dist.global.Linking.openURL(o)}catch(r){console.error(r)}}function O0(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}${R0(i,!0)}`}else r=`${r}/wc?${i}`;return r}function x0(s){let e="_self";j0()?e="_top":(k0()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function D0(s,e){let t="";try{if(zo()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Bu(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Hu(){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 Oh(){return typeof N.dist.process<"u"&&N.dist.process.env.IS_VITEST==="true"}function k0(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function j0(){try{return window.self!==window.top}catch{return!1}}function R0(s,e=!1){const t=N.dist.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Hf(s){return N.dist.Buffer.from(s,"base64").toString("utf-8")}function U0(s){return new Promise(e=>setTimeout(e,s))}function Co(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function L0(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function hc(s,...e){if(!L0(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 xh(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Co(s.outputLen),Co(s.blockLen)}function In(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 Wf(s,e){hc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ha=BigInt(2**32-1),Wu=BigInt(32);function z0(s,e=!1){return e?{h:Number(s&ha),l:Number(s>>Wu&ha)}:{h:Number(s>>Wu&ha)|0,l:Number(s&ha)|0}}function F0(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}=z0(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const q0=(s,e,t)=>s<<t|e>>>32-t,B0=(s,e,t)=>e<<t|s>>>32-t,H0=(s,e,t)=>e<<t-32|s>>>64-t,W0=(s,e,t)=>s<<t-32|e>>>64-t,_r=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function V0(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function jc(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function zs(s,e){return s<<32-e|s>>>e}const Vu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function K0(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Ku(s){for(let e=0;e<s.length;e++)s[e]=K0(s[e])}function G0(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function En(s){return typeof s=="string"&&(s=G0(s)),hc(s),s}let Dh=class{clone(){return this._cloneInto()}};function Vf(s){const e=i=>s().update(En(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function qo(s=32){if(_r&&typeof _r.getRandomValues=="function")return _r.getRandomValues(new Uint8Array(s));if(_r&&typeof _r.randomBytes=="function")return _r.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Kf=[],Gf=[],Yf=[],Y0=BigInt(0),qn=BigInt(1),Q0=BigInt(2),J0=BigInt(7),Z0=BigInt(256),X0=BigInt(113);for(let s=0,e=qn,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Kf.push(2*(5*i+t)),Gf.push((s+1)*(s+2)/2%64);let r=Y0;for(let n=0;n<7;n++)e=(e<<qn^(e>>J0)*X0)%Z0,e&Q0&&(r^=qn<<(qn<<BigInt(n))-qn);Yf.push(r)}const[eI,tI]=F0(Yf,!0),Gu=(s,e,t)=>t>32?H0(s,e,t):q0(s,e,t),Yu=(s,e,t)=>t>32?W0(s,e,t):B0(s,e,t);function sI(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],d=Gu(l,h,1)^t[a],p=Yu(l,h,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Gf[o],c=Gu(r,n,a),l=Yu(r,n,a),h=Kf[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]^=eI[i],s[1]^=tI[i]}t.fill(0)}let iI=class Qf extends Dh{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,Co(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=V0(this.state)}keccak(){Vu||Ku(this.state32),sI(this.state32,this.rounds),Vu||Ku(this.state32),this.posOut=0,this.pos=0}update(e){In(this);const{blockLen:t,state:i}=this;e=En(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){In(this,!1),hc(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 Co(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Wf(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 Qf(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 rI=(s,e,t)=>Vf(()=>new iI(e,s,t)),nI=rI(1,136,256/8),oI="https://rpc.walletconnect.org/v1";function Jf(s){const e=`Ethereum Signed Message:
|
|
3
|
+
${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+N.dist.Buffer.from(nI(t)).toString("hex")}async function aI(s,e,t,i,r,n){switch(t.t){case"eip191":return await cI(s,e,t.s);case"eip1271":return await lI(s,e,t.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function cI(s,e,t){return(await b0({hash:Jf(e),signature:t})).toLowerCase()===s.toLowerCase()}async function lI(s,e,t,i,r,n){const o=yn(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),d=Jf(e).substring(2),p=a+d+c+l+h,f=await fetch(`${n||oI}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:hI(),jsonrpc:"2.0",method:"eth_call",params:[{to:s,data:p},"latest"]})}),{result:g}=await f.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function hI(){return Date.now()+Math.floor(Math.random()*1e3)}var uI=Object.defineProperty,dI=Object.defineProperties,pI=Object.getOwnPropertyDescriptors,Qu=Object.getOwnPropertySymbols,gI=Object.prototype.hasOwnProperty,fI=Object.prototype.propertyIsEnumerable,Ju=(s,e,t)=>e in s?uI(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,wI=(s,e)=>{for(var t in e||(e={}))gI.call(e,t)&&Ju(s,t,e[t]);if(Qu)for(var t of Qu(e))fI.call(e,t)&&Ju(s,t,e[t]);return s},yI=(s,e)=>dI(s,pI(e));const mI="did:pkh:",kh=s=>s==null?void 0:s.split(":"),bI=s=>{const e=s&&kh(s);if(e)return s.includes(mI)?e[3]:e[1]},$l=s=>{const e=s&&kh(s);if(e)return e[2]+":"+e[3]},Va=s=>{const e=s&&kh(s);if(e)return e.pop()};async function Zu(s){const{cacao:e,projectId:t}=s,{s:i,p:r}=e,n=Zf(r,r.iss),o=Va(r.iss);return await aI(o,n,i,$l(r.iss),t)}const Zf=(s,e)=>{const t=`${s.domain} wants you to sign in with your Ethereum account:`,i=Va(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: ${bI(e)}`,c=`Nonce: ${s.nonce}`,l=`Issued At: ${s.iat}`,h=s.exp?`Expiration Time: ${s.exp}`:void 0,d=s.nbf?`Not Before: ${s.nbf}`:void 0,p=s.requestId?`Request ID: ${s.requestId}`:void 0,f=s.resources?`Resources:${s.resources.map(w=>`
|
|
4
|
+
- ${w}`).join("")}`:void 0,g=Da(s.resources);if(g){const w=So(g);r=TI(r,w)}return[t,i,"",r,"",n,o,a,c,l,h,d,p,f].filter(w=>w!=null).join(`
|
|
5
|
+
`)};function vI(s){return N.dist.Buffer.from(JSON.stringify(s)).toString("base64")}function II(s){return JSON.parse(N.dist.Buffer.from(s,"base64").toString("utf-8"))}function lr(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 EI(s,e,t,i={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[s]:AI(e,t,i)}}}function AI(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 Xf(s){return lr(s),`urn:recap:${vI(s).replace(/=/g,"")}`}function So(s){const e=II(s.replace("urn:recap:",""));return lr(e),e}function NI(s,e,t){const i=EI(s,e,t);return Xf(i)}function _I(s){return s&&s.includes("urn:recap:")}function CI(s,e){const t=So(s),i=So(e),r=SI(t,i);return Xf(r)}function SI(s,e){lr(s),lr(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]=yI(wI({},i.att[r]),{[a]:((c=s.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),i}function TI(s="",e){lr(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(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));c.sort((d,p)=>d.action.localeCompare(p.action));const l={};c.forEach(d=>{l[d.ability]||(l[d.ability]=[]),l[d.ability].push(d.action)});const h=Object.keys(l).map(d=>(r++,`(${r}) '${d}': '${l[d].join("', '")}' for '${a}'.`));i.push(h.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${s?s+" ":""}${o}`}function Xu(s){var e;const t=So(s);lr(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function ed(s){const e=So(s);lr(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 Da(s){if(!s)return;const e=s==null?void 0:s[s.length-1];return _I(e)?e:void 0}function Rc(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function ew(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function as(s,...e){if(!ew(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 td(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 PI(s,e){as(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function sd(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}const ki=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),$I=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),MI=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!MI)throw new Error("Non little-endian hardware is not supported");function OI(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Ml(s){if(typeof s=="string")s=OI(s);else if(ew(s))s=Ol(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function xI(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function DI(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 kI=(s,e)=>{function t(i,...r){if(as(i),s.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");s.varSizeNonce?as(l):as(l,s.nonceLength)}const n=s.tagLength;n&&r[1]!==void 0&&as(r[1]);const o=e(i,...r),a=(l,h)=>{if(h!==void 0){if(l!==2)throw new Error("cipher output not supported");as(h)}};let c=!1;return{encrypt(l,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,as(l),a(o.encrypt.length,h),o.encrypt(l,h)},decrypt(l,h){if(as(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 id(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&&!jI(e))throw new Error("invalid output, must be aligned");return e}function rd(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 jI(s){return s.byteOffset%4===0}function Ol(s){return Uint8Array.from(s)}function An(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}const tw=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),RI=tw("expand 16-byte k"),UI=tw("expand 32-byte k"),LI=ki(RI),zI=ki(UI);function Ie(s,e){return s<<e|s>>>32-e}function xl(s){return s.byteOffset%4===0}const ua=64,FI=16,sw=2**32-1,nd=new Uint32Array;function qI(s,e,t,i,r,n,o,a){const c=r.length,l=new Uint8Array(ua),h=ki(l),d=xl(r)&&xl(n),p=d?ki(r):nd,f=d?ki(n):nd;for(let g=0;g<c;o++){if(s(e,t,i,h,o,a),o>=sw)throw new Error("arx: counter overflow");const w=Math.min(ua,c-g);if(d&&w===ua){const v=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let b=0,y;b<FI;b++)y=v+b,f[y]=p[y]^h[b];g+=ua;continue}for(let v=0,b;v<w;v++)b=g+v,n[b]=r[b]^l[v];g+=w}}function BI(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=xI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return Rc(r),Rc(o),sd(n),sd(t),(a,c,l,h,d=0)=>{as(a),as(c),as(l);const p=l.length;if(h===void 0&&(h=new Uint8Array(p)),as(h),Rc(d),d<0||d>=sw)throw new Error("arx: counter overflow");if(h.length<p)throw new Error(`arx: output (${h.length}) is shorter than data (${p})`);const f=[];let g=a.length,w,v;if(g===32)f.push(w=Ol(a)),v=zI;else if(g===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),v=LI,f.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);xl(c)||f.push(c=Ol(c));const b=ki(w);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(v,b,ki(c.subarray(0,16)),b),c=c.subarray(16)}const y=16-r;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const _=new Uint8Array(12);_.set(c,n?0:12-c.length),c=_,f.push(c)}const A=ki(c);return qI(s,v,b,A,l,h,d,o),An(...f),h}}const _t=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let HI=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=Ml(e),as(e,32);const t=_t(e,0),i=_t(e,2),r=_t(e,4),n=_t(e,6),o=_t(e,8),a=_t(e,10),c=_t(e,12),l=_t(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]=_t(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],d=o[4],p=o[5],f=o[6],g=o[7],w=o[8],v=o[9],b=_t(e,t+0),y=_t(e,t+2),A=_t(e,t+4),_=_t(e,t+6),C=_t(e,t+8),T=_t(e,t+10),P=_t(e,t+12),x=_t(e,t+14);let $=n[0]+(b&8191),q=n[1]+((b>>>13|y<<3)&8191),j=n[2]+((y>>>10|A<<6)&8191),G=n[3]+((A>>>7|_<<9)&8191),B=n[4]+((_>>>4|C<<12)&8191),W=n[5]+(C>>>1&8191),V=n[6]+((C>>>14|T<<2)&8191),H=n[7]+((T>>>11|P<<5)&8191),K=n[8]+((P>>>8|x<<8)&8191),Q=n[9]+(x>>>5|r),S=0,z=S+$*a+q*(5*v)+j*(5*w)+G*(5*g)+B*(5*f);S=z>>>13,z&=8191,z+=W*(5*p)+V*(5*d)+H*(5*h)+K*(5*l)+Q*(5*c),S+=z>>>13,z&=8191;let ee=S+$*c+q*a+j*(5*v)+G*(5*w)+B*(5*g);S=ee>>>13,ee&=8191,ee+=W*(5*f)+V*(5*p)+H*(5*d)+K*(5*h)+Q*(5*l),S+=ee>>>13,ee&=8191;let J=S+$*l+q*c+j*a+G*(5*v)+B*(5*w);S=J>>>13,J&=8191,J+=W*(5*g)+V*(5*f)+H*(5*p)+K*(5*d)+Q*(5*h),S+=J>>>13,J&=8191;let be=S+$*h+q*l+j*c+G*a+B*(5*v);S=be>>>13,be&=8191,be+=W*(5*w)+V*(5*g)+H*(5*f)+K*(5*p)+Q*(5*d),S+=be>>>13,be&=8191;let de=S+$*d+q*h+j*l+G*c+B*a;S=de>>>13,de&=8191,de+=W*(5*v)+V*(5*w)+H*(5*g)+K*(5*f)+Q*(5*p),S+=de>>>13,de&=8191;let te=S+$*p+q*d+j*h+G*l+B*c;S=te>>>13,te&=8191,te+=W*a+V*(5*v)+H*(5*w)+K*(5*g)+Q*(5*f),S+=te>>>13,te&=8191;let st=S+$*f+q*p+j*d+G*h+B*l;S=st>>>13,st&=8191,st+=W*c+V*a+H*(5*v)+K*(5*w)+Q*(5*g),S+=st>>>13,st&=8191;let Ue=S+$*g+q*f+j*p+G*d+B*h;S=Ue>>>13,Ue&=8191,Ue+=W*l+V*c+H*a+K*(5*v)+Q*(5*w),S+=Ue>>>13,Ue&=8191;let ve=S+$*w+q*g+j*f+G*p+B*d;S=ve>>>13,ve&=8191,ve+=W*h+V*l+H*c+K*a+Q*(5*v),S+=ve>>>13,ve&=8191;let De=S+$*v+q*w+j*g+G*f+B*p;S=De>>>13,De&=8191,De+=W*d+V*h+H*l+K*c+Q*a,S+=De>>>13,De&=8191,S=(S<<2)+S|0,S=S+z|0,z=S&8191,S=S>>>13,ee+=S,n[0]=z,n[1]=ee,n[2]=J,n[3]=be,n[4]=de,n[5]=te,n[6]=st,n[7]=Ue,n[8]=ve,n[9]=De}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;An(i)}update(e){td(this);const{buffer:t,blockLen:i}=this;e=Ml(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(){An(this.h,this.r,this.buffer,this.pad)}digestInto(e){td(this),PI(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 WI(s){const e=(i,r)=>s(r).update(Ml(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const VI=WI(s=>new HI(s));function KI(s,e,t,i,r,n=20){let o=s[0],a=s[1],c=s[2],l=s[3],h=e[0],d=e[1],p=e[2],f=e[3],g=e[4],w=e[5],v=e[6],b=e[7],y=r,A=t[0],_=t[1],C=t[2],T=o,P=a,x=c,$=l,q=h,j=d,G=p,B=f,W=g,V=w,H=v,K=b,Q=y,S=A,z=_,ee=C;for(let be=0;be<n;be+=2)T=T+q|0,Q=Ie(Q^T,16),W=W+Q|0,q=Ie(q^W,12),T=T+q|0,Q=Ie(Q^T,8),W=W+Q|0,q=Ie(q^W,7),P=P+j|0,S=Ie(S^P,16),V=V+S|0,j=Ie(j^V,12),P=P+j|0,S=Ie(S^P,8),V=V+S|0,j=Ie(j^V,7),x=x+G|0,z=Ie(z^x,16),H=H+z|0,G=Ie(G^H,12),x=x+G|0,z=Ie(z^x,8),H=H+z|0,G=Ie(G^H,7),$=$+B|0,ee=Ie(ee^$,16),K=K+ee|0,B=Ie(B^K,12),$=$+B|0,ee=Ie(ee^$,8),K=K+ee|0,B=Ie(B^K,7),T=T+j|0,ee=Ie(ee^T,16),H=H+ee|0,j=Ie(j^H,12),T=T+j|0,ee=Ie(ee^T,8),H=H+ee|0,j=Ie(j^H,7),P=P+G|0,Q=Ie(Q^P,16),K=K+Q|0,G=Ie(G^K,12),P=P+G|0,Q=Ie(Q^P,8),K=K+Q|0,G=Ie(G^K,7),x=x+B|0,S=Ie(S^x,16),W=W+S|0,B=Ie(B^W,12),x=x+B|0,S=Ie(S^x,8),W=W+S|0,B=Ie(B^W,7),$=$+q|0,z=Ie(z^$,16),V=V+z|0,q=Ie(q^V,12),$=$+q|0,z=Ie(z^$,8),V=V+z|0,q=Ie(q^V,7);let J=0;i[J++]=o+T|0,i[J++]=a+P|0,i[J++]=c+x|0,i[J++]=l+$|0,i[J++]=h+q|0,i[J++]=d+j|0,i[J++]=p+G|0,i[J++]=f+B|0,i[J++]=g+W|0,i[J++]=w+V|0,i[J++]=v+H|0,i[J++]=b+K|0,i[J++]=y+Q|0,i[J++]=A+S|0,i[J++]=_+z|0,i[J++]=C+ee|0}const GI=BI(KI,{counterRight:!1,counterLength:4,allowShortKeys:!1}),YI=new Uint8Array(16),od=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(YI.subarray(t))},QI=new Uint8Array(32);function ad(s,e,t,i,r){const n=s(e,t,QI),o=VI.create(n);r&&od(o,r),od(o,i);const a=new Uint8Array(16),c=$I(a);rd(c,0,BigInt(r?r.length:0),!0),rd(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return An(n,a),l}const JI=s=>(e,t,i)=>({encrypt(r,n){const o=r.length;n=id(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);s(e,t,a,a,1);const c=ad(s,e,t,a,i);return n.set(c,o),An(c),n},decrypt(r,n){n=id(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=ad(s,e,t,o,i);if(!DI(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),An(c),n}}),iw=kI({blockSize:64,nonceLength:12,tagLength:16},JI(GI));let rw=class extends Dh{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,xh(e);const i=En(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 In(this),this.iHash.update(e),this}digestInto(e){In(this),hc(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 jh=(s,e,t)=>new rw(s,e).update(t).digest();jh.create=(s,e)=>new rw(s,e);function ZI(s,e,t){return xh(s),t===void 0&&(t=new Uint8Array(s.outputLen)),jh(s,En(t),En(e))}const Uc=new Uint8Array([0]),cd=new Uint8Array;function XI(s,e,t,i=32){if(xh(s),Co(i),i>255*s.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/s.outputLen);t===void 0&&(t=cd);const n=new Uint8Array(r*s.outputLen),o=jh.create(s,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)Uc[0]=l+1,a.update(l===0?cd:c).update(t).update(Uc).digestInto(c),n.set(c,s.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Uc.fill(0),n.slice(0,i)}const e1=(s,e,t,i,r)=>XI(s,ZI(s,e,t),i,r);function t1(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 s1(s,e,t){return s&e^~s&t}function i1(s,e,t){return s&e^s&t^e&t}let r1=class extends Dh{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=jc(this.buffer)}update(e){In(this);const{view:t,buffer:i,blockLen:r}=this;e=En(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=jc(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){In(this),Wf(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 d=o;d<r;d++)t[d]=0;t1(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=jc(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 d=0;d<l;d++)a.setUint32(4*d,h[d],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 n1=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]),bi=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),vi=new Uint32Array(64);let o1=class extends r1{constructor(){super(64,32,8,!1),this.A=bi[0]|0,this.B=bi[1]|0,this.C=bi[2]|0,this.D=bi[3]|0,this.E=bi[4]|0,this.F=bi[5]|0,this.G=bi[6]|0,this.H=bi[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 d=0;d<16;d++,t+=4)vi[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const p=vi[d-15],f=vi[d-2],g=zs(p,7)^zs(p,18)^p>>>3,w=zs(f,17)^zs(f,19)^f>>>10;vi[d]=w+vi[d-7]+g+vi[d-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:c,G:l,H:h}=this;for(let d=0;d<64;d++){const p=zs(a,6)^zs(a,11)^zs(a,25),f=h+p+s1(a,c,l)+n1[d]+vi[d]|0,g=(zs(i,2)^zs(i,13)^zs(i,22))+i1(i,r,n)|0;h=l,l=c,c=a,a=o+f|0,o=n,n=r,r=i,i=f+g|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(){vi.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const uc=Vf(()=>new o1);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nw=BigInt(0);function Rh(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ow(s){if(!Rh(s))throw new Error("Uint8Array expected")}const a1=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function c1(s){ow(s);let e="";for(let t=0;t<s.length;t++)e+=a1[s[t]];return e}function l1(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?nw:BigInt("0x"+s)}const ii={_0:48,_9:57,A:65,F:70,a:97,f:102};function ld(s){if(s>=ii._0&&s<=ii._9)return s-ii._0;if(s>=ii.A&&s<=ii.F)return s-(ii.A-10);if(s>=ii.a&&s<=ii.f)return s-(ii.a-10)}function aw(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=ld(s.charCodeAt(n)),a=ld(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 hd(s){return ow(s),l1(c1(Uint8Array.from(s).reverse()))}function h1(s,e){return aw(s.toString(16).padStart(e*2,"0"))}function u1(s,e){return h1(s,e).reverse()}function ud(s,e,t){let i;if(typeof e=="string")try{i=aw(e)}catch(n){throw new Error(s+" must be hex string or Uint8Array, cause: "+n)}else if(Rh(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 Lc=s=>typeof s=="bigint"&&nw<=s;function d1(s,e,t){return Lc(s)&&Lc(e)&&Lc(t)&&e<=s&&s<t}function dd(s,e,t,i){if(!d1(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const p1={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"||Rh(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 g1(s,e,t={}){const i=(r,n,o)=>{const a=p1[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),da=BigInt(1);function cw(s,e){const t=s%e;return t>=dn?t:e+t}function f1(s,e,t){if(e<dn)throw new Error("invalid exponent, negatives unsupported");if(t<=dn)throw new Error("invalid modulus");if(t===da)return dn;let i=da;for(;e>dn;)e&da&&(i=i*s%t),s=s*s%t,e>>=da;return i}function Ds(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 Cr=BigInt(0),zc=BigInt(1);function w1(s){return g1(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function y1(s){const e=w1(s),{P:t}=e,i=y=>cw(y,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(y=>y),c=e.powPminus2||(y=>f1(y,t-BigInt(2),t));function l(y,A,_){const C=i(y*(A-_));return A=i(A-C),_=i(_+C),[A,_]}const h=(e.a-BigInt(2))/BigInt(4);function d(y,A){dd("u",y,Cr,t),dd("scalar",A,Cr,t);const _=A,C=y;let T=zc,P=Cr,x=y,$=zc,q=Cr,j;for(let B=BigInt(r-1);B>=Cr;B--){const W=_>>B&zc;q^=W,j=l(q,T,x),T=j[0],x=j[1],j=l(q,P,$),P=j[0],$=j[1],q=W;const V=T+P,H=i(V*V),K=T-P,Q=i(K*K),S=H-Q,z=x+$,ee=x-$,J=i(ee*V),be=i(z*K),de=J+be,te=J-be;x=i(de*de),$=i(C*i(te*te)),T=i(H*Q),P=i(S*(H+i(h*S)))}j=l(q,T,x),T=j[0],x=j[1],j=l(q,P,$),P=j[0],$=j[1];const G=c(P);return i(T*G)}function p(y){return u1(i(y),n)}function f(y){const A=ud("u coordinate",y,n);return o===32&&(A[31]&=127),hd(A)}function g(y){const A=ud("scalar",y),_=A.length;if(_!==n&&_!==o){let C=""+n+" or "+o;throw new Error("invalid scalar, expected "+C+" bytes, got "+_)}return hd(a(A))}function w(y,A){const _=f(A),C=g(y),T=d(_,C);if(T===Cr)throw new Error("invalid private or public key received");return p(T)}const v=p(e.Gu);function b(y){return w(y,v)}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(y,A)=>w(y,A),getPublicKey:y=>b(y),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}const Dl=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const m1=BigInt(1),pd=BigInt(2),b1=BigInt(3),v1=BigInt(5);BigInt(8);function I1(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=Dl,o=s*s%n*s%n,a=Ds(o,pd,n)*o%n,c=Ds(a,m1,n)*s%n,l=Ds(c,v1,n)*c%n,h=Ds(l,e,n)*l%n,d=Ds(h,t,n)*h%n,p=Ds(d,i,n)*d%n,f=Ds(p,r,n)*p%n,g=Ds(f,r,n)*p%n,w=Ds(g,e,n)*l%n;return{pow_p_5_8:Ds(w,pd,n)*s%n,b2:o}}function E1(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const kl=y1({P:Dl,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=Dl,{pow_p_5_8:t,b2:i}=I1(s);return cw(Ds(t,b1,e)*i,e)},adjustScalarBytes:E1,randomBytes:qo}),lw="base10",qt="base16",Mi="base64pad",Bn="base64url",Bo="utf8",hw=0,pi=1,Ho=2,A1=0,gd=1,fo=12,Uh=32;function N1(){const s=kl.utils.randomPrivateKey(),e=kl.getPublicKey(s);return{privateKey:u.toString(s,qt),publicKey:u.toString(e,qt)}}function jl(){const s=qo(Uh);return u.toString(s,qt)}function _1(s,e){const t=kl.getSharedSecret(u.fromString(s,qt),u.fromString(e,qt)),i=e1(uc,t,void 0,void 0,Uh);return u.toString(i,qt)}function ka(s){const e=uc(u.fromString(s,qt));return u.toString(e,qt)}function ui(s){const e=uc(u.fromString(s,Bo));return u.toString(e,qt)}function uw(s){return u.fromString(`${s}`,lw)}function hr(s){return Number(u.toString(s,lw))}function C1(s){const e=uw(typeof s.type<"u"?s.type:hw);if(hr(e)===pi&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?u.fromString(s.senderPublicKey,qt):void 0,i=typeof s.iv<"u"?u.fromString(s.iv,qt):qo(fo),r=u.fromString(s.symKey,qt),n=iw(r,i).encrypt(u.fromString(s.message,Bo));return dw({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function S1(s){const e=u.fromString(s.symKey,qt),{sealed:t,iv:i}=To(s),r=iw(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return u.toString(r,Bo)}function T1(s,e){const t=uw(Ho),i=qo(fo),r=u.fromString(s,Bo);return dw({type:t,sealed:r,iv:i,encoding:e})}function P1(s,e){const{sealed:t}=To({encoded:s,encoding:e});return u.toString(t,Bo)}function dw(s){const{encoding:e=Mi}=s;if(hr(s.type)===Ho)return u.toString(u.concat([s.type,s.sealed]),e);if(hr(s.type)===pi){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return u.toString(u.concat([s.type,s.senderPublicKey,s.iv,s.sealed]),e)}return u.toString(u.concat([s.type,s.iv,s.sealed]),e)}function To(s){const{encoded:e,encoding:t=Mi}=s,i=u.fromString(e,t),r=i.slice(A1,gd),n=gd;if(hr(r)===pi){const l=n+Uh,h=l+fo,d=i.slice(n,l),p=i.slice(l,h),f=i.slice(h);return{type:r,sealed:f,iv:p,senderPublicKey:d}}if(hr(r)===Ho){const l=i.slice(n),h=qo(fo);return{type:r,sealed:l,iv:h}}const o=n+fo,a=i.slice(n,o),c=i.slice(o);return{type:r,sealed:c,iv:a}}function $1(s,e){const t=To({encoded:s,encoding:e==null?void 0:e.encoding});return pw({type:hr(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?u.toString(t.senderPublicKey,qt):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function pw(s){const e=(s==null?void 0:s.type)||hw;if(e===pi){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 fd(s){return s.type===pi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function wd(s){return s.type===Ho}function M1(s){return new kf.ec("p256").keyFromPublic({x:N.dist.Buffer.from(s.x,"base64").toString("hex"),y:N.dist.Buffer.from(s.y,"base64").toString("hex")},"hex")}function O1(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function x1(s){return N.dist.Buffer.from(O1(s),"base64")}function D1(s,e){const[t,i,r]=s.split("."),n=x1(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=uc(c),h=M1(e),d=u.toString(l,qt);if(!h.verify(d,{r:o,s:a}))throw new Error("Invalid signature");return u.sn(s).payload}const k1="irn";function Ka(s){return(s==null?void 0:s.relay)||{protocol:k1}}function ao(s){const e=u.C[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function j1(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 yd(s){if(!s.includes("wc:")){const l=Hf(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:R1(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:j1(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function R1(s){return s.startsWith("//")?s.substring(2):s}function U1(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 md(s){const e=new URLSearchParams,t=U1(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 pa(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function Pn(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function L1(s){const e=[];return Object.values(s).forEach(t=>{e.push(...Pn(t.accounts))}),e}function z1(s,e){const t=[];return Object.values(s).forEach(i=>{Pn(i.accounts).includes(e)&&t.push(...i.methods)}),t}function F1(s,e){const t=[];return Object.values(s).forEach(i=>{Pn(i.accounts).includes(e)&&t.push(...i.events)}),t}function Lh(s){return s.includes(":")}function co(s){return Lh(s)?s.split(":")[0]:s}function q1(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 bd(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=q1(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=xa(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const B1={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}},H1={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}=H1[s];return{message:e?`${t} ${e}`:t,code:i}}function je(s,e){const{message:t,code:i}=B1[s];return{message:e?`${t} ${e}`:t,code:i}}function ur(s,e){return!!Array.isArray(s)}function Po(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function Wt(s){return typeof s>"u"}function nt(s,e){return e&&Wt(s)?!0:typeof s=="string"&&!!s.trim().length}function zh(s,e){return e&&Wt(s)?!0:typeof s=="number"&&!isNaN(s)}function W1(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return nr(r,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=s.namespaces[o],h=Pn(a),d=t[o];(!nr(Rf(o,d),h)||!nr(d.methods,c)||!nr(d.events,l))&&(n=!1)}),n):!1}function Ga(s){return nt(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function V1(s){if(nt(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Ga(t)}}return!1}function K1(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(nt(s,!1)){if(e(s))return!0;const t=Hf(s);return e(t)}}catch{}return!1}function G1(s){var e;return(e=s==null?void 0:s.proposer)==null?void 0:e.publicKey}function Y1(s){return s==null?void 0:s.topic}function Q1(s,e){let t=null;return nt(s==null?void 0:s.publicKey,!1)||(t=U("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function vd(s){let e=!0;return ur(s)?s.length&&(e=s.every(t=>nt(t,!1))):e=!1,e}function J1(s,e,t){let i=null;return ur(e)&&e.length?e.forEach(r=>{i||Ga(r)||(i=je("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Ga(s)||(i=je("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 Z1(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=J1(r,Rf(r,n),`${e} ${t}`);o&&(i=o)}),i}function X1(s,e){let t=null;return ur(s)?s.forEach(i=>{t||V1(i)||(t=je("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=je("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function eE(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=X1(i==null?void 0:i.accounts,`${e} namespace`);r&&(t=r)}),t}function tE(s,e){let t=null;return vd(s==null?void 0:s.methods)?vd(s==null?void 0:s.events)||(t=je("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=je("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function gw(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=tE(i,`${e}, namespace`);r&&(t=r)}),t}function sE(s,e,t){let i=null;if(s&&Po(s)){const r=gw(s,e);r&&(i=r);const n=Z1(s,e,t);n&&(i=n)}else i=U("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function Fc(s,e){let t=null;if(s&&Po(s)){const i=gw(s,e);i&&(t=i);const r=eE(s,e);r&&(t=r)}else t=U("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function fw(s){return nt(s.protocol,!0)}function iE(s,e){let t=!1;return s?s&&ur(s)&&s.length&&s.forEach(i=>{t=fw(i)}):t=!0,t}function rE(s){return typeof s=="number"}function Zt(s){return typeof s<"u"&&typeof s!==null}function nE(s){return!(!s||typeof s!="object"||!s.code||!zh(s.code,!1)||!s.message||!nt(s.message,!1))}function oE(s){return!(Wt(s)||!nt(s.method,!1))}function aE(s){return!(Wt(s)||Wt(s.result)&&Wt(s.error)||!zh(s.id,!1)||!nt(s.jsonrpc,!1))}function cE(s){return!(Wt(s)||!nt(s.name,!1))}function Id(s,e){return!(!Ga(e)||!L1(s).includes(e))}function lE(s,e,t){return nt(t,!1)?z1(s,e).includes(t):!1}function hE(s,e,t){return nt(t,!1)?F1(s,e).includes(t):!1}function Ed(s,e,t){let i=null;const r=uE(s),n=dE(e),o=Object.keys(r),a=Object.keys(n),c=Ad(Object.keys(s)),l=Ad(Object.keys(e)),h=c.filter(d=>!l.includes(d));return h.length&&(i=U("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
|
|
6
|
+
Required: ${h.toString()}
|
|
7
|
+
Received: ${Object.keys(e).toString()}`)),nr(o,a)||(i=U("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces.
|
|
8
|
+
Required: ${o.toString()}
|
|
9
|
+
Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||i)return;const p=Pn(e[d].accounts);p.includes(d)||(i=U("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${d}
|
|
10
|
+
Required: ${d}
|
|
11
|
+
Approved: ${p.toString()}`))}),o.forEach(d=>{i||(nr(r[d].methods,n[d].methods)?nr(r[d].events,n[d].events)||(i=U("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${d}`)):i=U("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${d}`))}),i}function uE(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 Ad(s){return[...new Set(s.map(e=>e.includes(":")?e.split(":")[0]:e))]}function dE(s){const e={};return Object.keys(s).forEach(t=>{if(t.includes(":"))e[t]=s[t];else{const i=Pn(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 pE(s,e){return zh(s,!1)&&s<=e.max&&s>=e.min}function Nd(){const s=Fo();return new Promise(e=>{switch(s){case ls.browser:e(gE());break;case ls.reactNative:e(fE());break;case ls.node:e(wE());break;default:e(!0)}})}function gE(){return zo()&&(navigator==null?void 0:navigator.onLine)}async function fE(){if(zi()&&typeof N.dist.global<"u"&&N.dist.global!=null&&N.dist.global.NetInfo){const s=await(N.dist.global==null?void 0:N.dist.global.NetInfo.fetch());return s==null?void 0:s.isConnected}return!0}function wE(){return!0}function yE(s){switch(Fo()){case ls.browser:mE(s);break;case ls.reactNative:bE(s);break}}function mE(s){!zi()&&zo()&&(window.addEventListener("online",()=>s(!0)),window.addEventListener("offline",()=>s(!1)))}function bE(s){var e;zi()&&typeof N.dist.global<"u"&&N.dist.global!=null&&N.dist.global.NetInfo&&((e=N.dist.global)==null||e.NetInfo.addEventListener(t=>s(t==null?void 0:t.isConnected)))}const qc={};let Hn=class{static get(e){return qc[e]}static set(e,t){qc[e]=t}static delete(e){delete qc[e]}};var Ya={exports:{}};Ya.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]",d="[object Date]",p="[object Error]",f="[object Function]",g="[object GeneratorFunction]",w="[object Map]",v="[object Number]",b="[object Null]",y="[object Object]",A="[object Promise]",_="[object Proxy]",C="[object RegExp]",T="[object Set]",P="[object String]",x="[object Symbol]",$="[object Undefined]",q="[object WeakMap]",j="[object ArrayBuffer]",G="[object DataView]",B="[object Float32Array]",W="[object Float64Array]",V="[object Int8Array]",H="[object Int16Array]",K="[object Int32Array]",Q="[object Uint8Array]",S="[object Uint8ClampedArray]",z="[object Uint16Array]",ee="[object Uint32Array]",J=/[\\^$.*+?()[\]{}|]/g,be=/^\[object .+?Constructor\]$/,de=/^(?:0|[1-9]\d*)$/,te={};te[B]=te[W]=te[V]=te[H]=te[K]=te[Q]=te[S]=te[z]=te[ee]=!0,te[a]=te[c]=te[j]=te[h]=te[G]=te[d]=te[p]=te[f]=te[w]=te[v]=te[y]=te[C]=te[T]=te[P]=te[q]=!1;var st=typeof N.commonjsGlobal=="object"&&N.commonjsGlobal&&N.commonjsGlobal.Object===Object&&N.commonjsGlobal,Ue=typeof self=="object"&&self&&self.Object===Object&&self,ve=st||Ue||Function("return this")(),De=e&&!e.nodeType&&e,js=De&&!0&&s&&!s.nodeType&&s,Rs=js&&js.exports===De,Xs=Rs&&st.process,Er=function(){try{return Xs&&Xs.binding&&Xs.binding("util")}catch{}}(),Us=Er&&Er.isTypedArray;function Dn(m,E){for(var M=-1,Y=m==null?0:m.length,Ge=0,oe=[];++M<Y;){var it=m[M];E(it,M,m)&&(oe[Ge++]=it)}return oe}function Dm(m,E){for(var M=-1,Y=E.length,Ge=m.length;++M<Y;)m[Ge+M]=E[M];return m}function km(m,E){for(var M=-1,Y=m==null?0:m.length;++M<Y;)if(E(m[M],M,m))return!0;return!1}function jm(m,E){for(var M=-1,Y=Array(m);++M<m;)Y[M]=E(M);return Y}function Rm(m){return function(E){return m(E)}}function Um(m,E){return m.has(E)}function Lm(m,E){return m==null?void 0:m[E]}function zm(m){var E=-1,M=Array(m.size);return m.forEach(function(Y,Ge){M[++E]=[Ge,Y]}),M}function Fm(m,E){return function(M){return m(E(M))}}function qm(m){var E=-1,M=Array(m.size);return m.forEach(function(Y){M[++E]=Y}),M}var Bm=Array.prototype,Hm=Function.prototype,ta=Object.prototype,_c=ve["__core-js_shared__"],hu=Hm.toString,Ls=ta.hasOwnProperty,uu=function(){var m=/[^.]+$/.exec(_c&&_c.keys&&_c.keys.IE_PROTO||"");return m?"Symbol(src)_1."+m:""}(),du=ta.toString,Wm=RegExp("^"+hu.call(Ls).replace(J,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),pu=Rs?ve.Buffer:void 0,sa=ve.Symbol,gu=ve.Uint8Array,fu=ta.propertyIsEnumerable,Vm=Bm.splice,qi=sa?sa.toStringTag:void 0,wu=Object.getOwnPropertySymbols,Km=pu?pu.isBuffer:void 0,Gm=Fm(Object.keys,Object),Cc=Ar(ve,"DataView"),kn=Ar(ve,"Map"),Sc=Ar(ve,"Promise"),Tc=Ar(ve,"Set"),Pc=Ar(ve,"WeakMap"),jn=Ar(Object,"create"),Ym=Wi(Cc),Qm=Wi(kn),Jm=Wi(Sc),Zm=Wi(Tc),Xm=Wi(Pc),yu=sa?sa.prototype:void 0,$c=yu?yu.valueOf:void 0;function Bi(m){var E=-1,M=m==null?0:m.length;for(this.clear();++E<M;){var Y=m[E];this.set(Y[0],Y[1])}}function eb(){this.__data__=jn?jn(null):{},this.size=0}function tb(m){var E=this.has(m)&&delete this.__data__[m];return this.size-=E?1:0,E}function sb(m){var E=this.__data__;if(jn){var M=E[m];return M===i?void 0:M}return Ls.call(E,m)?E[m]:void 0}function ib(m){var E=this.__data__;return jn?E[m]!==void 0:Ls.call(E,m)}function rb(m,E){var M=this.__data__;return this.size+=this.has(m)?0:1,M[m]=jn&&E===void 0?i:E,this}Bi.prototype.clear=eb,Bi.prototype.delete=tb,Bi.prototype.get=sb,Bi.prototype.has=ib,Bi.prototype.set=rb;function ei(m){var E=-1,M=m==null?0:m.length;for(this.clear();++E<M;){var Y=m[E];this.set(Y[0],Y[1])}}function nb(){this.__data__=[],this.size=0}function ob(m){var E=this.__data__,M=ra(E,m);if(M<0)return!1;var Y=E.length-1;return M==Y?E.pop():Vm.call(E,M,1),--this.size,!0}function ab(m){var E=this.__data__,M=ra(E,m);return M<0?void 0:E[M][1]}function cb(m){return ra(this.__data__,m)>-1}function lb(m,E){var M=this.__data__,Y=ra(M,m);return Y<0?(++this.size,M.push([m,E])):M[Y][1]=E,this}ei.prototype.clear=nb,ei.prototype.delete=ob,ei.prototype.get=ab,ei.prototype.has=cb,ei.prototype.set=lb;function Hi(m){var E=-1,M=m==null?0:m.length;for(this.clear();++E<M;){var Y=m[E];this.set(Y[0],Y[1])}}function hb(){this.size=0,this.__data__={hash:new Bi,map:new(kn||ei),string:new Bi}}function ub(m){var E=na(this,m).delete(m);return this.size-=E?1:0,E}function db(m){return na(this,m).get(m)}function pb(m){return na(this,m).has(m)}function gb(m,E){var M=na(this,m),Y=M.size;return M.set(m,E),this.size+=M.size==Y?0:1,this}Hi.prototype.clear=hb,Hi.prototype.delete=ub,Hi.prototype.get=db,Hi.prototype.has=pb,Hi.prototype.set=gb;function ia(m){var E=-1,M=m==null?0:m.length;for(this.__data__=new Hi;++E<M;)this.add(m[E])}function fb(m){return this.__data__.set(m,i),this}function wb(m){return this.__data__.has(m)}ia.prototype.add=ia.prototype.push=fb,ia.prototype.has=wb;function wi(m){var E=this.__data__=new ei(m);this.size=E.size}function yb(){this.__data__=new ei,this.size=0}function mb(m){var E=this.__data__,M=E.delete(m);return this.size=E.size,M}function bb(m){return this.__data__.get(m)}function vb(m){return this.__data__.has(m)}function Ib(m,E){var M=this.__data__;if(M instanceof ei){var Y=M.__data__;if(!kn||Y.length<t-1)return Y.push([m,E]),this.size=++M.size,this;M=this.__data__=new Hi(Y)}return M.set(m,E),this.size=M.size,this}wi.prototype.clear=yb,wi.prototype.delete=mb,wi.prototype.get=bb,wi.prototype.has=vb,wi.prototype.set=Ib;function Eb(m,E){var M=oa(m),Y=!M&&Rb(m),Ge=!M&&!Y&&Mc(m),oe=!M&&!Y&&!Ge&&Cu(m),it=M||Y||Ge||oe,ft=it?jm(m.length,String):[],At=ft.length;for(var Ze in m)Ls.call(m,Ze)&&!(it&&(Ze=="length"||Ge&&(Ze=="offset"||Ze=="parent")||oe&&(Ze=="buffer"||Ze=="byteLength"||Ze=="byteOffset")||Ob(Ze,At)))&&ft.push(Ze);return ft}function ra(m,E){for(var M=m.length;M--;)if(Eu(m[M][0],E))return M;return-1}function Ab(m,E,M){var Y=E(m);return oa(m)?Y:Dm(Y,M(m))}function Rn(m){return m==null?m===void 0?$:b:qi&&qi in Object(m)?$b(m):jb(m)}function mu(m){return Un(m)&&Rn(m)==a}function bu(m,E,M,Y,Ge){return m===E?!0:m==null||E==null||!Un(m)&&!Un(E)?m!==m&&E!==E:Nb(m,E,M,Y,bu,Ge)}function Nb(m,E,M,Y,Ge,oe){var it=oa(m),ft=oa(E),At=it?c:yi(m),Ze=ft?c:yi(E);At=At==a?y:At,Ze=Ze==a?y:Ze;var ts=At==y,Cs=Ze==y,Rt=At==Ze;if(Rt&&Mc(m)){if(!Mc(E))return!1;it=!0,ts=!1}if(Rt&&!ts)return oe||(oe=new wi),it||Cu(m)?vu(m,E,M,Y,Ge,oe):Tb(m,E,At,M,Y,Ge,oe);if(!(M&r)){var ps=ts&&Ls.call(m,"__wrapped__"),gs=Cs&&Ls.call(E,"__wrapped__");if(ps||gs){var mi=ps?m.value():m,ti=gs?E.value():E;return oe||(oe=new wi),Ge(mi,ti,M,Y,oe)}}return Rt?(oe||(oe=new wi),Pb(m,E,M,Y,Ge,oe)):!1}function _b(m){if(!_u(m)||Db(m))return!1;var E=Au(m)?Wm:be;return E.test(Wi(m))}function Cb(m){return Un(m)&&Nu(m.length)&&!!te[Rn(m)]}function Sb(m){if(!kb(m))return Gm(m);var E=[];for(var M in Object(m))Ls.call(m,M)&&M!="constructor"&&E.push(M);return E}function vu(m,E,M,Y,Ge,oe){var it=M&r,ft=m.length,At=E.length;if(ft!=At&&!(it&&At>ft))return!1;var Ze=oe.get(m);if(Ze&&oe.get(E))return Ze==E;var ts=-1,Cs=!0,Rt=M&n?new ia:void 0;for(oe.set(m,E),oe.set(E,m);++ts<ft;){var ps=m[ts],gs=E[ts];if(Y)var mi=it?Y(gs,ps,ts,E,m,oe):Y(ps,gs,ts,m,E,oe);if(mi!==void 0){if(mi)continue;Cs=!1;break}if(Rt){if(!km(E,function(ti,Vi){if(!Um(Rt,Vi)&&(ps===ti||Ge(ps,ti,M,Y,oe)))return Rt.push(Vi)})){Cs=!1;break}}else if(!(ps===gs||Ge(ps,gs,M,Y,oe))){Cs=!1;break}}return oe.delete(m),oe.delete(E),Cs}function Tb(m,E,M,Y,Ge,oe,it){switch(M){case G:if(m.byteLength!=E.byteLength||m.byteOffset!=E.byteOffset)return!1;m=m.buffer,E=E.buffer;case j:return!(m.byteLength!=E.byteLength||!oe(new gu(m),new gu(E)));case h:case d:case v:return Eu(+m,+E);case p:return m.name==E.name&&m.message==E.message;case C:case P:return m==E+"";case w:var ft=zm;case T:var At=Y&r;if(ft||(ft=qm),m.size!=E.size&&!At)return!1;var Ze=it.get(m);if(Ze)return Ze==E;Y|=n,it.set(m,E);var ts=vu(ft(m),ft(E),Y,Ge,oe,it);return it.delete(m),ts;case x:if($c)return $c.call(m)==$c.call(E)}return!1}function Pb(m,E,M,Y,Ge,oe){var it=M&r,ft=Iu(m),At=ft.length,Ze=Iu(E),ts=Ze.length;if(At!=ts&&!it)return!1;for(var Cs=At;Cs--;){var Rt=ft[Cs];if(!(it?Rt in E:Ls.call(E,Rt)))return!1}var ps=oe.get(m);if(ps&&oe.get(E))return ps==E;var gs=!0;oe.set(m,E),oe.set(E,m);for(var mi=it;++Cs<At;){Rt=ft[Cs];var ti=m[Rt],Vi=E[Rt];if(Y)var Su=it?Y(Vi,ti,Rt,E,m,oe):Y(ti,Vi,Rt,m,E,oe);if(!(Su===void 0?ti===Vi||Ge(ti,Vi,M,Y,oe):Su)){gs=!1;break}mi||(mi=Rt=="constructor")}if(gs&&!mi){var aa=m.constructor,ca=E.constructor;aa!=ca&&"constructor"in m&&"constructor"in E&&!(typeof aa=="function"&&aa instanceof aa&&typeof ca=="function"&&ca instanceof ca)&&(gs=!1)}return oe.delete(m),oe.delete(E),gs}function Iu(m){return Ab(m,zb,Mb)}function na(m,E){var M=m.__data__;return xb(E)?M[typeof E=="string"?"string":"hash"]:M.map}function Ar(m,E){var M=Lm(m,E);return _b(M)?M:void 0}function $b(m){var E=Ls.call(m,qi),M=m[qi];try{m[qi]=void 0;var Y=!0}catch{}var Ge=du.call(m);return Y&&(E?m[qi]=M:delete m[qi]),Ge}var Mb=wu?function(m){return m==null?[]:(m=Object(m),Dn(wu(m),function(E){return fu.call(m,E)}))}:Fb,yi=Rn;(Cc&&yi(new Cc(new ArrayBuffer(1)))!=G||kn&&yi(new kn)!=w||Sc&&yi(Sc.resolve())!=A||Tc&&yi(new Tc)!=T||Pc&&yi(new Pc)!=q)&&(yi=function(m){var E=Rn(m),M=E==y?m.constructor:void 0,Y=M?Wi(M):"";if(Y)switch(Y){case Ym:return G;case Qm:return w;case Jm:return A;case Zm:return T;case Xm:return q}return E});function Ob(m,E){return E=E??o,!!E&&(typeof m=="number"||de.test(m))&&m>-1&&m%1==0&&m<E}function xb(m){var E=typeof m;return E=="string"||E=="number"||E=="symbol"||E=="boolean"?m!=="__proto__":m===null}function Db(m){return!!uu&&uu in m}function kb(m){var E=m&&m.constructor,M=typeof E=="function"&&E.prototype||ta;return m===M}function jb(m){return du.call(m)}function Wi(m){if(m!=null){try{return hu.call(m)}catch{}try{return m+""}catch{}}return""}function Eu(m,E){return m===E||m!==m&&E!==E}var Rb=mu(function(){return arguments}())?mu:function(m){return Un(m)&&Ls.call(m,"callee")&&!fu.call(m,"callee")},oa=Array.isArray;function Ub(m){return m!=null&&Nu(m.length)&&!Au(m)}var Mc=Km||qb;function Lb(m,E){return bu(m,E)}function Au(m){if(!_u(m))return!1;var E=Rn(m);return E==f||E==g||E==l||E==_}function Nu(m){return typeof m=="number"&&m>-1&&m%1==0&&m<=o}function _u(m){var E=typeof m;return m!=null&&(E=="object"||E=="function")}function Un(m){return m!=null&&typeof m=="object"}var Cu=Us?Rm(Us):Cb;function zb(m){return Ub(m)?Eb(m):Sb(m)}function Fb(){return[]}function qb(){return!1}s.exports=Lb})(Ya,Ya.exports);var vE=Ya.exports;const IE=N.getDefaultExportFromCjs(vE),ww="wc",yw=2,Rl="core",Js=`${ww}@2:${Rl}:`,EE={logger:"error"},AE={database:":memory:"},NE="crypto",_d="client_ed25519_seed",_E=u.cjs.ONE_DAY,CE="keychain",SE="0.3",TE="messages",PE="0.3",Cd=u.cjs.SIX_HOURS,$E="publisher",mw="irn",ME="error",bw="wss://relay.walletconnect.org",OE="relayer",It={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"},xE="_subscription",fs={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},DE=.1,Ul="2.19.0",Qe={link_mode:"link_mode",relay:"relay"},kE="0.3",jE="WALLETCONNECT_CLIENT_ID",Sd="WALLETCONNECT_LINK_MODE_APPS",ns={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},RE="subscription",UE="0.3",LE=u.cjs.FIVE_SECONDS*1e3,zE="pairing",FE="0.3",Wn={wc_pairingDelete:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:u.cjs.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:u.cjs.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:0},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:0}}},tr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ss={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},qE="history",BE="0.3",HE="expirer",bs={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},WE="0.3",VE="verify-api",KE="https://verify.walletconnect.com",vw="https://verify.walletconnect.org",wo=vw,GE=`${wo}/v3`,YE=[KE,vw],QE="echo",JE="https://echo.walletconnect.com",Gs={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"},ci={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"},Ts={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"},Ki={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"},Gi={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"},Vn={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"},ZE=.1,XE="event-client",eA=86400,tA="https://pulse.walletconnect.org/batch";function sA(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 d(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,v=0,b=0,y=g.length;b!==y&&g[b]===0;)b++,w++;for(var A=(y-b)*h+1>>>0,_=new Uint8Array(A);b!==y;){for(var C=g[b],T=0,P=A-1;(C!==0||T<v)&&P!==-1;P--,T++)C+=256*_[P]>>>0,_[P]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");v=T,b++}for(var x=A-v;x!==A&&_[x]===0;)x++;for(var $=c.repeat(w);x<A;++x)$+=s.charAt(_[x]);return $}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var v=0,b=0;g[w]===c;)v++,w++;for(var y=(g.length-w)*l+1>>>0,A=new Uint8Array(y);g[w];){var _=t[g.charCodeAt(w)];if(_===255)return;for(var C=0,T=y-1;(_!==0||C<b)&&T!==-1;T--,C++)_+=a*A[T]>>>0,A[T]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");b=C,w++}if(g[w]!==" "){for(var P=y-b;P!==y&&A[P]===0;)P++;for(var x=new Uint8Array(v+(y-P)),$=v;P!==y;)x[$++]=A[P++];return x}}}function f(g){var w=p(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var iA=sA,rA=iA;const Iw=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")},nA=s=>new TextEncoder().encode(s),oA=s=>new TextDecoder().decode(s);let aA=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")}},cA=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 Ew(this,e)}},lA=class{constructor(e){this.decoders=e}or(e){return Ew(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 Ew=(s,e)=>new lA({...s.decoders||{[s.prefix]:s},...e.decoders||{[e.prefix]:e}});let hA=class{constructor(e,t,i,r){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=r,this.encoder=new aA(e,t,i),this.decoder=new cA(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const dc=({name:s,prefix:e,encode:t,decode:i})=>new hA(s,e,t,i),Wo=({prefix:s,name:e,alphabet:t})=>{const{encode:i,decode:r}=rA(t,e);return dc({prefix:s,name:e,encode:i,decode:n=>Iw(r(n))})},uA=(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 d=r[s[h]];if(d===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|d,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},dA=(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},kt=({name:s,prefix:e,bitsPerChar:t,alphabet:i})=>dc({prefix:e,name:s,encode(r){return dA(r,i,t)},decode(r){return uA(r,i,t,s)}}),pA=dc({prefix:"\0",name:"identity",encode:s=>oA(s),decode:s=>nA(s)});var gA=Object.freeze({__proto__:null,identity:pA});const fA=kt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wA=Object.freeze({__proto__:null,base2:fA});const yA=kt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var mA=Object.freeze({__proto__:null,base8:yA});const bA=Wo({prefix:"9",name:"base10",alphabet:"0123456789"});var vA=Object.freeze({__proto__:null,base10:bA});const IA=kt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),EA=kt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var AA=Object.freeze({__proto__:null,base16:IA,base16upper:EA});const NA=kt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),_A=kt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),CA=kt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),SA=kt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),TA=kt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),PA=kt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),$A=kt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),MA=kt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),OA=kt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xA=Object.freeze({__proto__:null,base32:NA,base32upper:_A,base32pad:CA,base32padupper:SA,base32hex:TA,base32hexupper:PA,base32hexpad:$A,base32hexpadupper:MA,base32z:OA});const DA=Wo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),kA=Wo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var jA=Object.freeze({__proto__:null,base36:DA,base36upper:kA});const RA=Wo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),UA=Wo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var LA=Object.freeze({__proto__:null,base58btc:RA,base58flickr:UA});const zA=kt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),FA=kt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),qA=kt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),BA=kt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var HA=Object.freeze({__proto__:null,base64:zA,base64pad:FA,base64url:qA,base64urlpad:BA});const Aw=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),WA=Aw.reduce((s,e,t)=>(s[t]=e,s),[]),VA=Aw.reduce((s,e,t)=>(s[e.codePointAt(0)]=t,s),[]);function KA(s){return s.reduce((e,t)=>(e+=WA[t],e),"")}function GA(s){const e=[];for(const t of s){const i=VA[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const YA=dc({prefix:"🚀",name:"base256emoji",encode:KA,decode:GA});var QA=Object.freeze({__proto__:null,base256emoji:YA}),JA=Nw,Td=128,ZA=-128,XA=Math.pow(2,31);function Nw(s,e,t){e=e||[],t=t||0;for(var i=t;s>=XA;)e[t++]=s&255|Td,s/=128;for(;s&ZA;)e[t++]=s&255|Td,s>>>=7;return e[t]=s|0,Nw.bytes=t-i+1,e}var eN=Ll,tN=128,Pd=127;function Ll(s,i){var t=0,i=i||0,r=0,n=i,o,a=s.length;do{if(n>=a)throw Ll.bytes=0,new RangeError("Could not decode varint");o=s[n++],t+=r<28?(o&Pd)<<r:(o&Pd)*Math.pow(2,r),r+=7}while(o>=tN);return Ll.bytes=n-i,t}var sN=Math.pow(2,7),iN=Math.pow(2,14),rN=Math.pow(2,21),nN=Math.pow(2,28),oN=Math.pow(2,35),aN=Math.pow(2,42),cN=Math.pow(2,49),lN=Math.pow(2,56),hN=Math.pow(2,63),uN=function(s){return s<sN?1:s<iN?2:s<rN?3:s<nN?4:s<oN?5:s<aN?6:s<cN?7:s<lN?8:s<hN?9:10},dN={encode:JA,decode:eN,encodingLength:uN},_w=dN;const $d=(s,e,t=0)=>(_w.encode(s,e,t),e),Md=s=>_w.encodingLength(s),zl=(s,e)=>{const t=e.byteLength,i=Md(s),r=i+Md(t),n=new Uint8Array(r+t);return $d(s,n,0),$d(t,n,i),n.set(e,r),new pN(s,t,e,n)};let pN=class{constructor(e,t,i,r){this.code=e,this.size=t,this.digest=i,this.bytes=r}};const Cw=({name:s,code:e,encode:t})=>new gN(s,e,t);let gN=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?zl(this.code,t):t.then(i=>zl(this.code,i))}else throw Error("Unknown type, must be binary type")}};const Sw=s=>async e=>new Uint8Array(await crypto.subtle.digest(s,e)),fN=Cw({name:"sha2-256",code:18,encode:Sw("SHA-256")}),wN=Cw({name:"sha2-512",code:19,encode:Sw("SHA-512")});var yN=Object.freeze({__proto__:null,sha256:fN,sha512:wN});const Tw=0,mN="identity",Pw=Iw,bN=s=>zl(Tw,Pw(s)),vN={code:Tw,name:mN,encode:Pw,digest:bN};var IN=Object.freeze({__proto__:null,identity:vN});new TextEncoder,new TextDecoder;const Od={...gA,...wA,...mA,...vA,...AA,...xA,...jA,...LA,...HA,...QA};({...yN,...IN});function EN(s=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(s):new Uint8Array(s)}function $w(s,e,t,i){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:i}}}const xd=$w("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),Bc=$w("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=EN(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),AN={utf8:xd,"utf-8":xd,hex:Od.base16,latin1:Bc,ascii:Bc,binary:Bc,...Od};function NN(s,e="utf8"){const t=AN[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 _N=Object.defineProperty,CN=(s,e,t)=>e in s?_N(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Fs=(s,e,t)=>CN(s,typeof e!="symbol"?e+"":e,t);let SN=class{constructor(e,t){this.core=e,this.logger=t,Fs(this,"keychain",new Map),Fs(this,"name",CE),Fs(this,"version",SE),Fs(this,"initialized",!1),Fs(this,"storagePrefix",Js),Fs(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Fs(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Fs(this,"set",async(i,r)=>{this.isInitialized(),this.keychain.set(i,r),await this.persist()}),Fs(this,"get",i=>{this.isInitialized();const r=this.keychain.get(i);if(typeof r>"u"){const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return r}),Fs(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,zf(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ff(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var TN=Object.defineProperty,PN=(s,e,t)=>e in s?TN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ct=(s,e,t)=>PN(s,typeof e!="symbol"?e+"":e,t);let $N=class{constructor(e,t,i){this.core=e,this.logger=t,Ct(this,"name",NE),Ct(this,"keychain"),Ct(this,"randomSessionIdentifier",jl()),Ct(this,"initialized",!1),Ct(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ct(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ct(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=u.Po(r);return u.Qe(n.publicKey)}),Ct(this,"generateKeyPair",()=>{this.isInitialized();const r=N1();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ct(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=u.Po(n),a=this.randomSessionIdentifier,c=_E;return await u.Qo(a,r,c,o)}),Ct(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=_1(a,n);return this.setSymKey(c,o)}),Ct(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||ka(r);return await this.keychain.set(o,r),o}),Ct(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ct(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ct(this,"encode",async(r,n,o)=>{this.isInitialized();const a=pw(o),c=u.safeJsonStringify(n);if(wd(a))return T1(c,o==null?void 0:o.encoding);if(fd(a)){const p=a.senderPublicKey,f=a.receiverPublicKey;r=await this.generateSharedKey(p,f)}const l=this.getSymKey(r),{type:h,senderPublicKey:d}=a;return C1({type:h,symKey:l,message:c,senderPublicKey:d,encoding:o==null?void 0:o.encoding})}),Ct(this,"decode",async(r,n,o)=>{this.isInitialized();const a=$1(n,o);if(wd(a)){const c=P1(n,o==null?void 0:o.encoding);return u.safeJsonParse(c)}if(fd(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=S1({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return u.safeJsonParse(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ct(this,"getPayloadType",(r,n=Mi)=>{const o=To({encoded:r,encoding:n});return hr(o.type)}),Ct(this,"getPayloadSenderPublicKey",(r,n=Mi)=>{const o=To({encoded:r,encoding:n});return o.senderPublicKey?u.toString(o.senderPublicKey,qt):void 0}),this.core=e,this.logger=u.E(t,this.name),this.keychain=i||new SN(this.core,this.logger)}get context(){return u.y(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(_d)}catch{e=jl(),await this.keychain.set(_d,e)}return NN(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var MN=Object.defineProperty,ON=(s,e,t)=>e in s?MN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,qs=(s,e,t)=>ON(s,typeof e!="symbol"?e+"":e,t);let xN=class extends Iv{constructor(e,t){super(e,t),this.logger=e,this.core=t,qs(this,"messages",new Map),qs(this,"name",TE),qs(this,"version",PE),qs(this,"initialized",!1),qs(this,"storagePrefix",Js),qs(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}}}),qs(this,"set",async(i,r)=>{this.isInitialized();const n=ui(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}),qs(this,"get",i=>{this.isInitialized();let r=this.messages.get(i);return typeof r>"u"&&(r={}),r}),qs(this,"has",(i,r)=>{this.isInitialized();const n=this.get(i),o=ui(r);return typeof n[o]<"u"}),qs(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()}),this.logger=u.E(e,this.name),this.core=t}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,zf(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ff(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var DN=Object.defineProperty,kN=Object.defineProperties,jN=Object.getOwnPropertyDescriptors,Dd=Object.getOwnPropertySymbols,RN=Object.prototype.hasOwnProperty,UN=Object.prototype.propertyIsEnumerable,Fl=(s,e,t)=>e in s?DN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ga=(s,e)=>{for(var t in e||(e={}))RN.call(e,t)&&Fl(s,t,e[t]);if(Dd)for(var t of Dd(e))UN.call(e,t)&&Fl(s,t,e[t]);return s},Hc=(s,e)=>kN(s,jN(e)),Ps=(s,e,t)=>Fl(s,typeof e!="symbol"?e+"":e,t);let LN=class extends Ev{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Ps(this,"events",new u.eventsExports.EventEmitter),Ps(this,"name",$E),Ps(this,"queue",new Map),Ps(this,"publishTimeout",u.cjs.toMiliseconds(u.cjs.ONE_MINUTE)),Ps(this,"initialPublishTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),Ps(this,"needsTransportRestart",!1),Ps(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)||Cd,c=Ka(n),l=(n==null?void 0:n.prompt)||!1,h=(n==null?void 0:n.tag)||0,d=(n==null?void 0:n.id)||u.getBigIntRpcId().toString(),p={topic:i,message:r,opts:{ttl:a,relay:c,prompt:l,tag:h,id:d,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},f=`Failed to publish payload, please try again. id:${d} tag:${h}`;try{const g=new Promise(async w=>{const v=({id:y})=>{p.opts.id===y&&(this.removeRequestFromQueue(y),this.relayer.events.removeListener(It.publish,v),w(p))};this.relayer.events.on(It.publish,v);const b=$i(new Promise((y,A)=>{this.rpcPublish({topic:i,message:r,ttl:a,prompt:l,tag:h,id:d,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(y).catch(_=>{this.logger.warn(_,_==null?void 0:_.message),A(_)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${h}`);try{await b,this.events.removeListener(It.publish,v)}catch(y){this.queue.set(d,Hc(ga({},p),{attempt:1})),this.logger.warn(y,y==null?void 0:y.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:i,message:r,opts:n}}),await $i(g,this.publishTimeout,f)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(d)}}),Ps(this,"on",(i,r)=>{this.events.on(i,r)}),Ps(this,"once",(i,r)=>{this.events.once(i,r)}),Ps(this,"off",(i,r)=>{this.events.off(i,r)}),Ps(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.relayer=e,this.logger=u.E(t,this.name),this.registerEventListeners()}get context(){return u.y(this.logger)}async rpcPublish(e){var t,i,r,n;const{topic:o,message:a,ttl:c=Cd,prompt:l,tag:h,id:d,attestation:p,tvf:f}=e,g={method:ao(Ka().protocol).publish,params:ga({topic:o,message:a,ttl:c,prompt:l,tag:h,attestation:p},f),id:d};Wt((t=g.params)==null?void 0:t.prompt)&&((i=g.params)==null||delete i.prompt),Wt((r=g.params)==null?void 0:r.tag)&&((n=g.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const w=await this.relayer.request(g);return this.relayer.events.emit(It.publish,e),this.logger.debug("Successfully Published Payload"),w}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,Hc(ga({},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(Hc(ga({},e),{topic:r,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(u.r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(It.connection_stalled);return}this.checkQueue()}),this.relayer.on(It.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}};var zN=Object.defineProperty,FN=(s,e,t)=>e in s?zN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Sr=(s,e,t)=>FN(s,typeof e!="symbol"?e+"":e,t);let qN=class{constructor(){Sr(this,"map",new Map),Sr(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),Sr(this,"get",e=>this.map.get(e)||[]),Sr(this,"exists",(e,t)=>this.get(e).includes(t)),Sr(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)}),Sr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}};var BN=Object.defineProperty,HN=Object.defineProperties,WN=Object.getOwnPropertyDescriptors,kd=Object.getOwnPropertySymbols,VN=Object.prototype.hasOwnProperty,KN=Object.prototype.propertyIsEnumerable,ql=(s,e,t)=>e in s?BN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Kn=(s,e)=>{for(var t in e||(e={}))VN.call(e,t)&&ql(s,t,e[t]);if(kd)for(var t of kd(e))KN.call(e,t)&&ql(s,t,e[t]);return s},Wc=(s,e)=>HN(s,WN(e)),ke=(s,e,t)=>ql(s,typeof e!="symbol"?e+"":e,t);let GN=class extends _v{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ke(this,"subscriptions",new Map),ke(this,"topicMap",new qN),ke(this,"events",new u.eventsExports.EventEmitter),ke(this,"name",RE),ke(this,"version",UE),ke(this,"pending",new Map),ke(this,"cached",[]),ke(this,"initialized",!1),ke(this,"pendingSubscriptionWatchLabel","pending_sub_watch_label"),ke(this,"pollingInterval",20),ke(this,"storagePrefix",Js),ke(this,"subscribeTimeout",u.cjs.toMiliseconds(u.cjs.ONE_MINUTE)),ke(this,"initialSubscribeTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),ke(this,"clientId"),ke(this,"batchSubscribeTopicsLimit",500),ke(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ke(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=Ka(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}}),ke(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)}),ke(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 u.cjs.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)>=LE&&(clearInterval(c),a.stop(r),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)}),ke(this,"on",(i,r)=>{this.events.on(i,r)}),ke(this,"once",(i,r)=>{this.events.once(i,r)}),ke(this,"off",(i,r)=>{this.events.off(i,r)}),ke(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),ke(this,"start",async()=>{await this.onConnect()}),ke(this,"stop",async()=>{await this.onDisconnect()}),ke(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ke(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)}),ke(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(u.r.pulse,async()=>{await this.checkPending()}),this.events.on(ns.created,async i=>{const r=ns.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()}),this.events.on(ns.deleted,async i=>{const r=ns.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()})}),this.relayer=e,this.logger=u.E(t,this.name),this.clientId=""}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let 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=Ka(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=je("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)===Qe.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:ao(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)===Qe.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(h=>this.logger.warn(h))},u.cjs.toMiliseconds(u.cjs.ONE_SECOND)),a;const c=new Promise(async h=>{const d=p=>{p.topic===e&&(this.events.removeListener(ns.created,d),h(p.id))};this.events.on(ns.created,d);try{const p=await $i(new Promise((f,g)=>{this.relayer.request(n).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),g(w)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(ns.created,d),h(p)}catch{}}),l=await $i(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(It.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:ao(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 $i(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(It.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:ao(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 $i(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(It.connection_stalled)}return r}rpcUnsubscribe(e,t,i){const r={method:ao(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,Wc(Kn({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Kn({},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,Kn({},t)),this.topicMap.set(t.topic,e),this.events.emit(ns.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}=U("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(ns.deleted,Wc(Kn({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ns.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(ns.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=U("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=>Wc(Kn({},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 U0(u.cjs.toMiliseconds(u.cjs.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=U("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 ui(e+await this.getClientId())}};var YN=Object.defineProperty,jd=Object.getOwnPropertySymbols,QN=Object.prototype.hasOwnProperty,JN=Object.prototype.propertyIsEnumerable,Bl=(s,e,t)=>e in s?YN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Rd=(s,e)=>{for(var t in e||(e={}))QN.call(e,t)&&Bl(s,t,e[t]);if(jd)for(var t of jd(e))JN.call(e,t)&&Bl(s,t,e[t]);return s},Ee=(s,e,t)=>Bl(s,typeof e!="symbol"?e+"":e,t);let ZN=class extends Av{constructor(e){super(e),Ee(this,"protocol","wc"),Ee(this,"version",2),Ee(this,"core"),Ee(this,"logger"),Ee(this,"events",new u.eventsExports.EventEmitter),Ee(this,"provider"),Ee(this,"messages"),Ee(this,"subscriber"),Ee(this,"publisher"),Ee(this,"name",OE),Ee(this,"transportExplicitlyClosed",!1),Ee(this,"initialized",!1),Ee(this,"connectionAttemptInProgress",!1),Ee(this,"relayUrl"),Ee(this,"projectId"),Ee(this,"packageName"),Ee(this,"bundleId"),Ee(this,"hasExperiencedNetworkDisruption",!1),Ee(this,"pingTimeout"),Ee(this,"heartBeatTimeout",u.cjs.toMiliseconds(u.cjs.THIRTY_SECONDS+u.cjs.FIVE_SECONDS)),Ee(this,"reconnectTimeout"),Ee(this,"connectPromise"),Ee(this,"reconnectInProgress",!1),Ee(this,"requestsInFlight",[]),Ee(this,"connectTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),Ee(this,"request",async t=>{var i,r;this.logger.debug("Publishing Request Payload");const n=t.id||u.getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(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}}),Ee(this,"resetPingTimeout",()=>{if(Wa())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)}}),Ee(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),Ee(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(It.connect)}),Ee(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ee(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(It.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ee(this,"registerProviderListeners",()=>{this.provider.on(fs.payload,this.onPayloadHandler),this.provider.on(fs.connect,this.onConnectHandler),this.provider.on(fs.disconnect,this.onDisconnectHandler),this.provider.on(fs.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?u.E(e.logger,this.name):u.Ot(u.k({level:e.logger||ME})),this.messages=new xN(this.logger,e.core),this.subscriber=new GN(this,this.logger),this.publisher=new LN(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||bw,this.projectId=e.projectId,A0()?this.packageName=qu():N0()&&(this.bundleId=qu()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return u.y(this.logger)}get connected(){var e,t,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:Qe.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(ns.created,l),c())};return await Promise.all([new Promise(h=>{c=h,this.subscriber.on(ns.created,l)}),new Promise(async(h,d)=>{a=await this.subscriber.subscribe(e,Rd({internal:{throwOnFailedPublish:o}},t)).catch(p=>{o&&d(p)})||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 $i(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 Nd())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=dt(u.cjs.FIVE_MINUTES),n={topic:i,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(It.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(fs.disconnect,n),await $i(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(fs.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(fs.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(fs.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,u.cjs.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,r,n;if(Wa())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 u.o(new u.f(T0({sdkVersion:Ul,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}),u.isJsonRpcRequest(e)){if(!e.method.endsWith(xE))return;const t=e.params,{topic:i,message:r,publishedAt:n,attestation:o}=t.data,a={topic:i,message:r,publishedAt:n,transportType:Qe.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Rd({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else u.isJsonRpcResponse(e)&&this.events.emit(It.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(It.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=u.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(fs.payload,this.onPayloadHandler),this.provider.off(fs.connect,this.onConnectHandler),this.provider.off(fs.disconnect,this.onDisconnectHandler),this.provider.off(fs.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Nd();yE(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(It.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},u.cjs.toMiliseconds(DE)))))}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}};var XN=Object.defineProperty,Ud=Object.getOwnPropertySymbols,e_=Object.prototype.hasOwnProperty,t_=Object.prototype.propertyIsEnumerable,Hl=(s,e,t)=>e in s?XN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ld=(s,e)=>{for(var t in e||(e={}))e_.call(e,t)&&Hl(s,t,e[t]);if(Ud)for(var t of Ud(e))t_.call(e,t)&&Hl(s,t,e[t]);return s},Kt=(s,e,t)=>Hl(s,typeof e!="symbol"?e+"":e,t);let yr=class extends Nv{constructor(e,t,i,r=Js,n=void 0){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,Kt(this,"map",new Map),Kt(this,"version",kE),Kt(this,"cached",[]),Kt(this,"initialized",!1),Kt(this,"getKey"),Kt(this,"storagePrefix",Js),Kt(this,"recentlyDeleted",[]),Kt(this,"recentlyDeletedLimit",200),Kt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Wt(o)?this.map.set(this.getKey(o),o):G1(o)?this.map.set(o.id,o):Y1(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Kt(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())}),Kt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Kt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>IE(a[c],o[c]))):this.values)),Kt(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=Ld(Ld({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Kt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=u.E(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=U("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:i}=U("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}=U("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}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var s_=Object.defineProperty,i_=(s,e,t)=>e in s?s_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ge=(s,e,t)=>i_(s,typeof e!="symbol"?e+"":e,t);let r_=class{constructor(e,t){this.core=e,this.logger=t,ge(this,"name",zE),ge(this,"version",FE),ge(this,"events",new u.Nt),ge(this,"pairings"),ge(this,"initialized",!1),ge(this,"storagePrefix",Js),ge(this,"ignoredPayloadTypes",[pi]),ge(this,"registeredMethods",[]),ge(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ge(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),ge(this,"create",async i=>{this.isInitialized();const r=jl(),n=await this.core.crypto.setSymKey(r),o=dt(u.cjs.FIVE_MINUTES),a={protocol:mw},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},l=md({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(tr.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}}),ge(this,"pair",async i=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[Gs.pairing_started]}});this.isValidPair(i,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=yd(i.uri);r.props.properties.topic=n,r.addTrace(Gs.pairing_uri_validation_success),r.addTrace(Gs.pairing_uri_not_expired);let h;if(this.pairings.keys.includes(n)){if(h=this.pairings.get(n),r.addTrace(Gs.existing_pairing),h.active)throw r.setError(ci.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(Gs.pairing_not_expired)}const d=c||dt(u.cjs.FIVE_MINUTES),p={topic:n,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(n,d),await this.pairings.set(n,p),r.addTrace(Gs.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(tr.create,p),r.addTrace(Gs.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(Gs.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(ci.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(f){throw r.setError(ci.subscribe_pairing_topic_failure),f}return r.addTrace(Gs.subscribe_pairing_topic_success),p}),ge(this,"activate",async({topic:i})=>{this.isInitialized();const r=dt(u.cjs.FIVE_MINUTES);this.core.expirer.set(i,r),await this.pairings.update(i,{active:!0,expiry:r})}),ge(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}=Ji();this.events.once(Pe("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),ge(this,"updateExpiry",async({topic:i,expiry:r})=>{this.isInitialized(),await this.pairings.update(i,{expiry:r})}),ge(this,"updateMetadata",async({topic:i,metadata:r})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:r})}),ge(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ge(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",je("USER_DISCONNECTED")),await this.deletePairing(r))}),ge(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(r);return md({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),ge(this,"sendRequest",async(i,r,n)=>{const o=u.formatJsonRpcRequest(r,n),a=await this.core.crypto.encode(i,o),c=Wn[r].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),ge(this,"sendResult",async(i,r,n)=>{const o=u.formatJsonRpcResult(i,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,i)).request.method,l=Wn[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),ge(this,"sendError",async(i,r,n)=>{const o=u.formatJsonRpcError(i,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,i)).request.method,l=Wn[c]?Wn[c].res:Wn.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),ge(this,"deletePairing",async(i,r)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,je("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),r?Promise.resolve():this.core.expirer.del(i)])}),ge(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(r=>Ci(r.expiry));await Promise.all(i.map(r=>this.deletePairing(r.topic)))}),ge(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)}}),ge(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)}}),ge(this,"onPairingPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(tr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),ge(this,"onPairingPingResponse",(i,r)=>{const{id:n}=r;setTimeout(()=>{u.isJsonRpcResult(r)?this.events.emit(Pe("pairing_ping",n),{}):u.isJsonRpcError(r)&&this.events.emit(Pe("pairing_ping",n),{error:r.error})},500)}),ge(this,"onPairingDeleteRequest",async(i,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(tr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),ge(this,"onUnknownRpcMethodRequest",async(i,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=je("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)}}),ge(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(je("WC_METHOD_UNSUPPORTED",i))}),ge(this,"isValidPair",(i,r)=>{var n;if(!Zt(i)){const{message:a}=U("MISSING_OR_INVALID",`pair() params: ${i}`);throw r.setError(ci.malformed_pairing_uri),new Error(a)}if(!K1(i.uri)){const{message:a}=U("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw r.setError(ci.malformed_pairing_uri),new Error(a)}const o=yd(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(ci.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(ci.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&u.cjs.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(ci.pairing_expired);const{message:a}=U("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ge(this,"isValidPing",async i=>{if(!Zt(i)){const{message:n}=U("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),ge(this,"isValidDisconnect",async i=>{if(!Zt(i)){const{message:n}=U("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),ge(this,"isValidPairingTopic",async i=>{if(!nt(i,!1)){const{message:r}=U("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(r)}if(!this.pairings.keys.includes(i)){const{message:r}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(r)}if(Ci(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:r}=U("EXPIRED",`pairing topic: ${i}`);throw new Error(r)}}),this.core=e,this.logger=u.E(t,this.name),this.pairings=new yr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return u.y(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(It.message,async e=>{const{topic:t,message:i,transportType:r}=e;if(!this.pairings.keys.includes(t)||r===Qe.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const n=await this.core.crypto.decode(t,i);try{u.isJsonRpcRequest(n)?(this.core.history.set(t,n),this.onRelayEventRequest({topic:t,payload:n})):u.isJsonRpcResponse(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(bs.expired,async e=>{const{topic:t}=Bf(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(tr.expire,{topic:t}))})}};var n_=Object.defineProperty,o_=(s,e,t)=>e in s?n_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,St=(s,e,t)=>o_(s,typeof e!="symbol"?e+"":e,t);let a_=class extends vv{constructor(e,t){super(e,t),this.core=e,this.logger=t,St(this,"records",new Map),St(this,"events",new u.eventsExports.EventEmitter),St(this,"name",qE),St(this,"version",BE),St(this,"cached",[]),St(this,"initialized",!1),St(this,"storagePrefix",Js),St(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)}),St(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:dt(u.cjs.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ss.created,o)}),St(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=u.isJsonRpcError(i)?{error:i.error}:{result:i.result},this.records.set(r.id,r),this.persist(),this.events.emit(Ss.updated,r))}),St(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))),St(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(Ss.deleted,n)}}),this.persist()}),St(this,"exists",async(i,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===i:!1)),St(this,"on",(i,r)=>{this.events.on(i,r)}),St(this,"once",(i,r)=>{this.events.once(i,r)}),St(this,"off",(i,r)=>{this.events.off(i,r)}),St(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:u.formatJsonRpcRequest(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}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ss.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=U("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(Ss.created,e=>{const t=Ss.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ss.updated,e=>{const t=Ss.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ss.deleted,e=>{const t=Ss.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(u.r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{u.cjs.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Ss.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var c_=Object.defineProperty,l_=(s,e,t)=>e in s?c_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ut=(s,e,t)=>l_(s,typeof e!="symbol"?e+"":e,t);let h_=class extends Cv{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ut(this,"expirations",new Map),Ut(this,"events",new u.eventsExports.EventEmitter),Ut(this,"name",HE),Ut(this,"version",WE),Ut(this,"cached",[]),Ut(this,"initialized",!1),Ut(this,"storagePrefix",Js),Ut(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)}),Ut(this,"has",i=>{try{const r=this.formatTarget(i);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ut(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(bs.created,{target:n,expiration:o})}),Ut(this,"get",i=>{this.isInitialized();const r=this.formatTarget(i);return this.getExpiration(r)}),Ut(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(bs.deleted,{target:r,expiration:n})}}),Ut(this,"on",(i,r)=>{this.events.on(i,r)}),Ut(this,"once",(i,r)=>{this.events.once(i,r)}),Ut(this,"off",(i,r)=>{this.events.off(i,r)}),Ut(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return P0(e);if(typeof e=="number")return $0(e);const{message:t}=U("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(bs.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=U("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}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;u.cjs.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(bs.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(u.r.pulse,()=>this.checkExpirations()),this.events.on(bs.created,e=>{const t=bs.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(bs.expired,e=>{const t=bs.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(bs.deleted,e=>{const t=bs.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var u_=Object.defineProperty,d_=(s,e,t)=>e in s?u_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,at=(s,e,t)=>d_(s,typeof e!="symbol"?e+"":e,t);let p_=class extends Sv{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,at(this,"name",VE),at(this,"abortController"),at(this,"isDevEnv"),at(this,"verifyUrlV3",GE),at(this,"storagePrefix",Js),at(this,"version",yw),at(this,"publicKey"),at(this,"fetchPromise"),at(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&u.cjs.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),at(this,"register",async r=>{if(!zo()||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=u.getDocument_1(),h=this.startAbortTimer(u.cjs.ONE_SECOND*5),d=await new Promise((p,f)=>{const g=()=>{window.removeEventListener("message",v),l.body.removeChild(w),f("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const w=l.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",g,{signal:this.abortController.signal});const v=b=>{if(b.data&&typeof b.data=="string")try{const y=JSON.parse(b.data);if(y.type==="verify_attestation"){if(u.sn(y.attestation).payload.id!==o)return;clearInterval(h),l.body.removeChild(w),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",v),p(y.attestation===null?"":y.attestation)}}catch(y){this.logger.warn(y)}};l.body.appendChild(w),window.addEventListener("message",v,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),at(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(u.sn(n).payload.id!==a)return;const 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)}),at(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(u.cjs.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),at(this,"getVerifyUrl",r=>{let n=r||wo;return YE.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${wo}`),n=wo),n}),at(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(u.cjs.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),at(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),at(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),at(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")}}),at(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),at(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}),at(this,"validateAttestation",(r,n)=>{const o=D1(r,n.publicKey),a={hasExpired:u.cjs.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=u.E(t,this.name),this.abortController=new AbortController,this.isDevEnv=Oh(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return u.y(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),u.cjs.toMiliseconds(e))}};var g_=Object.defineProperty,f_=(s,e,t)=>e in s?g_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,zd=(s,e,t)=>f_(s,typeof e!="symbol"?e+"":e,t);let w_=class extends Tv{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,zd(this,"context",QE),zd(this,"registerDeviceToken",async i=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${JE}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=u.E(t,this.context)}};var y_=Object.defineProperty,Fd=Object.getOwnPropertySymbols,m_=Object.prototype.hasOwnProperty,b_=Object.prototype.propertyIsEnumerable,Wl=(s,e,t)=>e in s?y_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Gn=(s,e)=>{for(var t in e||(e={}))m_.call(e,t)&&Wl(s,t,e[t]);if(Fd)for(var t of Fd(e))b_.call(e,t)&&Wl(s,t,e[t]);return s},wt=(s,e,t)=>Wl(s,typeof e!="symbol"?e+"":e,t);let v_=class extends Pv{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,wt(this,"context",XE),wt(this,"storagePrefix",Js),wt(this,"storageVersion",ZE),wt(this,"events",new Map),wt(this,"shouldPersist",!1),wt(this,"init",async()=>{if(!Oh())try{const r={eventId:Hu(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Lf(this.core.relayer.protocol,this.core.relayer.version,Ul)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),wt(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=Hu(),h=this.core.projectId||"",d=Date.now(),p=Gn({eventId:l,timestamp:d,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,p),this.shouldPersist=!0),p}),wt(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 Gn(Gn({},a),this.setMethods(a.eventId))}),wt(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),wt(this,"setEventListeners",()=>{this.core.heartbeat.on(u.r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{u.cjs.fromMiliseconds(Date.now())-u.cjs.fromMiliseconds(r.timestamp)>eA&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),wt(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),wt(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)}),wt(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)}),wt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),wt(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,Gn(Gn({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),wt(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)}}),wt(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${tA}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ul}${n}`,{method:"POST",body:JSON.stringify(r)})}),wt(this,"getAppDomain",()=>Uf().url),this.logger=u.E(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 I_=Object.defineProperty,qd=Object.getOwnPropertySymbols,E_=Object.prototype.hasOwnProperty,A_=Object.prototype.propertyIsEnumerable,Vl=(s,e,t)=>e in s?I_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Bd=(s,e)=>{for(var t in e||(e={}))E_.call(e,t)&&Vl(s,t,e[t]);if(qd)for(var t of qd(e))A_.call(e,t)&&Vl(s,t,e[t]);return s},Be=(s,e,t)=>Vl(s,typeof e!="symbol"?e+"":e,t);let N_=class Mw extends wv{constructor(e){var t;super(e),Be(this,"protocol",ww),Be(this,"version",yw),Be(this,"name",Rl),Be(this,"relayUrl"),Be(this,"projectId"),Be(this,"customStoragePrefix"),Be(this,"events",new u.eventsExports.EventEmitter),Be(this,"logger"),Be(this,"heartbeat"),Be(this,"relayer"),Be(this,"crypto"),Be(this,"storage"),Be(this,"history"),Be(this,"expirer"),Be(this,"pairing"),Be(this,"verify"),Be(this,"echoClient"),Be(this,"linkModeSupportedApps"),Be(this,"eventClient"),Be(this,"initialized",!1),Be(this,"logChunkController"),Be(this,"on",(o,a)=>this.events.on(o,a)),Be(this,"once",(o,a)=>this.events.once(o,a)),Be(this,"off",(o,a)=>this.events.off(o,a)),Be(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),Be(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:c})=>{if(!o||!a)return;const l={topic:o,message:a,publishedAt:Date.now(),transportType:Qe.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:c})}),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||bw,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=u.k({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:EE.logger,name:Rl}),{logger:r,chunkLoggerController:n}=u.A({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=u.E(r,this.name),this.heartbeat=new u.i,this.crypto=new $N(this,this.logger,e==null?void 0:e.keychain),this.history=new a_(this,this.logger),this.expirer=new h_(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new u.h(Bd(Bd({},AE),e==null?void 0:e.storageOptions)),this.relayer=new ZN({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new r_(this,this.logger),this.verify=new p_(this,this.logger,this.storage),this.echoClient=new w_(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new v_(this,this.logger,e==null?void 0:e.telemetryEnabled)}static async init(e){const t=new Mw(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(jE,i),t}get context(){return u.y(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Sd,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(Sd)||[],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 __=N_;var C_=Object.defineProperty,S_=(s,e,t)=>e in s?C_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Hd=(s,e,t)=>S_(s,typeof e!="symbol"?e+"":e,t);let T_=class{constructor(e){this.opts=e,Hd(this,"protocol","wc"),Hd(this,"version",2)}},P_=class{constructor(e){this.client=e}};const Ow="wc",xw=2,Dw="client",Fh=`${Ow}@${xw}:${Dw}:`,Vc={name:Dw,logger:"error"},Wd="WALLETCONNECT_DEEPLINK_CHOICE",$_="proposal",Vd="Proposal expired",M_="session",Tr=u.cjs.SEVEN_DAYS,O_="engine",yt={wc_sessionPropose:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1104},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1106},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1112},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1114},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:u.cjs.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:u.cjs.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1119}}},Kc={min:u.cjs.FIVE_MINUTES,max:u.cjs.SEVEN_DAYS},Bs={idle:"IDLE",active:"ACTIVE"},Kd={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},x_="request",D_=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],k_="wc",j_="auth",R_="authKeys",U_="pairingTopics",L_="requests",pc=`${k_}@${1.5}:${j_}:`,ja=`${pc}:PUB_KEY`;var z_=Object.defineProperty,F_=Object.defineProperties,q_=Object.getOwnPropertyDescriptors,Gd=Object.getOwnPropertySymbols,B_=Object.prototype.hasOwnProperty,H_=Object.prototype.propertyIsEnumerable,Kl=(s,e,t)=>e in s?z_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Xe=(s,e)=>{for(var t in e||(e={}))B_.call(e,t)&&Kl(s,t,e[t]);if(Gd)for(var t of Gd(e))H_.call(e,t)&&Kl(s,t,e[t]);return s},Gt=(s,e)=>F_(s,q_(e)),D=(s,e,t)=>Kl(s,typeof e!="symbol"?e+"":e,t);let W_=class extends P_{constructor(e){super(e),D(this,"name",O_),D(this,"events",new u.Nt),D(this,"initialized",!1),D(this,"requestQueue",{state:Bs.idle,queue:[]}),D(this,"sessionRequestQueue",{state:Bs.idle,queue:[]}),D(this,"requestQueueDelay",u.cjs.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(yt)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},u.cjs.toMiliseconds(this.requestQueueDelay)))}),D(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Gt(Xe({},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,d=!1;try{if(l){const C=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=C.active}}catch(C){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),C}if(!l||!d){const{topic:C,uri:T}=await this.client.core.pairing.create();l=C,h=T}if(!l){const{message:C}=U("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(C)}const p=await this.client.core.crypto.generateKeyPair(),f=yt.wc_sessionPropose.req.ttl||u.cjs.FIVE_MINUTES,g=dt(f),w=Gt(Xe({requiredNamespaces:n,optionalNamespaces:o,relays:c??[{protocol:mw}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:l},a&&{sessionProperties:a}),{id:u.payloadId()}),v=Pe("session_connect",w.id),{reject:b,resolve:y,done:A}=Ji(f,Vd),_=({id:C})=>{C===w.id&&(this.client.events.off("proposal_expire",_),this.pendingSessions.delete(w.id),this.events.emit(v,{error:{message:Vd,code:0}}))};return this.client.events.on("proposal_expire",_),this.events.once(v,({error:C,session:T})=>{this.client.events.off("proposal_expire",_),C?b(C):T&&y(T)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:w,throwOnFailedPublish:!0,clientRpcId:w.id}),await this.setProposal(w.id,w),{uri:h,approval:A}}),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:[Ts.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(x){throw o.setError(Ki.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(Ki.proposal_not_found),x}try{await this.isValidApprove(t)}catch(x){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Ki.session_approve_namespace_validation_failure),x}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:h,sessionConfig:d}=t,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:g,requiredNamespaces:w,optionalNamespaces:v}=p;let b=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:f});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Ts.session_approve_started,properties:{topic:f,trace:[Ts.session_approve_started,Ts.session_namespaces_validation_success]}}));const y=await this.client.core.crypto.generateKeyPair(),A=g.publicKey,_=await this.client.core.crypto.generateSharedKey(y,A),C=Xe(Xe({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:y,metadata:this.client.metadata},expiry:dt(Tr)},h&&{sessionProperties:h}),d&&{sessionConfig:d}),T=Qe.relay;b.addTrace(Ts.subscribing_session_topic);try{await this.client.core.relayer.subscribe(_,{transportType:T})}catch(x){throw b.setError(Ki.subscribe_session_topic_failure),x}b.addTrace(Ts.subscribe_session_topic_success);const P=Gt(Xe({},C),{topic:_,requiredNamespaces:w,optionalNamespaces:v,pairingTopic:f,acknowledged:!1,self:C.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:y,transportType:Qe.relay});await this.client.session.set(_,P),b.addTrace(Ts.store_session);try{b.addTrace(Ts.publishing_session_settle),await this.sendRequest({topic:_,method:"wc_sessionSettle",params:C,throwOnFailedPublish:!0}).catch(x=>{throw b==null||b.setError(Ki.session_settle_publish_failure),x}),b.addTrace(Ts.session_settle_publish_success),b.addTrace(Ts.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:y},throwOnFailedPublish:!0}).catch(x=>{throw b==null||b.setError(Ki.session_approve_publish_failure),x}),b.addTrace(Ts.session_approve_publish_success)}catch(x){throw this.client.logger.error(x),this.client.session.delete(_,je("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(_),x}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:g.metadata}),await this.client.proposal.delete(a,je("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(_,dt(Tr)),{topic:_,acknowledged:()=>Promise.resolve(this.client.session.get(_))}}),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:yt.wc_sessionPropose.reject}),await this.client.proposal.delete(i,je("USER_DISCONNECTED")))}),D(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:i,namespaces:r}=t,{done:n,resolve:o,reject:a}=Ji(),c=u.payloadId(),l=u.getBigIntRpcId().toString(),h=this.client.session.get(i).namespaces;return this.events.once(Pe("session_update",c),({error:d})=>{d?a(d):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(d=>{this.client.logger.error(d),this.client.session.update(i,{namespaces:h}),a(d)}),{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=u.payloadId(),{done:n,resolve:o,reject:a}=Ji();return this.events.once(Pe("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,dt(Tr)),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(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:i,request:r,topic:n,expiry:o=yt.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===Qe.relay&&await this.confirmOnlineStateOrThrow();const c=u.payloadId(),l=u.getBigIntRpcId().toString(),{done:h,resolve:d,reject:p}=Ji(o,"Request expired. Please try again.");this.events.once(Pe("session_request",c),({error:b,result:y})=>{b?p(b):d(y)});const f="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:f,params:{request:Gt(Xe({},r),{expiryTimestamp:dt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(b=>p(b)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),await h();const w={request:Gt(Xe({},r),{expiryTimestamp:dt(o)}),chainId:i},v=this.shouldSetTVF(f,w);return await Promise.all([new Promise(async b=>{await this.sendRequest(Xe({clientRpcId:c,relayRpcId:l,topic:n,method:f,params:w,expiry:o,throwOnFailedPublish:!0},v&&{tvf:this.getTVFParams(c,w)})).catch(y=>p(y)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),b()}),new Promise(async b=>{var y;if(!((y=a.sessionConfig)!=null&&y.disableDeepLink)){const A=await D0(this.client.core.storage,Wd);await M0({id:c,topic:n,wcDeepLink:A})}b()}),h()]).then(b=>b[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===Qe.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);u.isJsonRpcResult(r)?await this.sendResult({id:n,topic:i,result:r.result,throwOnFailedPublish:!0,appLink:a}):u.isJsonRpcError(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=u.payloadId(),n=u.getBigIntRpcId().toString(),{done:o,resolve:a,reject:c}=Ji();this.events.once(Pe("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=u.getBigIntRpcId().toString(),a=u.payloadId();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:je("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}=U("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=>W1(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?Qe.link_mode:Qe.relay;o===Qe.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:h,nonce:d,type:p,exp:f,nbf:g,methods:w=[],expiry:v}=t,b=[...t.resources||[]],{topic:y,uri:A}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:y,uri:A}});const _=await this.client.core.crypto.generateKeyPair(),C=ka(_);if(await Promise.all([this.client.auth.authKeys.set(ja,{responseTopic:C,publicKey:_}),this.client.auth.pairingTopics.set(C,{topic:C,pairingTopic:y})]),await this.client.core.relayer.subscribe(C,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${y}`),w.length>0){const{namespace:S}=yn(a[0]);let z=NI(S,"request",w);Da(b)&&(z=CI(z,b.pop())),b.push(z)}const T=v&&v>yt.wc_sessionAuthenticate.req.ttl?v:yt.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:p??"caip122",chains:a,statement:c,aud:l,domain:h,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:g,resources:b},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:dt(T)},x={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:x,relays:[{protocol:"irn"}],pairingTopic:y,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:dt(yt.wc_sessionPropose.req.ttl),id:u.payloadId()},{done:q,resolve:j,reject:G}=Ji(T,"Request expired"),B=u.payloadId(),W=Pe("session_connect",$.id),V=Pe("session_request",B),H=async({error:S,session:z})=>{this.events.off(V,K),S?G(S):z&&j({session:z})},K=async S=>{var z,ee,J;if(await this.deletePendingAuthRequest(B,{message:"fulfilled",code:0}),S.error){const De=je("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return S.error.code===De.code?void 0:(this.events.off(W,H),G(S.error.message))}await this.deleteProposal($.id),this.events.off(W,H);const{cacaos:be,responder:de}=S.result,te=[],st=[];for(const De of be){await Zu({cacao:De,projectId:this.client.core.projectId})||(this.client.logger.error(De,"Signature verification failed"),G(je("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:js}=De,Rs=Da(js.resources),Xs=[$l(js.iss)],Er=Va(js.iss);if(Rs){const Us=Xu(Rs),Dn=ed(Rs);te.push(...Us),Xs.push(...Dn)}for(const Us of Xs)st.push(`${Us}:${Er}`)}const Ue=await this.client.core.crypto.generateSharedKey(_,de.publicKey);let ve;te.length>0&&(ve={topic:Ue,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:de,controller:de.publicKey,expiry:dt(Tr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:y,namespaces:bd([...new Set(te)],[...new Set(st)]),transportType:o},await this.client.core.relayer.subscribe(Ue,{transportType:o}),await this.client.session.set(Ue,ve),y&&await this.client.core.pairing.updateMetadata({topic:y,metadata:de.metadata}),ve=this.client.session.get(Ue)),(z=this.client.metadata.redirect)!=null&&z.linkMode&&(ee=de.metadata.redirect)!=null&&ee.linkMode&&(J=de.metadata.redirect)!=null&&J.universal&&i&&(this.client.core.addLinkModeSupportedApp(de.metadata.redirect.universal),this.client.session.update(Ue,{transportType:Qe.link_mode})),j({auths:be,session:ve})};this.events.once(W,H),this.events.once(V,K);let Q;try{if(n){const S=u.formatJsonRpcRequest("wc_sessionAuthenticate",P,B);this.client.core.history.set(y,S);const z=await this.client.core.crypto.encode("",S,{type:Ho,encoding:Bn});Q=pa(i,y,z)}else await Promise.all([this.sendRequest({topic:y,method:"wc_sessionAuthenticate",params:P,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:B}),this.sendRequest({topic:y,method:"wc_sessionPropose",params:$,expiry:yt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(S){throw this.events.off(W,H),this.events.off(V,K),S}return await this.setProposal($.id,$),await this.setAuthRequest(B,{request:Gt(Xe({},P),{verifyContext:{}}),pairingTopic:y,transportType:o}),{uri:Q??A,response:q}}),D(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Gi.authenticated_session_approve_started]}});try{this.isInitialized()}catch(v){throw n.setError(Vn.no_internet_connection),v}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(Vn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Qe.relay;a===Qe.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),h=ka(c),d={type:pi,receiverPublicKey:c,senderPublicKey:l},p=[],f=[];for(const v of r){if(!await Zu({cacao:v,projectId:this.client.core.projectId})){n.setError(Vn.invalid_cacao);const C=je("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:h,error:C,encodeOpts:d}),new Error(C.message)}n.addTrace(Gi.cacaos_verified);const{p:b}=v,y=Da(b.resources),A=[$l(b.iss)],_=Va(b.iss);if(y){const C=Xu(y),T=ed(y);p.push(...C),A.push(...T)}for(const C of A)f.push(`${C}:${_}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Gi.create_authenticated_session_topic);let w;if((p==null?void 0:p.length)>0){w={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:dt(Tr),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:bd([...new Set(p)],[...new Set(f)]),transportType:a},n.addTrace(Gi.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(v){throw n.setError(Vn.subscribe_authenticated_session_topic_failure),v}n.addTrace(Gi.subscribe_authenticated_session_topic_success),await this.client.session.set(g,w),n.addTrace(Gi.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Gi.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:i,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(v){throw n.setError(Vn.authenticated_session_approve_publish_failure),v}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:w}}),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===Qe.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ka(o),l={type:pi,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:r,encodeOpts:l,rpcOpts:yt.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,je("USER_DISCONNECTED"))}),D(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:r}=t;return Zf(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,je("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(Wd).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===r&&this.deletePendingSessionRequest(l.id,je("USER_DISCONNECTED"))}),r===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Bs.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(Ki.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,je("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=Bs.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,dt(yt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),D(this,"setAuthRequest",async(t,i)=>{const{request:r,pairingTopic:n,transportType:o=Qe.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||dt(yt.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:d}=t,p=u.formatJsonRpcRequest(r,n,c);let f;const g=!!h;try{const b=g?Bn:Mi;f=await this.client.core.crypto.encode(i,p,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),b}let w;if(D_.includes(r)){const b=ui(JSON.stringify(p)),y=ui(f);w=await this.client.core.verify.register({id:y,decryptedId:b})}const v=yt[r].req;if(v.attestation=w,o&&(v.ttl=o),a&&(v.id=a),this.client.core.history.set(i,p),g){const b=pa(h,i,f);await N.dist.global.Linking.openURL(b,this.client.name)}else{const b=yt[r].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=Gt(Xe({},d),{correlationId:p.id}),l?(b.internal=Gt(Xe({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,b)):this.client.core.relayer.publish(i,f,b).catch(y=>this.client.logger.error(y))}return p.id}),D(this,"sendResult",async t=>{const{id:i,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,l=u.formatJsonRpcResult(i,n);let h;const d=c&&typeof(N.dist.global==null?void 0:N.dist.global.Linking)<"u";try{const g=d?Bn:Mi;h=await this.client.core.crypto.encode(r,l,Gt(Xe({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let p,f;try{p=await this.client.core.history.get(r,i);const g=p.request;try{this.shouldSetTVF(g.method,g.params)&&(f=this.getTVFParams(i,g.params,n))}catch(w){this.client.logger.warn("sendResult() -> getTVFParams() failed",w)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${i}) failed`),g}if(d){const g=pa(c,r,h);await N.dist.global.Linking.openURL(g,this.client.name)}else{const g=p.request.method,w=yt[g].res;w.tvf=Gt(Xe({},f),{correlationId:i}),o?(w.internal=Gt(Xe({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,h,w)):this.client.core.relayer.publish(r,h,w).catch(v=>this.client.logger.error(v))}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=u.formatJsonRpcError(i,n);let h;const d=c&&typeof(N.dist.global==null?void 0:N.dist.global.Linking)<"u";try{const f=d?Bn:Mi;h=await this.client.core.crypto.encode(r,l,Gt(Xe({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),f}let p;try{p=await this.client.core.history.get(r,i)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${r}, ${i}) failed`),f}if(d){const f=pa(c,r,h);await N.dist.global.Linking.openURL(f,this.client.name)}else{const f=p.request.method,g=a||yt[f].res;this.client.core.relayer.publish(r,h,g)}await this.client.core.history.resolve(l)}),D(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(r=>{let n=!1;Ci(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=>{Ci(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===Bs.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=Bs.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Bs.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}=U("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(ci.proposal_listener_not_found)),this.isValidConnect(Xe({},r.params));const h=a.expiryTimestamp||dt(yt.wc_sessionPropose.req.ttl),d=Xe({id:c,pairingTopic:i,expiryTimestamp:h},a);await this.setProposal(c,d);const p=await this.getVerifyContext({attestationId:n,hash:ui(JSON.stringify(r)),encryptedId:o,metadata:d.proposer.metadata});l==null||l.addTrace(Gs.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:p})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:yt.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),D(this,"onSessionProposeResponse",async(t,i,r)=>{const{id:n}=i;if(u.isJsonRpcResult(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 d=await this.client.core.relayer.subscribe(h,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:t})}else if(u.isJsonRpcError(i)){await this.client.proposal.delete(n,je("USER_DISCONNECTED"));const o=Pe("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:d}=i.params,p=[...this.pendingSessions.values()].find(w=>w.sessionTopic===t);if(!p)return this.client.logger.error(`Pending session not found for topic ${t}`);const f=this.client.proposal.get(p.proposalId),g=Gt(Xe(Xe({topic:t,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},h&&{sessionProperties:h}),d&&{sessionConfig:d}),{transportType:Qe.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(Pe("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),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;u.isJsonRpcResult(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Pe("session_approve",r),{})):u.isJsonRpcError(i)&&(await this.client.session.delete(t,je("USER_DISCONNECTED")),this.events.emit(Pe("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=Hn.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:je("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Xe({topic:t},r));try{Hn.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 Hn.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=Pe("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(i)?this.events.emit(Pe("session_update",r),{}):u.isJsonRpcError(i)&&this.events.emit(Pe("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,dt(Tr)),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=Pe("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(i)?this.events.emit(Pe("session_extend",r),{}):u.isJsonRpcError(i)&&this.events.emit(Pe("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=Pe("session_ping",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);setTimeout(()=>{u.isJsonRpcResult(i)?this.events.emit(Pe("session_ping",r),{}):u.isJsonRpcError(i)&&this.events.emit(Pe("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(It.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:je("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:d,params:p}=a;try{await this.isValidRequest(Xe({topic:o},p));const f=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:ui(JSON.stringify(u.formatJsonRpcRequest("wc_sessionRequest",p,d))),encryptedId:l,metadata:f.peer.metadata,transportType:h}),w={id:d,topic:o,params:p,verifyContext:g};await this.setPendingSessionRequest(w),h===Qe.link_mode&&(i=f.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((r=f.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),D(this,"onSessionRequestResponse",(t,i)=>{const{id:r}=i,n=Pe("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(i)?this.events.emit(Pe("session_request",r),{result:i.result}):u.isJsonRpcError(i)&&this.events.emit(Pe("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=Hn.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Xe({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),Hn.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}),u.isJsonRpcResult(i)?this.events.emit(Pe("session_request",r),{result:i.result}):u.isJsonRpcError(i)&&this.events.emit(Pe("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:d}=n.params,p=await this.getVerifyContext({attestationId:o,hash:ui(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:r,id:n.id,authPayload:h,verifyContext:p,expiryTimestamp:d};await this.setAuthRequest(n.id,{request:f,pairingTopic:r,transportType:c}),c===Qe.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:p})}catch(l){this.client.logger.error(l);const h=n.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(n.params.requester.metadata,c),f={type:pi,receiverPublicKey:h,senderPublicKey:d};await this.sendError({id:n.id,topic:r,error:l,encodeOpts:f,rpcOpts:yt.wc_sessionAuthenticate.autoReject,appLink:p})}}),D(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),D(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Bs.idle,this.processSessionRequestQueue()},u.cjs.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=Pe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Pe("session_request",n.request.id),{error:i})})}),D(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Bs.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=Bs.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:u.formatJsonRpcRequest("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(!Zt(t)){const{message:c}=U("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(Wt(i)||await this.isValidPairingTopic(i),!iE(a)){const{message:c}=U("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!Wt(r)&&Po(r)!==0&&this.validateNamespaces(r,"requiredNamespaces"),!Wt(n)&&Po(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Wt(o)||this.validateSessionProps(o,"sessionProperties")}),D(this,"validateNamespaces",(t,i)=>{const r=sE(t,"connect()",i);if(r)throw new Error(r.message)}),D(this,"isValidApprove",async t=>{if(!Zt(t))throw new Error(U("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=Fc(r,"approve()");if(c)throw new Error(c.message);const l=Ed(a.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!nt(n,!0)){const{message:h}=U("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}Wt(o)||this.validateSessionProps(o,"sessionProperties")}),D(this,"isValidReject",async t=>{if(!Zt(t)){const{message:n}=U("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:r}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!nE(r)){const{message:n}=U("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),D(this,"isValidSessionSettleRequest",t=>{if(!Zt(t)){const{message:l}=U("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(l)}const{relay:i,controller:r,namespaces:n,expiry:o}=t;if(!fw(i)){const{message:l}=U("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=Q1(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Fc(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Ci(o)){const{message:l}=U("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),D(this,"isValidUpdate",async t=>{if(!Zt(t)){const{message:c}=U("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=Fc(r,"update()");if(o)throw new Error(o.message);const a=Ed(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),D(this,"isValidExtend",async t=>{if(!Zt(t)){const{message:r}=U("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(!Zt(t)){const{message:c}=U("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(!Id(a,n)){const{message:c}=U("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!oE(r)){const{message:c}=U("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!lE(a,n,r.method)){const{message:c}=U("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!pE(o,Kc)){const{message:c}=U("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Kc.min} and ${Kc.max}`);throw new Error(c)}}),D(this,"isValidRespond",async t=>{var i;if(!Zt(t)){const{message:o}=U("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(!aE(n)){const{message:o}=U("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),D(this,"isValidPing",async t=>{if(!Zt(t)){const{message:r}=U("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),D(this,"isValidEmit",async t=>{if(!Zt(t)){const{message:a}=U("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(!Id(o,n)){const{message:a}=U("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!cE(r)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!hE(o,n,r.name)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),D(this,"isValidDisconnect",async t=>{if(!Zt(t)){const{message:r}=U("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(!nt(r,!1))throw new Error("uri is required parameter");if(!nt(n,!1))throw new Error("domain is required parameter");if(!nt(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>yn(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=yn(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||wo,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Qe.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(!nt(r,!1)){const{message:n}=U("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}=U("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,d,p;return!t||i!==Qe.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&&((d=t==null?void 0:t.redirect)==null?void 0:d.universal)!==""&&((p=t==null?void 0:t.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(N.dist.global==null?void 0:N.dist.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=Bu(t,"topic")||"",r=decodeURIComponent(Bu(t,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:Qe.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:r,sessionExists:n})}),D(this,"registerLinkModeListeners",async()=>{var t;if(Oh()||zi()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=N.dist.global==null?void 0:N.dist.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(Kd).includes(r.method)}),D(this,"getTVFParams",(t,i,r)=>{var n,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,r);return Gt(Xe({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=Kd[t];if(typeof i=="string")return[i];const n=i[r.key];if(ur(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}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(It.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(ja)?this.client.auth.authKeys.get(ja):{publicKey:void 0},a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===Qe.link_mode?Bn:Mi});try{u.isJsonRpcRequest(a)?(this.client.core.history.set(t,a),this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:ui(i)})):u.isJsonRpcResponse(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n})}catch(c){this.client.logger.error(c)}}registerExpirerEvents(){this.client.core.expirer.on(bs.expired,async e=>{const{topic:t,id:i}=Bf(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,U("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,U("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(tr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(tr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!nt(e,!1)){const{message:t}=U("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}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Ci(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=U("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!nt(e,!1)){const{message:t}=U("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}=U("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Ci(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=U("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=U("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(nt(e,!1)){const{message:t}=U("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=U("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!rE(e)){const{message:t}=U("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=U("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Ci(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=U("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}},V_=class extends yr{constructor(e,t){super(e,t,$_,Fh),this.core=e,this.logger=t}},K_=class extends yr{constructor(e,t){super(e,t,M_,Fh),this.core=e,this.logger=t}},G_=class extends yr{constructor(e,t){super(e,t,x_,Fh,i=>i.id),this.core=e,this.logger=t}},Y_=class extends yr{constructor(e,t){super(e,t,R_,pc,()=>ja),this.core=e,this.logger=t}},Q_=class extends yr{constructor(e,t){super(e,t,U_,pc),this.core=e,this.logger=t}},J_=class extends yr{constructor(e,t){super(e,t,L_,pc,i=>i.id),this.core=e,this.logger=t}};var Z_=Object.defineProperty,X_=(s,e,t)=>e in s?Z_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Gc=(s,e,t)=>X_(s,typeof e!="symbol"?e+"":e,t);let eC=class{constructor(e,t){this.core=e,this.logger=t,Gc(this,"authKeys"),Gc(this,"pairingTopics"),Gc(this,"requests"),this.authKeys=new Y_(this.core,this.logger),this.pairingTopics=new Q_(this.core,this.logger),this.requests=new J_(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}};var tC=Object.defineProperty,sC=(s,e,t)=>e in s?tC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fe=(s,e,t)=>sC(s,typeof e!="symbol"?e+"":e,t);let iC=class kw extends T_{constructor(e){super(e),fe(this,"protocol",Ow),fe(this,"version",xw),fe(this,"name",Vc.name),fe(this,"metadata"),fe(this,"core"),fe(this,"logger"),fe(this,"events",new u.eventsExports.EventEmitter),fe(this,"engine"),fe(this,"session"),fe(this,"proposal"),fe(this,"pendingRequest"),fe(this,"auth"),fe(this,"signConfig"),fe(this,"on",(i,r)=>this.events.on(i,r)),fe(this,"once",(i,r)=>this.events.once(i,r)),fe(this,"off",(i,r)=>this.events.off(i,r)),fe(this,"removeListener",(i,r)=>this.events.removeListener(i,r)),fe(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),fe(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"update",async i=>{try{return await this.engine.update(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"request",async i=>{try{return await this.engine.request(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"find",i=>{try{return this.engine.find(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),fe(this,"authenticate",async(i,r)=>{try{return await this.engine.authenticate(i,r)}catch(n){throw this.logger.error(n.message),n}}),fe(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),fe(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)||Vc.name,this.metadata=(e==null?void 0:e.metadata)||Uf(),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:u.Ot(u.k({level:(e==null?void 0:e.logger)||Vc.logger}));this.core=(e==null?void 0:e.core)||new __(e),this.logger=u.E(t,this.name),this.session=new K_(this.core,this.logger),this.proposal=new V_(this.core,this.logger),this.pendingRequest=new G_(this.core,this.logger),this.engine=new W_(this),this.auth=new eC(this.core,this.logger)}static async init(e){const t=new kw(e);return await t.initialize(),t}get context(){return u.y(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},u.cjs.toMiliseconds(u.cjs.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Yd="error",rC="wss://relay.walletconnect.org",nC="wc",oC="universal_provider",Qd=`${nC}@2:${oC}:`,jw="https://rpc.walletconnect.org/v1/",rn="generic",aC=`${jw}bundler`,Ns={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var fa=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof N.dist.global<"u"?N.dist.global:typeof self<"u"?self:{};function cC(){this.__data__=[],this.size=0}var lC=cC;function hC(s,e){return s===e||s!==s&&e!==e}var gc=hC,uC=gc;function dC(s,e){for(var t=s.length;t--;)if(uC(s[t][0],e))return t;return-1}var fc=dC,pC=fc,gC=Array.prototype,fC=gC.splice;function wC(s){var e=this.__data__,t=pC(e,s);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():fC.call(e,t,1),--this.size,!0}var yC=wC,mC=fc;function bC(s){var e=this.__data__,t=mC(e,s);return t<0?void 0:e[t][1]}var vC=bC,IC=fc;function EC(s){return IC(this.__data__,s)>-1}var AC=EC,NC=fc;function _C(s,e){var t=this.__data__,i=NC(t,s);return i<0?(++this.size,t.push([s,e])):t[i][1]=e,this}var CC=_C,SC=lC,TC=yC,PC=vC,$C=AC,MC=CC;function nn(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])}}nn.prototype.clear=SC,nn.prototype.delete=TC,nn.prototype.get=PC,nn.prototype.has=$C,nn.prototype.set=MC;var wc=nn,OC=wc;function xC(){this.__data__=new OC,this.size=0}var DC=xC;function kC(s){var e=this.__data__,t=e.delete(s);return this.size=e.size,t}var jC=kC;function RC(s){return this.__data__.get(s)}var UC=RC;function LC(s){return this.__data__.has(s)}var zC=LC,FC=typeof fa=="object"&&fa&&fa.Object===Object&&fa,Rw=FC,qC=Rw,BC=typeof self=="object"&&self&&self.Object===Object&&self,HC=qC||BC||Function("return this")(),$n=HC,WC=$n,VC=WC.Symbol,Uw=VC,Jd=Uw,Lw=Object.prototype,KC=Lw.hasOwnProperty,GC=Lw.toString,Yn=Jd?Jd.toStringTag:void 0;function YC(s){var e=KC.call(s,Yn),t=s[Yn];try{s[Yn]=void 0;var i=!0}catch{}var r=GC.call(s);return i&&(e?s[Yn]=t:delete s[Yn]),r}var QC=YC,JC=Object.prototype,ZC=JC.toString;function XC(s){return ZC.call(s)}var eS=XC,Zd=Uw,tS=QC,sS=eS,iS="[object Null]",rS="[object Undefined]",Xd=Zd?Zd.toStringTag:void 0;function nS(s){return s==null?s===void 0?rS:iS:Xd&&Xd in Object(s)?tS(s):sS(s)}var yc=nS;function oS(s){var e=typeof s;return s!=null&&(e=="object"||e=="function")}var mr=oS,aS=yc,cS=mr,lS="[object AsyncFunction]",hS="[object Function]",uS="[object GeneratorFunction]",dS="[object Proxy]";function pS(s){if(!cS(s))return!1;var e=aS(s);return e==hS||e==uS||e==lS||e==dS}var qh=pS,gS=$n,fS=gS["__core-js_shared__"],wS=fS,Yc=wS,ep=function(){var s=/[^.]+$/.exec(Yc&&Yc.keys&&Yc.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function yS(s){return!!ep&&ep in s}var mS=yS,bS=Function.prototype,vS=bS.toString;function IS(s){if(s!=null){try{return vS.call(s)}catch{}try{return s+""}catch{}}return""}var ES=IS,AS=qh,NS=mS,_S=mr,CS=ES,SS=/[\\^$.*+?()[\]{}|]/g,TS=/^\[object .+?Constructor\]$/,PS=Function.prototype,$S=Object.prototype,MS=PS.toString,OS=$S.hasOwnProperty,xS=RegExp("^"+MS.call(OS).replace(SS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function DS(s){if(!_S(s)||NS(s))return!1;var e=AS(s)?xS:TS;return e.test(CS(s))}var kS=DS;function jS(s,e){return s==null?void 0:s[e]}var RS=jS,US=kS,LS=RS;function zS(s,e){var t=LS(s,e);return US(t)?t:void 0}var Bh=zS,FS=Bh,qS=$n,BS=FS(qS,"Map"),zw=BS,HS=Bh,WS=HS(Object,"create"),mc=WS,tp=mc;function VS(){this.__data__=tp?tp(null):{},this.size=0}var KS=VS;function GS(s){var e=this.has(s)&&delete this.__data__[s];return this.size-=e?1:0,e}var YS=GS,QS=mc,JS="__lodash_hash_undefined__",ZS=Object.prototype,XS=ZS.hasOwnProperty;function eT(s){var e=this.__data__;if(QS){var t=e[s];return t===JS?void 0:t}return XS.call(e,s)?e[s]:void 0}var tT=eT,sT=mc,iT=Object.prototype,rT=iT.hasOwnProperty;function nT(s){var e=this.__data__;return sT?e[s]!==void 0:rT.call(e,s)}var oT=nT,aT=mc,cT="__lodash_hash_undefined__";function lT(s,e){var t=this.__data__;return this.size+=this.has(s)?0:1,t[s]=aT&&e===void 0?cT:e,this}var hT=lT,uT=KS,dT=YS,pT=tT,gT=oT,fT=hT;function on(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])}}on.prototype.clear=uT,on.prototype.delete=dT,on.prototype.get=pT,on.prototype.has=gT,on.prototype.set=fT;var wT=on,sp=wT,yT=wc,mT=zw;function bT(){this.size=0,this.__data__={hash:new sp,map:new(mT||yT),string:new sp}}var vT=bT;function IT(s){var e=typeof s;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?s!=="__proto__":s===null}var ET=IT,AT=ET;function NT(s,e){var t=s.__data__;return AT(e)?t[typeof e=="string"?"string":"hash"]:t.map}var bc=NT,_T=bc;function CT(s){var e=_T(this,s).delete(s);return this.size-=e?1:0,e}var ST=CT,TT=bc;function PT(s){return TT(this,s).get(s)}var $T=PT,MT=bc;function OT(s){return MT(this,s).has(s)}var xT=OT,DT=bc;function kT(s,e){var t=DT(this,s),i=t.size;return t.set(s,e),this.size+=t.size==i?0:1,this}var jT=kT,RT=vT,UT=ST,LT=$T,zT=xT,FT=jT;function an(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])}}an.prototype.clear=RT,an.prototype.delete=UT,an.prototype.get=LT,an.prototype.has=zT,an.prototype.set=FT;var qT=an,BT=wc,HT=zw,WT=qT,VT=200;function KT(s,e){var t=this.__data__;if(t instanceof BT){var i=t.__data__;if(!HT||i.length<VT-1)return i.push([s,e]),this.size=++t.size,this;t=this.__data__=new WT(i)}return t.set(s,e),this.size=t.size,this}var GT=KT,YT=wc,QT=DC,JT=jC,ZT=UC,XT=zC,eP=GT;function cn(s){var e=this.__data__=new YT(s);this.size=e.size}cn.prototype.clear=QT,cn.prototype.delete=JT,cn.prototype.get=ZT,cn.prototype.has=XT,cn.prototype.set=eP;var tP=cn,sP=Bh,iP=function(){try{var s=sP(Object,"defineProperty");return s({},"",{}),s}catch{}}(),Fw=iP,ip=Fw;function rP(s,e,t){e=="__proto__"&&ip?ip(s,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):s[e]=t}var Hh=rP,nP=Hh,oP=gc;function aP(s,e,t){(t!==void 0&&!oP(s[e],t)||t===void 0&&!(e in s))&&nP(s,e,t)}var qw=aP;function cP(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 lP=cP,hP=lP,uP=hP(),dP=uP,Gl={exports:{}};(function(s,e){var t=$n,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 d=l.length,p=a?a(d):new l.constructor(d);return l.copy(p),p}s.exports=c})(Gl,Gl.exports);var pP=$n,gP=pP.Uint8Array,fP=gP,rp=fP;function wP(s){var e=new s.constructor(s.byteLength);return new rp(e).set(new rp(s)),e}var yP=wP,mP=yP;function bP(s,e){var t=e?mP(s.buffer):s.buffer;return new s.constructor(t,s.byteOffset,s.length)}var vP=bP;function IP(s,e){var t=-1,i=s.length;for(e||(e=Array(i));++t<i;)e[t]=s[t];return e}var EP=IP,AP=mr,np=Object.create,NP=function(){function s(){}return function(e){if(!AP(e))return{};if(np)return np(e);s.prototype=e;var t=new s;return s.prototype=void 0,t}}(),_P=NP;function CP(s,e){return function(t){return s(e(t))}}var SP=CP,TP=SP,PP=TP(Object.getPrototypeOf,Object),Bw=PP,$P=Object.prototype;function MP(s){var e=s&&s.constructor,t=typeof e=="function"&&e.prototype||$P;return s===t}var Hw=MP,OP=_P,xP=Bw,DP=Hw;function kP(s){return typeof s.constructor=="function"&&!DP(s)?OP(xP(s)):{}}var jP=kP;function RP(s){return s!=null&&typeof s=="object"}var Vo=RP,UP=yc,LP=Vo,zP="[object Arguments]";function FP(s){return LP(s)&&UP(s)==zP}var qP=FP,op=qP,BP=Vo,Ww=Object.prototype,HP=Ww.hasOwnProperty,WP=Ww.propertyIsEnumerable,VP=op(function(){return arguments}())?op:function(s){return BP(s)&&HP.call(s,"callee")&&!WP.call(s,"callee")},Vw=VP,KP=Array.isArray,Kw=KP,GP=9007199254740991;function YP(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=GP}var Gw=YP,QP=qh,JP=Gw;function ZP(s){return s!=null&&JP(s.length)&&!QP(s)}var Wh=ZP,XP=Wh,e$=Vo;function t$(s){return e$(s)&&XP(s)}var s$=t$,Qa={exports:{}};function i$(){return!1}var r$=i$;(function(s,e){var t=$n,i=r$,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})(Qa,Qa.exports);var n$=yc,o$=Bw,a$=Vo,c$="[object Object]",l$=Function.prototype,h$=Object.prototype,Yw=l$.toString,u$=h$.hasOwnProperty,d$=Yw.call(Object);function p$(s){if(!a$(s)||n$(s)!=c$)return!1;var e=o$(s);if(e===null)return!0;var t=u$.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Yw.call(t)==d$}var g$=p$,f$=yc,w$=Gw,y$=Vo,m$="[object Arguments]",b$="[object Array]",v$="[object Boolean]",I$="[object Date]",E$="[object Error]",A$="[object Function]",N$="[object Map]",_$="[object Number]",C$="[object Object]",S$="[object RegExp]",T$="[object Set]",P$="[object String]",$$="[object WeakMap]",M$="[object ArrayBuffer]",O$="[object DataView]",x$="[object Float32Array]",D$="[object Float64Array]",k$="[object Int8Array]",j$="[object Int16Array]",R$="[object Int32Array]",U$="[object Uint8Array]",L$="[object Uint8ClampedArray]",z$="[object Uint16Array]",F$="[object Uint32Array]",Ye={};Ye[x$]=Ye[D$]=Ye[k$]=Ye[j$]=Ye[R$]=Ye[U$]=Ye[L$]=Ye[z$]=Ye[F$]=!0,Ye[m$]=Ye[b$]=Ye[M$]=Ye[v$]=Ye[O$]=Ye[I$]=Ye[E$]=Ye[A$]=Ye[N$]=Ye[_$]=Ye[C$]=Ye[S$]=Ye[T$]=Ye[P$]=Ye[$$]=!1;function q$(s){return y$(s)&&w$(s.length)&&!!Ye[f$(s)]}var B$=q$;function H$(s){return function(e){return s(e)}}var W$=H$,Yl={exports:{}};(function(s,e){var t=Rw,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})(Yl,Yl.exports);var V$=B$,K$=W$,ap=Yl.exports,cp=ap&&ap.isTypedArray,G$=cp?K$(cp):V$,Qw=G$;function Y$(s,e){if(!(e==="constructor"&&typeof s[e]=="function")&&e!="__proto__")return s[e]}var Jw=Y$,Q$=Hh,J$=gc,Z$=Object.prototype,X$=Z$.hasOwnProperty;function e2(s,e,t){var i=s[e];(!(X$.call(s,e)&&J$(i,t))||t===void 0&&!(e in s))&&Q$(s,e,t)}var t2=e2,s2=t2,i2=Hh;function r2(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?i2(t,a,c):s2(t,a,c)}return t}var n2=r2;function o2(s,e){for(var t=-1,i=Array(s);++t<s;)i[t]=e(t);return i}var a2=o2,c2=9007199254740991,l2=/^(?:0|[1-9]\d*)$/;function h2(s,e){var t=typeof s;return e=e??c2,!!e&&(t=="number"||t!="symbol"&&l2.test(s))&&s>-1&&s%1==0&&s<e}var Zw=h2,u2=a2,d2=Vw,p2=Kw,g2=Qa.exports,f2=Zw,w2=Qw,y2=Object.prototype,m2=y2.hasOwnProperty;function b2(s,e){var t=p2(s),i=!t&&d2(s),r=!t&&!i&&g2(s),n=!t&&!i&&!r&&w2(s),o=t||i||r||n,a=o?u2(s.length,String):[],c=a.length;for(var l in s)(e||m2.call(s,l))&&!(o&&(l=="length"||r&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||f2(l,c)))&&a.push(l);return a}var v2=b2;function I2(s){var e=[];if(s!=null)for(var t in Object(s))e.push(t);return e}var E2=I2,A2=mr,N2=Hw,_2=E2,C2=Object.prototype,S2=C2.hasOwnProperty;function T2(s){if(!A2(s))return _2(s);var e=N2(s),t=[];for(var i in s)i=="constructor"&&(e||!S2.call(s,i))||t.push(i);return t}var P2=T2,$2=v2,M2=P2,O2=Wh;function x2(s){return O2(s)?$2(s,!0):M2(s)}var Xw=x2,D2=n2,k2=Xw;function j2(s){return D2(s,k2(s))}var R2=j2,lp=qw,U2=Gl.exports,L2=vP,z2=EP,F2=jP,hp=Vw,up=Kw,q2=s$,B2=Qa.exports,H2=qh,W2=mr,V2=g$,K2=Qw,dp=Jw,G2=R2;function Y2(s,e,t,i,r,n,o){var a=dp(s,t),c=dp(e,t),l=o.get(c);if(l){lp(s,t,l);return}var h=n?n(a,c,t+"",s,e,o):void 0,d=h===void 0;if(d){var p=up(c),f=!p&&B2(c),g=!p&&!f&&K2(c);h=c,p||f||g?up(a)?h=a:q2(a)?h=z2(a):f?(d=!1,h=U2(c,!0)):g?(d=!1,h=L2(c,!0)):h=[]:V2(c)||hp(c)?(h=a,hp(a)?h=G2(a):(!W2(a)||H2(a))&&(h=F2(c))):d=!1}d&&(o.set(c,h),r(h,c,i,n,o),o.delete(c)),lp(s,t,h)}var Q2=Y2,J2=tP,Z2=qw,X2=dP,eM=Q2,tM=mr,sM=Xw,iM=Jw;function ey(s,e,t,i,r){s!==e&&X2(e,function(n,o){if(r||(r=new J2),tM(n))eM(s,e,o,t,ey,i,r);else{var a=i?i(iM(s,o),n,o+"",s,e,r):void 0;a===void 0&&(a=n),Z2(s,o,a)}},sM)}var rM=ey;function nM(s){return s}var ty=nM;function oM(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 aM=oM,cM=aM,pp=Math.max;function lM(s,e,t){return e=pp(e===void 0?s.length-1:e,0),function(){for(var i=arguments,r=-1,n=pp(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),cM(s,this,a)}}var hM=lM;function uM(s){return function(){return s}}var dM=uM,pM=dM,gp=Fw,gM=ty,fM=gp?function(s,e){return gp(s,"toString",{configurable:!0,enumerable:!1,value:pM(e),writable:!0})}:gM,wM=fM,yM=800,mM=16,bM=Date.now;function vM(s){var e=0,t=0;return function(){var i=bM(),r=mM-(i-t);if(t=i,r>0){if(++e>=yM)return arguments[0]}else e=0;return s.apply(void 0,arguments)}}var IM=vM,EM=wM,AM=IM,NM=AM(EM),_M=NM,CM=ty,SM=hM,TM=_M;function PM(s,e){return TM(SM(s,e,CM),s+"")}var $M=PM,MM=gc,OM=Wh,xM=Zw,DM=mr;function kM(s,e,t){if(!DM(t))return!1;var i=typeof e;return(i=="number"?OM(t)&&xM(e,t.length):i=="string"&&e in t)?MM(t[e],s):!1}var jM=kM,RM=$M,UM=jM;function LM(s){return RM(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&&UM(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 zM=LM,FM=rM,qM=zM,BM=qM(function(s,e,t){FM(s,e,t)}),HM=BM,WM=Object.defineProperty,VM=Object.defineProperties,KM=Object.getOwnPropertyDescriptors,fp=Object.getOwnPropertySymbols,GM=Object.prototype.hasOwnProperty,YM=Object.prototype.propertyIsEnumerable,wp=(s,e,t)=>e in s?WM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,wa=(s,e)=>{for(var t in e||(e={}))GM.call(e,t)&&wp(s,t,e[t]);if(fp)for(var t of fp(e))YM.call(e,t)&&wp(s,t,e[t]);return s},QM=(s,e)=>VM(s,KM(e));function us(s,e,t){var i;const r=yn(s);return((i=e.rpcMap)==null?void 0:i[r.reference])||`${jw}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function br(s){return s.includes(":")?s.split(":")[1]:s}function sy(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function JM(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 Qc(s={},e={}){const t=yp(s),i=yp(e);return HM(t,i)}function yp(s){var e,t,i,r;const n={};if(!Po(s))return n;for(const[o,a]of Object.entries(s)){const c=Lh(o)?[o]:a.chains,l=a.methods||[],h=a.events||[],d=a.rpcMap||{},p=co(o);n[p]=QM(wa(wa({},n[p]),a),{chains:xa(c,(e=n[p])==null?void 0:e.chains),methods:xa(l,(t=n[p])==null?void 0:t.methods),events:xa(h,(i=n[p])==null?void 0:i.events),rpcMap:wa(wa({},d),(r=n[p])==null?void 0:r.rpcMap)})}return n}function ZM(s){return s.includes(":")?s.split(":")[2]:s}function mp(s){const e={};for(const[t,i]of Object.entries(s)){const r=i.methods||[],n=i.events||[],o=i.accounts||[],a=Lh(t)?[t]:i.chains?i.chains:sy(i.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Jc(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 iy={},Ce=s=>iy[s],Zc=(s,e)=>{iy[s]=e};var XM=Object.defineProperty,eO=(s,e,t)=>e in s?XM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Pr=(s,e,t)=>eO(s,typeof e!="symbol"?e+"":e,t);class tO{constructor(e){Pr(this,"name","polkadot"),Pr(this,"client"),Pr(this,"httpProviders"),Pr(this,"events"),Pr(this,"namespace"),Pr(this,"chainId"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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(Ns.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=br(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||us(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Ce("disableProviderPing")))}}var sO=Object.defineProperty,iO=Object.defineProperties,rO=Object.getOwnPropertyDescriptors,bp=Object.getOwnPropertySymbols,nO=Object.prototype.hasOwnProperty,oO=Object.prototype.propertyIsEnumerable,Ql=(s,e,t)=>e in s?sO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,vp=(s,e)=>{for(var t in e||(e={}))nO.call(e,t)&&Ql(s,t,e[t]);if(bp)for(var t of bp(e))oO.call(e,t)&&Ql(s,t,e[t]);return s},Ip=(s,e)=>iO(s,rO(e)),$r=(s,e,t)=>Ql(s,typeof e!="symbol"?e+"":e,t);class aO{constructor(e){$r(this,"name","eip155"),$r(this,"client"),$r(this,"chainId"),$r(this,"namespace"),$r(this,"httpProviders"),$r(this,"events"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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(Ns.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||us(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Ce("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(br(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:Ip(vp({},o.sessionProperties||{}),{capabilities:Ip(vp({},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(u.formatJsonRpcRequest("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`${aC}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var cO=Object.defineProperty,lO=(s,e,t)=>e in s?cO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Mr=(s,e,t)=>lO(s,typeof e!="symbol"?e+"":e,t);class hO{constructor(e){Mr(this,"name","solana"),Mr(this,"client"),Mr(this,"httpProviders"),Mr(this,"events"),Mr(this,"namespace"),Mr(this,"chainId"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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(Ns.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=br(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||us(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Ce("disableProviderPing")))}}var uO=Object.defineProperty,dO=(s,e,t)=>e in s?uO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Or=(s,e,t)=>dO(s,typeof e!="symbol"?e+"":e,t);class pO{constructor(e){Or(this,"name","cosmos"),Or(this,"client"),Or(this,"httpProviders"),Or(this,"events"),Or(this,"namespace"),Or(this,"chainId"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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(Ns.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=br(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||us(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Ce("disableProviderPing")))}}var gO=Object.defineProperty,fO=(s,e,t)=>e in s?gO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,xr=(s,e,t)=>fO(s,typeof e!="symbol"?e+"":e,t);class wO{constructor(e){xr(this,"name","algorand"),xr(this,"client"),xr(this,"httpProviders"),xr(this,"events"),xr(this,"namespace"),xr(this,"chainId"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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||us(`${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(Ns.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||us(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new u.o(new u.f$1(i,Ce("disableProviderPing")))}}var yO=Object.defineProperty,mO=(s,e,t)=>e in s?yO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Dr=(s,e,t)=>mO(s,typeof e!="symbol"?e+"":e,t);class bO{constructor(e){Dr(this,"name","cip34"),Dr(this,"client"),Dr(this,"httpProviders"),Dr(this,"events"),Dr(this,"namespace"),Dr(this,"chainId"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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(Ns.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=br(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 u.o(new u.f$1(i,Ce("disableProviderPing")))}}var vO=Object.defineProperty,IO=(s,e,t)=>e in s?vO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,kr=(s,e,t)=>IO(s,typeof e!="symbol"?e+"":e,t);class EO{constructor(e){kr(this,"name","elrond"),kr(this,"client"),kr(this,"httpProviders"),kr(this,"events"),kr(this,"namespace"),kr(this,"chainId"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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(Ns.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=br(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||us(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Ce("disableProviderPing")))}}var AO=Object.defineProperty,NO=(s,e,t)=>e in s?AO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,jr=(s,e,t)=>NO(s,typeof e!="symbol"?e+"":e,t);class _O{constructor(e){jr(this,"name","multiversx"),jr(this,"client"),jr(this,"httpProviders"),jr(this,"events"),jr(this,"namespace"),jr(this,"chainId"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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(Ns.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=br(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||us(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Ce("disableProviderPing")))}}var CO=Object.defineProperty,SO=(s,e,t)=>e in s?CO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Rr=(s,e,t)=>SO(s,typeof e!="symbol"?e+"":e,t);class TO{constructor(e){Rr(this,"name","near"),Rr(this,"client"),Rr(this,"httpProviders"),Rr(this,"events"),Rr(this,"namespace"),Rr(this,"chainId"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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||us(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Ns.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||us(e,this.namespace);return typeof i>"u"?void 0:new u.o(new u.f$1(i,Ce("disableProviderPing")))}}var PO=Object.defineProperty,$O=(s,e,t)=>e in s?PO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ur=(s,e,t)=>$O(s,typeof e!="symbol"?e+"":e,t);class MO{constructor(e){Ur(this,"name","tezos"),Ur(this,"client"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"namespace"),Ur(this,"chainId"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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||us(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(Ns.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||us(e,this.namespace);return typeof i>"u"?void 0:new u.o(new u.f$1(i))}}var OO=Object.defineProperty,xO=(s,e,t)=>e in s?OO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Lr=(s,e,t)=>xO(s,typeof e!="symbol"?e+"":e,t);class DO{constructor(e){Lr(this,"name",rn),Lr(this,"client"),Lr(this,"httpProviders"),Lr(this,"events"),Lr(this,"namespace"),Lr(this,"chainId"),this.namespace=e.namespace,this.events=Ce("events"),this.client=Ce("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(Ns.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=yn(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||us(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Ce("disableProviderPing")))}}var kO=Object.defineProperty,jO=Object.defineProperties,RO=Object.getOwnPropertyDescriptors,Ep=Object.getOwnPropertySymbols,UO=Object.prototype.hasOwnProperty,LO=Object.prototype.propertyIsEnumerable,Jl=(s,e,t)=>e in s?kO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ya=(s,e)=>{for(var t in e||(e={}))UO.call(e,t)&&Jl(s,t,e[t]);if(Ep)for(var t of Ep(e))LO.call(e,t)&&Jl(s,t,e[t]);return s},Xc=(s,e)=>jO(s,RO(e)),$s=(s,e,t)=>Jl(s,typeof e!="symbol"?e+"":e,t);class Vh{constructor(e){$s(this,"client"),$s(this,"namespaces"),$s(this,"optionalNamespaces"),$s(this,"sessionProperties"),$s(this,"events",new u.Nt),$s(this,"rpcProviders",{}),$s(this,"session"),$s(this,"providerOpts"),$s(this,"logger"),$s(this,"uri"),$s(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:u.Ot(u.k({level:(e==null?void 0:e.logger)||Yd})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Vh(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:ya({},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,u.formatJsonRpcResult(n,o))).catch(o=>t(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),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:je("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=mp(this.session.namespaces);this.namespaces=Qc(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=mp(r.namespaces);return this.namespaces=Qc(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===rn?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(ur(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 iC.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Yd,relayUrl:this.providerOpts.relayUrl||rC,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=>co(t)))];Zc("client",this.client),Zc("events",this.events),Zc("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=JM(t,this.session),r=sy(i),n=Qc(this.namespaces,this.optionalNamespaces),o=Xc(ya({},n[t]),{accounts:i,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new aO({namespace:o});break;case"algorand":this.rpcProviders[t]=new wO({namespace:o});break;case"solana":this.rpcProviders[t]=new hO({namespace:o});break;case"cosmos":this.rpcProviders[t]=new pO({namespace:o});break;case"polkadot":this.rpcProviders[t]=new tO({namespace:o});break;case"cip34":this.rpcProviders[t]=new bO({namespace:o});break;case"elrond":this.rpcProviders[t]=new EO({namespace:o});break;case"multiversx":this.rpcProviders[t]=new _O({namespace:o});break;case"near":this.rpcProviders[t]=new TO({namespace:o});break;case"tezos":this.rpcProviders[t]=new MO({namespace:o});break;default:this.rpcProviders[rn]?this.rpcProviders[rn].updateNamespace(o):this.rpcProviders[rn]=new DO({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&&ur(r)&&this.events.emit("accountsChanged",r.map(ZM))}else if(i.name==="chainChanged"){const r=t.chainId,n=t.event.data,o=co(r),a=Jc(r)!==Jc(n)?`${o}:${Jc(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=Xc(ya({},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",Xc(ya({},je("USER_DISCONNECTED")),{data:e.topic}))}),this.on(Ns.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[rn]}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=>co(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=co(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(`${Qd}/${e}`,t)}async getFromStore(e){return await this.client.core.storage.getItem(`${Qd}/${e}`)}}const zO=Vh,ry={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]}},ma={bigNumber(s){return s?new k.Big(s):new k.Big(0)},multiply(s,e){if(s===void 0||e===void 0)return new k.Big(0);const t=new k.Big(s),i=new k.Big(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,""))}},FO=[{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"}]}],qO=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],BO=[{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"}]}],se={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"},HO={getERC20Abi:s=>se.USDT_CONTRACT_ADDRESSES.includes(s)?BO:FO,getSwapAbi:()=>qO},Ii={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}}},ue={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 el(s){if(!s)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${s}:connected_connector_id`}const ae={setItem(s,e){lo()&&e!==void 0&&localStorage.setItem(s,e)},getItem(s){if(lo())return localStorage.getItem(s)||void 0},removeItem(s){lo()&&localStorage.removeItem(s)},clear(){lo()&&localStorage.clear()}};function lo(){return typeof window<"u"&&typeof localStorage<"u"}function Oi(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"}}const tl=(typeof N.dist.process<"u"&&typeof N.dist.process.env<"u"?N.dist.process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Vt={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:tl,SECURE_SITE_DASHBOARD:`${tl}/dashboard`,SECURE_SITE_FAVICON:`${tl}/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"}},X={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(s,e){return Date.now()-s>e},getActiveNetworkProps(){const s=X.getActiveNamespace(),e=X.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{ae.setItem(ue.DEEPLINK_CHOICE,JSON.stringify({href:e,name:s}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const s=ae.getItem(ue.DEEPLINK_CHOICE);if(s)return JSON.parse(s)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{ae.removeItem(ue.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(s){try{ae.setItem(ue.ACTIVE_NAMESPACE,s)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(s){try{ae.setItem(ue.ACTIVE_CAIP_NETWORK_ID,s),X.setActiveNamespace(s.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return ae.getItem(ue.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{ae.removeItem(ue.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(s){try{const e=el(s);ae.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(s){try{const e=X.getRecentWallets();e.find(i=>i.id===s.id)||(e.unshift(s),e.length>2&&e.pop(),ae.setItem(ue.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const s=ae.getItem(ue.RECENT_WALLETS);return s?JSON.parse(s):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(s,e){try{const t=el(s);ae.setItem(t,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return ae.getItem(ue.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(s){if(s)try{const e=el(s);return ae.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",s)}},setConnectedSocialProvider(s){try{ae.setItem(ue.CONNECTED_SOCIAL,s)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return ae.getItem(ue.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{ae.removeItem(ue.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return ae.getItem(ue.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var t;const s=ae.getItem(ue.ACTIVE_CAIP_NETWORK_ID);return(t=s==null?void 0:s.split(":"))==null?void 0:t[1]},setConnectionStatus(s){try{ae.setItem(ue.CONNECTION_STATUS,s)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return ae.getItem(ue.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const s=ae.getItem(ue.CONNECTED_NAMESPACES);return s!=null&&s.length?s.split(","):[]}catch{return[]}},setConnectedNamespaces(s){try{const e=Array.from(new Set(s));ae.setItem(ue.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(s){try{const e=X.getConnectedNamespaces();e.includes(s)||(e.push(s),X.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(s){try{const e=X.getConnectedNamespaces(),t=e.indexOf(s);t>-1&&(e.splice(t,1),X.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return ae.getItem(ue.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(s){try{ae.setItem(ue.TELEGRAM_SOCIAL_PROVIDER,s)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{ae.removeItem(ue.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let s={};try{const e=ae.getItem(ue.PORTFOLIO_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return s},removeAddressFromBalanceCache(s){try{const e=X.getBalanceCache();ae.setItem(ue.PORTFOLIO_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove address from balance cache",s)}},getBalanceCacheForCaipAddress(s){try{const t=X.getBalanceCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;X.removeAddressFromBalanceCache(s)}catch{console.info("Unable to get balance cache for address",s)}},updateBalanceCache(s){try{const e=X.getBalanceCache();e[s.caipAddress]=s,ae.setItem(ue.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",s)}},getNativeBalanceCache(){let s={};try{const e=ae.getItem(ue.NATIVE_BALANCE_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return s},removeAddressFromNativeBalanceCache(s){try{const e=X.getBalanceCache();ae.setItem(ue.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=X.getNativeBalanceCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",s),X.removeAddressFromBalanceCache(s)}catch{console.info("Unable to get balance cache for address",s)}},updateNativeBalanceCache(s){try{const e=X.getNativeBalanceCache();e[s.caipAddress]=s,ae.setItem(ue.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",s)}},getEnsCache(){let s={};try{const e=ae.getItem(ue.ENS_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return s},getEnsFromCacheForAddress(s){try{const t=X.getEnsCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;X.removeEnsFromCache(s)}catch{console.info("Unable to get ens name from cache",s)}},updateEnsCache(s){try{const e=X.getEnsCache();e[s.address]=s,ae.setItem(ue.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",s)}},removeEnsFromCache(s){try{const e=X.getEnsCache();ae.setItem(ue.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=ae.getItem(ue.IDENTITY_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return s},getIdentityFromCacheForAddress(s){try{const t=X.getIdentityCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;X.removeIdentityFromCache(s)}catch{console.info("Unable to get identity from cache",s)}},updateIdentityCache(s){try{const e=X.getIdentityCache();e[s.address]={identity:s.identity,timestamp:s.timestamp},ae.setItem(ue.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",s)}},removeIdentityFromCache(s){try{const e=X.getIdentityCache();ae.setItem(ue.IDENTITY_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove identity from cache",s)}},clearAddressCache(){try{ae.removeItem(ue.PORTFOLIO_CACHE),ae.removeItem(ue.NATIVE_BALANCE_CACHE),ae.removeItem(ue.ENS_CACHE),ae.removeItem(ue.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}}},le={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 le.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()<=Vt.TEN_SEC_MS:!0},isAllowedRetry(s,e=Vt.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()+Vt.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(le.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(!le.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()?X.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,le.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 se.W3M_API_URL},getBlockchainApiUrl(){return se.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return se.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?Vt.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 se.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 Qn(...s){const e=await fetch(...s);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class vc{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 Qn(n,{method:"GET",headers:e,signal:t,cache:i})).json()}async getBlob({headers:e,signal:t,...i}){const r=this.createUrl(i);return(await Qn(r,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await Qn(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 Qn(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 Qn(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 WO={handleSolanaDeeplinkRedirect(s){if(I.state.activeChain===se.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}`)}}},ss=k.proxy({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Es={state:ss,subscribeNetworkImages(s){return k.subscribe(ss.networkImages,()=>s(ss.networkImages))},subscribeKey(s,e){return k.subscribeKey(ss,s,e)},subscribe(s){return k.subscribe(ss,()=>s(ss))},setWalletImage(s,e){ss.walletImages[s]=e},setNetworkImage(s,e){ss.networkImages[s]=e},setChainImage(s,e){ss.chainImages[s]=e},setConnectorImage(s,e){ss.connectorImages={...ss.connectorImages,[s]:e}},setTokenImage(s,e){ss.tokenImages[s]=e},setCurrencyImage(s,e){ss.currencyImages[s]=e}},VO={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},sl=k.proxy({networkImagePromises:{}}),Kh={async fetchWalletImage(s){if(s)return await he._fetchWalletImage(s),this.getWalletImageById(s)},async fetchNetworkImage(s){if(!s)return;const e=this.getNetworkImageById(s);return e||(sl.networkImagePromises[s]||(sl.networkImagePromises[s]=he._fetchNetworkImage(s)),await sl.networkImagePromises[s],this.getNetworkImageById(s))},getWalletImageById(s){if(s)return Es.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 Es.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 Es.state.networkImages[s.assets.imageId]},getNetworkImageById(s){if(s)return Es.state.networkImages[s]},getConnectorImage(s){if(s!=null&&s.imageUrl)return s.imageUrl;if(s!=null&&s.imageId)return Es.state.connectorImages[s.imageId]},getChainImage(s){return Es.state.networkImages[VO[s]]}},KO={getFeatureValue(s,e){const t=e==null?void 0:e[s];return t===void 0?Vt.DEFAULT_FEATURES[s]:t},filterSocialsByPlatform(s){if(!s||!s.length)return s;if(le.isTelegram()){if(le.isIos())return s.filter(e=>e!=="google");if(le.isMac())return s.filter(e=>e!=="x");if(le.isAndroid())return s.filter(e=>!["facebook","x"].includes(e))}return s}},re=k.proxy({features:Vt.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Vt.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0}),R={state:re,subscribeKey(s,e){return k.subscribeKey(re,s,e)},setOptions(s){Object.assign(re,s)},setFeatures(s){if(!s)return;re.features||(re.features=Vt.DEFAULT_FEATURES);const e={...re.features,...s};re.features=e,re.features.socials&&(re.features.socials=KO.filterSocialsByPlatform(re.features.socials))},setProjectId(s){re.projectId=s},setCustomRpcUrls(s){re.customRpcUrls=s},setAllWallets(s){re.allWallets=s},setIncludeWalletIds(s){re.includeWalletIds=s},setExcludeWalletIds(s){re.excludeWalletIds=s},setFeaturedWalletIds(s){re.featuredWalletIds=s},setTokens(s){re.tokens=s},setTermsConditionsUrl(s){re.termsConditionsUrl=s},setPrivacyPolicyUrl(s){re.privacyPolicyUrl=s},setCustomWallets(s){re.customWallets=s},setIsSiweEnabled(s){re.isSiweEnabled=s},setIsUniversalProvider(s){re.isUniversalProvider=s},setSdkVersion(s){re.sdkVersion=s},setMetadata(s){re.metadata=s},setDisableAppend(s){re.disableAppend=s},setEIP6963Enabled(s){re.enableEIP6963=s},setDebug(s){re.debug=s},setEnableWalletConnect(s){re.enableWalletConnect=s},setEnableWalletGuide(s){re.enableWalletGuide=s},setEnableAuthLogger(s){re.enableAuthLogger=s},setEnableWallets(s){re.enableWallets=s},setHasMultipleAddresses(s){re.hasMultipleAddresses=s},setSIWX(s){re.siwx=s},setConnectMethodsOrder(s){re.features={...re.features,connectMethodsOrder:s}},setWalletFeaturesOrder(s){re.features={...re.features,walletFeaturesOrder:s}},setSocialsOrder(s){re.features={...re.features,socials:s}},setCollapseWallets(s){re.features={...re.features,collapseWallets:s}},setEnableEmbedded(s){re.enableEmbedded=s},setAllowUnsupportedChain(s){re.allowUnsupportedChain=s},setManualWCControl(s){re.manualWCControl=s},setEnableNetworkSwitch(s){re.enableNetworkSwitch=s},setDefaultAccountTypes(s={}){Object.entries(s).forEach(([e,t])=>{t&&(re.defaultAccountTypes[e]=t)})},setUniversalProviderConfigOverride(s){re.universalProviderConfigOverride=s},getUniversalProviderConfigOverride(){return re.universalProviderConfigOverride},getSnapshot(){return k.snapshot(re)}},Ei=k.proxy({message:"",variant:"info",open:!1}),yo={state:Ei,subscribeKey(s,e){return k.subscribeKey(Ei,s,e)},open(s,e){const{debug:t}=R.state,{shortMessage:i,longMessage:r}=s;t&&(Ei.message=i,Ei.variant=e,Ei.open=!0),r&&console.error(typeof r=="function"?r():r)},close(){Ei.open=!1,Ei.message="",Ei.variant="info"}},GO=le.getAnalyticsUrl(),YO=new vc({baseUrl:GO,clientId:null}),QO=["MODAL_CREATED"],ri=k.proxy({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),qe={state:ri,subscribe(s){return k.subscribe(ri,()=>s(ri))},getSdkProperties(){const{projectId:s,sdkType:e,sdkVersion:t}=R.state;return{projectId:s,st:e,sv:t||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(s){try{const e=ie.state.address;if(QO.includes(s.data.event)||typeof window>"u")return;await YO.post({path:"/e",params:qe.getSdkProperties(),body:{eventId:le.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:s.timestamp,props:{...s.data,address:e}}}),ri.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===se.HTTP_STATUS_CODES.FORBIDDEN&&!ri.reportedErrors.FORBIDDEN&&(yo.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${lo()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),ri.reportedErrors.FORBIDDEN=!0)}},sendEvent(s){var e;ri.timestamp=Date.now(),ri.data=s,(e=R.state.features)!=null&&e.analytics&&qe._sendAnalyticsEvent(ri)}},JO=le.getApiUrl(),Lt=new vc({baseUrl:JO,clientId:null}),ZO="40",Ap="4",XO=20,Oe=k.proxy({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),he={state:Oe,subscribeKey(s,e){return k.subscribeKey(Oe,s,e)},_getSdkProperties(){const{projectId:s,sdkType:e,sdkVersion:t}=R.state;return{projectId:s,st:e||"appkit",sv:t||"html-wagmi-4.2.2"}},_filterOutExtensions(s){return R.state.isUniversalProvider?s.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):s},async _fetchWalletImage(s){const e=`${Lt.baseUrl}/getWalletImage/${s}`,t=await Lt.getBlob({path:e,params:he._getSdkProperties()});Es.setWalletImage(s,URL.createObjectURL(t))},async _fetchNetworkImage(s){const e=`${Lt.baseUrl}/public/getAssetImage/${s}`,t=await Lt.getBlob({path:e,params:he._getSdkProperties()});Es.setNetworkImage(s,URL.createObjectURL(t))},async _fetchConnectorImage(s){const e=`${Lt.baseUrl}/public/getAssetImage/${s}`,t=await Lt.getBlob({path:e,params:he._getSdkProperties()});Es.setConnectorImage(s,URL.createObjectURL(t))},async _fetchCurrencyImage(s){const e=`${Lt.baseUrl}/public/getCurrencyImage/${s}`,t=await Lt.getBlob({path:e,params:he._getSdkProperties()});Es.setCurrencyImage(s,URL.createObjectURL(t))},async _fetchTokenImage(s){const e=`${Lt.baseUrl}/public/getTokenImage/${s}`,t=await Lt.getBlob({path:e,params:he._getSdkProperties()});Es.setTokenImage(s,URL.createObjectURL(t))},async fetchNetworkImages(){const s=I.getAllRequestedCaipNetworks(),e=s==null?void 0:s.map(({assets:t})=>t==null?void 0:t.imageId).filter(Boolean).filter(t=>!Kh.getNetworkImageById(t));e&&await Promise.allSettled(e.map(t=>he._fetchNetworkImage(t)))},async fetchConnectorImages(){const{connectors:s}=ce.state,e=s.map(({imageId:t})=>t).filter(Boolean);await Promise.allSettled(e.map(t=>he._fetchConnectorImage(t)))},async fetchCurrencyImages(s=[]){await Promise.allSettled(s.map(e=>he._fetchCurrencyImage(e)))},async fetchTokenImages(s=[]){await Promise.allSettled(s.map(e=>he._fetchTokenImage(e)))},async fetchFeaturedWallets(){const{featuredWalletIds:s}=R.state;if(s!=null&&s.length){const{data:e}=await Lt.get({path:"/getWallets",params:{...he._getSdkProperties(),page:"1",entries:s!=null&&s.length?String(s.length):Ap,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=>he._fetchWalletImage(i))),Oe.featured=e,Oe.allFeatured=e}},async fetchRecommendedWallets(){try{Oe.isFetchingRecommendedWallets=!0;const{includeWalletIds:s,excludeWalletIds:e,featuredWalletIds:t}=R.state,i=[...e??[],...t??[]].filter(Boolean),r=I.getRequestedCaipNetworkIds().join(","),{data:n,count:o}=await Lt.get({path:"/getWallets",params:{...he._getSdkProperties(),page:"1",chains:r,entries:Ap,include:s==null?void 0:s.join(","),exclude:i==null?void 0:i.join(",")}}),a=X.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=>he._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}=R.state,r=I.getRequestedCaipNetworkIds().join(","),n=[...Oe.recommended.map(({id:l})=>l),...t??[],...i??[]].filter(Boolean),{data:o,count:a}=await Lt.get({path:"/getWallets",params:{...he._getSdkProperties(),page:String(s),entries:ZO,chains:r,include:e==null?void 0:e.join(","),exclude:n.join(",")}}),c=o.slice(0,XO).map(l=>l.image_id).filter(Boolean);await Promise.allSettled(c.map(l=>he._fetchWalletImage(l))),Oe.wallets=le.uniqueBy([...Oe.wallets,...he._filterOutExtensions(o)],"id"),Oe.count=a>Oe.count?a:Oe.count,Oe.page=s},async initializeExcludedWallets({ids:s}){const e=I.getRequestedCaipNetworkIds().join(","),{data:t}=await Lt.get({path:"/getWallets",params:{...he._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}=R.state;Oe.search=[];const r=I.getRequestedCaipNetworkIds().join(","),{data:n}=await Lt.get({path:"/getWallets",params:{...he._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(",")}});qe.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=>he._fetchWalletImage(a)),le.wait(300)]),Oe.search=he._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&&he.initPromise("connectorImages",he.fetchConnectorImages),e&&he.initPromise("featuredWallets",he.fetchFeaturedWallets),t&&he.initPromise("recommendedWallets",he.fetchRecommendedWallets),i&&he.initPromise("networkImages",he.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(r)},prefetchAnalyticsConfig(){var s;(s=R.state.features)!=null&&s.analytics&&he.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:s}=await Lt.get({path:"/getAnalyticsConfig",params:he._getSdkProperties()});R.setFeatures({analytics:s})}catch{R.setFeatures({analytics:!1})}},setFilterByNamespace(s){if(!s){Oe.featured=Oe.allFeatured,Oe.recommended=Oe.allRecommended;return}const e=I.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))})}},Te=k.proxy({view:"Connect",history:["Connect"],transactionStack:[]}),Me={state:Te,subscribeKey(s,e){return k.subscribeKey(Te,s,e)},pushTransactionStack(s){Te.transactionStack.push(s)},popTransactionStack(s){var t,i;const e=Te.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=Te.history.indexOf("ConnectingSiwe");n>0?this.goBackToIndex(n-1):(ot.close(),Te.history=[])}else e.view&&this.reset(e.view);(i=e==null?void 0:e.onSuccess)==null||i.call(e)}},push(s,e){s!==Te.view&&(Te.view=s,Te.history.push(s),Te.data=e)},reset(s,e){Te.view=s,Te.history=[s],Te.data=e},replace(s,e){Te.history.at(-1)===s||(Te.view=s,Te.history[Te.history.length-1]=s,Te.data=e)},goBack(){var e;const s=!I.state.activeCaipAddress&&this.state.view==="ConnectingFarcaster";if(Te.history.length>1&&!Te.history.includes("UnsupportedChain")){Te.history.pop();const[t]=Te.history.slice(-1);t&&(Te.view=t)}else ot.close();(e=Te.data)!=null&&e.wallet&&(Te.data.wallet=void 0),setTimeout(()=>{var t,i,r;if(s){ie.setFarcasterUrl(void 0,I.state.activeChain);const n=ce.getAuthConnector();(t=n==null?void 0:n.provider)==null||t.reload();const o=k.snapshot(R.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(Te.history.length>1){Te.history=Te.history.slice(0,s+1);const[e]=Te.history.slice(-1);e&&(Te.view=e)}}},ni=k.proxy({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Ft={state:ni,subscribe(s){return k.subscribe(ni,()=>s(ni))},setThemeMode(s){ni.themeMode=s;try{const e=ce.getAuthConnector();if(e){const t=Ft.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:s,themeVariables:t,w3mThemeVariables:Oi(t,s)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(s){ni.themeVariables={...ni.themeVariables,...s};try{const e=ce.getAuthConnector();if(e){const t=Ft.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:Oi(ni.themeVariables,ni.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return k.snapshot(ni)}},ny={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0},xe=k.proxy({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...ny}}),ce={state:xe,subscribe(s){return k.subscribe(xe,()=>{s(xe)})},subscribeKey(s,e){return k.subscribeKey(xe,s,e)},initialize(s){s.forEach(e=>{const t=X.getConnectedConnectorId(e);t&&this.setConnectorId(t,e)})},setActiveConnector(s){s&&(xe.activeConnector=k.ref(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(k.ref(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)===se.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===se.CONNECTOR_ID.AUTH){const r=s,n=k.snapshot(R.state),o=Ft.getSnapshot().themeMode,a=Ft.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:Oi(a,o)}),this.setConnectors([s])}else this.setConnectors([s])},getAuthConnector(s){var i;const e=s||I.state.activeChain,t=xe.connectors.find(r=>r.id===se.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===I.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=k.snapshot(R.state),i=Ft.getSnapshot().themeMode,r=Ft.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:Oi(r,i)})},getConnectorsByNamespace(s){const e=xe.allConnectors.filter(t=>t.chain===s);return this.mergeMultiChainConnectors(e)},selectWalletConnector(s){const e=ce.getConnector(s.id,s.rdns);I.state.activeChain===se.CHAIN.SOLANA&&WO.handleSolanaDeeplinkRedirect((e==null?void 0:e.name)||s.name||""),e?Me.push("ConnectingExternal",{connector:e}):Me.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),he.setFilterByNamespace(s)},setConnectorId(s,e){s&&(xe.activeConnectorIds={...xe.activeConnectorIds,[e]:s},X.setConnectedConnectorId(e,s))},removeConnectorId(s){xe.activeConnectorIds={...xe.activeConnectorIds,[s]:void 0},X.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={...ny}}};function ba(s,e){return ce.getConnectorId(s)===e}function ex(s){const e=Array.from(I.state.chains.keys());let t=[];return s?(t.push([s,I.state.chains.get(s)]),ba(s,se.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(i=>{i!==s&&ba(i,se.CONNECTOR_ID.WALLET_CONNECT)&&t.push([i,I.state.chains.get(i)])}):ba(s,se.CONNECTOR_ID.AUTH)&&e.forEach(i=>{i!==s&&ba(i,se.CONNECTOR_ID.AUTH)&&t.push([i,I.state.chains.get(i)])})):t=Array.from(I.state.chains.entries()),t}var tx=Object.defineProperty,sx=(s,e,t)=>e in s?tx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Np=(s,e,t)=>sx(s,typeof e!="symbol"?e+"":e,t);class ix extends u.IEvents{constructor(e){super(),this.opts=e,Np(this,"protocol","wc"),Np(this,"version",2)}}var rx=Object.defineProperty,nx=(s,e,t)=>e in s?rx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ox=(s,e,t)=>nx(s,e+"",t);let ax=class extends u.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,ox(this,"records",new Map)}},cx=class{constructor(e,t){this.logger=e,this.core=t}};class lx extends u.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}let hx=class extends u.IEvents{constructor(e){super()}},ux=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},dx=class extends u.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},px=class extends u.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},gx=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},fx=class{constructor(e,t){this.projectId=e,this.logger=t}},wx=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};var yx=Object.defineProperty,mx=(s,e,t)=>e in s?yx(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,_p=(s,e,t)=>mx(s,typeof e!="symbol"?e+"":e,t);let bx=class{constructor(e){this.opts=e,_p(this,"protocol","wc"),_p(this,"version",2)}},vx=class{constructor(e){this.client=e}};const Ix="https://secure.walletconnect.org/sdk";typeof N.dist.process<"u"&&typeof N.dist.process.env<"u"&&N.dist.process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL;typeof N.dist.process<"u"&&typeof N.dist.process.env<"u"&&N.dist.process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL;typeof N.dist.process<"u"&&typeof N.dist.process.env<"u"&&N.dist.process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const Si={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"}},Zi=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),ut=k.proxy({...Zi}),vt={state:ut,subscribeKey(s,e){return k.subscribeKey(ut,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=le.parseError(s);this._showMessage({message:e,variant:"error"})},hide(){ut.message=Zi.message,ut.variant=Zi.variant,ut.svg=Zi.svg,ut.open=Zi.open,ut.autoClose=Zi.autoClose},_showMessage({message:s,svg:e,variant:t="success",autoClose:i=Zi.autoClose}){ut.open?(ut.open=!1,setTimeout(()=>{ut.message=s,ut.variant=t,ut.svg=e,ut.open=!0,ut.autoClose=i},150)):(ut.message=s,ut.variant=t,ut.svg=e,ut.open=!0,ut.autoClose=i)}},mn={getSIWX(){return R.state.siwx},async initializeIfEnabled(){var n;const s=R.state.siwx,e=I.getActiveCaipAddress();if(!(s&&e))return;const[t,i,r]=e.split(":");if(I.checkIfSupportedNetwork(t))try{if((await s.getSessions(`${t}:${i}`,r)).length)return;await ot.open({view:"SIWXSignMessage"})}catch(o){console.error("SIWXUtil:initializeIfEnabled",o),qe.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await((n=Fe._getClient())==null?void 0:n.disconnect().catch(console.error)),Me.reset("Connect"),vt.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const s=R.state.siwx,e=le.getPlainAddress(I.getActiveCaipAddress()),t=I.getActiveCaipNetwork(),i=Fe._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();ce.getConnectorId(t.chainNamespace)===se.CONNECTOR_ID.AUTH&&Me.pushTransactionStack({view:null,goBack:!1,replace:!0});const a=await i.signMessage(n);await s.addSession({data:r,message:n,signature:a}),ot.close(),qe.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){const n=this.getSIWXEventProperties();(!ot.state.open||Me.state.view==="ApproveTransaction")&&await ot.open({view:"SIWXSignMessage"}),n.isSmartAccount?vt.showError("This application might not support Smart Accounts"):vt.showError("Signature declined"),qe.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 Fe.disconnect():ot.close(),Me.reset("Connect"),qe.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getSessions(){const s=R.state.siwx,e=le.getPlainAddress(I.getActiveCaipAddress()),t=I.getActiveCaipNetwork();return s&&e&&t?s.getSessions(t.caipNetworkId,e):[]},async isSIWXCloseDisabled(){var e;const s=this.getSIWX();if(s){const t=Me.state.view==="ApproveTransaction",i=Me.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=mn.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=I.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(vt.showLoading("Authenticating...",{autoClose:!1}),ie.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(d=>{const p=s.client.formatAuthMessage({request:d.p,iss:d.p.iss});return{data:{...d.p,accountAddress:d.p.iss.split(":").slice(-1).join(""),chainId:d.p.iss.split(":").slice(2,4).join(":"),uri:d.p.aud,version:d.p.version||n.version,expirationTime:d.p.exp,issuedAt:d.p.iat,notBefore:d.p.nbf},message:p,signature:d.s.s,cacao:d}});try{await i.setSessions(h),qe.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:mn.getSIWXEventProperties()})}catch(d){throw console.error("SIWX:universalProviderAuth - failed to set sessions",d),qe.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:mn.getSIWXEventProperties()}),await s.disconnect().catch(console.error),d}finally{vt.hide()}}return!0},getSIWXEventProperties(){var s;return{network:((s=I.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||"",isSmartAccount:ie.state.preferredAccountType===Si.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const s=this.getSIWX();s&&await s.setSessions([])}},He=k.proxy({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Ex={state:He,subscribe(s){return k.subscribe(He,()=>s(He))},setLastNetworkInView(s){He.lastNetworkInView=s},async fetchTransactions(s,e){var t;if(!s)throw new Error("Transactions can't be fetched without an accountAddress");He.loading=!0;try{const i=await ne.fetchTransactions({account:s,cursor:He.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:(t=I.state.activeCaipNetwork)==null?void 0:t.caipNetworkId}),r=this.filterSpamTransactions(i.data),n=this.filterByConnectedChain(r),o=[...He.transactions,...n];He.loading=!1,e==="coinbase"?He.coinbaseTransactions=this.groupTransactionsByYearAndMonth(He.coinbaseTransactions,i.data):(He.transactions=o,He.transactionsByYear=this.groupTransactionsByYearAndMonth(He.transactionsByYear,n)),He.empty=o.length===0,He.next=i.next?i.next:void 0}catch{qe.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:s,projectId:R.state.projectId,cursor:He.next,isSmartAccount:ie.state.preferredAccountType===Si.ACCOUNT_TYPES.SMART_ACCOUNT}}),vt.showError("Failed to fetch transactions"),He.loading=!1,He.empty=!0,He.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=I.state.activeCaipNetwork)==null?void 0:i.caipNetworkId;return s.filter(r=>r.metadata.chain===e)},clearCursor(){He.next=void 0},resetTransactions(){He.transactions=[],He.transactionsByYear={},He.lastNetworkInView=void 0,He.loading=!1,He.empty=!1,He.next=void 0}},We=k.proxy({wcError:!1,buffering:!1,status:"disconnected"});let zr;const Fe={state:We,subscribeKey(s,e){return k.subscribeKey(We,s,e)},_getClient(){return We._client},setClient(s){We._client=k.ref(s)},async connectWalletConnect(){var s,e,t,i;if(le.isTelegram()||le.isSafari()&&le.isIos()){if(zr){await zr,zr=void 0;return}if(!le.isPairingExpired(We==null?void 0:We.wcPairingExpiry)){const r=We.wcUri;We.wcUri=r;return}zr=(e=(s=this._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:e.call(s).catch(()=>{}),this.state.status="connecting",await zr,zr=void 0,We.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&&I.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||I.state.activeChain;e&&ce.setConnectorId(s.id,e)},async setPreferredAccountType(s){var t;ot.setLoading(!0,I.state.activeChain);const e=ce.getAuthConnector();e&&(await(e==null?void 0:e.provider.setPreferredAccount(s)),await this.reconnectExternal(e),ot.setLoading(!1,I.state.activeChain),qe.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:s,network:((t=I.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(){We.wcUri=void 0,We.wcPairingExpiry=void 0,We.wcLinking=void 0,We.recentWallet=void 0,We.status="disconnected",Ex.resetTransactions(),X.deleteWalletConnectDeepLink()},resetUri(){We.wcUri=void 0,We.wcPairingExpiry=void 0},finalizeWcConnection(){var t,i;const{wcLinking:s,recentWallet:e}=Fe.state;s&&X.setWalletConnectDeepLink(s),e&&X.setAppKitRecent(e),qe.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:s?"mobile":"qrcode",name:((i=(t=Me.state.data)==null?void 0:t.wallet)==null?void 0:i.name)||"Unknown"}})},setWcBasic(s){We.wcBasic=s},setUri(s){We.wcUri=s,We.wcPairingExpiry=le.getPairingExpiry()},setWcLinking(s){We.wcLinking=s},setWcError(s){We.wcError=s,We.buffering=!1},setRecentWallet(s){We.recentWallet=s},setBuffering(s){We.buffering=s},setStatus(s){We.status=s},async disconnect(s){try{ot.setLoading(!0,s),await mn.clearSessions(),await I.disconnect(s),ot.setLoading(!1,s),ce.setFilterByNamespace(void 0)}catch{throw new Error("Failed to disconnect")}}},Jn=k.proxy({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),gi={state:Jn,subscribe(s){return k.subscribe(Jn,()=>s(Jn))},set(s){Object.assign(Jn,{...Jn,...s})}},il={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 wn.formatUnits(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"}},Cp={async getMyTokensWithBalance(s){const e=ie.state.address,t=I.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 ne.getBalance(e,t.caipNetworkId,s);return this.filterLowQualityTokens(i.balances)},async getEIP155Balances(s,e){var t,i;try{const r=il.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),n=await Fe.getCapabilities(s);if(!((i=(t=n==null?void 0:n[r])==null?void 0:t.assetDiscovery)!=null&&i.supported))return null;const o=await Fe.walletGetAssets({account:s,chainFilter:[r]});return il.isWalletGetAssetsResponse(o)?(o[r]||[]).map(c=>il.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:I.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]}},me=k.proxy({tokenBalances:[],loading:!1}),Sp={state:me,subscribe(s){return k.subscribe(me,()=>s(me))},subscribeKey(s,e){return k.subscribeKey(me,s,e)},setToken(s){s&&(me.token=k.ref(s))},setTokenAmount(s){me.sendTokenAmount=s},setReceiverAddress(s){me.receiverAddress=s},setReceiverProfileImageUrl(s){me.receiverProfileImageUrl=s},setReceiverProfileName(s){me.receiverProfileName=s},setGasPrice(s){me.gasPrice=s},setGasPriceInUsd(s){me.gasPriceInUSD=s},setNetworkBalanceInUsd(s){me.networkBalanceInUSD=s},setLoading(s){me.loading=s},sendToken(){var s;switch((s=I.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?(qe.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:ie.state.preferredAccountType===Si.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token.address,amount:this.state.sendTokenAmount,network:((e=I.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)&&(qe.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:ie.state.preferredAccountType===Si.ACCOUNT_TYPES.SMART_ACCOUNT,token:(i=this.state.token)==null?void 0:i.symbol,amount:this.state.sendTokenAmount,network:((r=I.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;me.loading=!0;const e=(n=I.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,t=(o=I.state.activeCaipNetwork)==null?void 0:o.chainNamespace,i=I.state.activeCaipAddress,r=i?le.getPlainAddress(i):void 0;if(me.lastRetry&&!le.isAllowedRetry(me.lastRetry,30*Vt.ONE_SEC_MS))return me.loading=!1,[];try{if(r&&e&&t){const a=await Cp.getMyTokensWithBalance();return me.tokenBalances=a,me.lastRetry=void 0,a}}catch(a){me.lastRetry=Date.now(),s==null||s(a),vt.showError("Token Balance Unavailable")}finally{me.loading=!1}return[]},fetchNetworkBalance(){if(me.tokenBalances.length===0)return;const s=Cp.mapBalancesToSwapTokens(me.tokenBalances);if(!s)return;const e=s.find(t=>t.address===I.getActiveNetworkTokenAddress());e&&(me.networkBalanceInUSD=e?ma.multiply(e.quantity.numeric,e.price).toString():"0")},isInsufficientNetworkTokenForGas(s,e){const t=e||"0";return ma.bigNumber(s).eq(0)?!0:ma.bigNumber(ma.bigNumber(t)).gt(s)},hasInsufficientGasFunds(){let s=!0;return ie.state.preferredAccountType===Si.ACCOUNT_TYPES.SMART_ACCOUNT?s=!1:me.networkBalanceInUSD&&(s=this.isInsufficientNetworkTokenForGas(me.networkBalanceInUSD,me.gasPriceInUSD)),s},async sendNativeToken(s){var n,o,a,c;Me.pushTransactionStack({view:"Account",goBack:!1});const e=s.receiverAddress,t=ie.state.address,i=Fe.parseUnits(s.sendTokenAmount.toString(),Number(s.decimals)),r="0x";try{await Fe.sendTransaction({chainNamespace:"eip155",to:e,address:t,data:r,value:i??BigInt(0),gasPrice:s.gasPrice}),vt.showSuccess("Transaction started"),qe.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:ie.state.preferredAccountType===Si.ACCOUNT_TYPES.SMART_ACCOUNT,token:((n=this.state.token)==null?void 0:n.symbol)||"",amount:s.sendTokenAmount,network:((o=I.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";qe.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:h,isSmartAccount:ie.state.preferredAccountType===Si.ACCOUNT_TYPES.SMART_ACCOUNT,token:((a=this.state.token)==null?void 0:a.symbol)||"",amount:s.sendTokenAmount,network:((c=I.state.activeCaipNetwork)==null?void 0:c.caipNetworkId)||""}}),vt.showError("Something went wrong")}},async sendERC20Token(s){var t,i;Me.pushTransactionStack({view:"Account",goBack:!1});const e=Fe.parseUnits(s.sendTokenAmount.toString(),Number(s.decimals));try{if(ie.state.address&&s.sendTokenAmount&&s.receiverAddress&&s.tokenAddress){const r=le.getPlainAddress(s.tokenAddress);await Fe.writeContract({fromAddress:ie.state.address,tokenAddress:r,args:[s.receiverAddress,e??BigInt(0)],method:"transfer",abi:HO.getERC20Abi(r),chainNamespace:"eip155"}),vt.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";qe.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:n,isSmartAccount:ie.state.preferredAccountType===Si.ACCOUNT_TYPES.SMART_ACCOUNT,token:((t=this.state.token)==null?void 0:t.symbol)||"",amount:s.sendTokenAmount,network:((i=I.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||""}}),vt.showError("Something went wrong")}},sendSolanaToken(){if(!this.state.sendTokenAmount||!this.state.receiverAddress){vt.showError("Please enter a valid amount and receiver address");return}Me.pushTransactionStack({view:"Account",goBack:!1}),Fe.sendTransaction({chainNamespace:"solana",to:this.state.receiverAddress,value:this.state.sendTokenAmount}).then(()=>{this.resetSend(),ie.fetchTokenBalance()}).catch(s=>{vt.showError("Failed to send transaction. Please try again."),console.error("SendController:sendToken - failed to send solana transaction",s)})},resetSend(){me.token=void 0,me.sendTokenAmount=void 0,me.receiverAddress=void 0,me.receiverProfileImageUrl=void 0,me.receiverProfileName=void 0,me.loading=!1,me.tokenBalances=[]}},rl={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},va={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},F=k.proxy({chains:k.proxyMap(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),I={state:F,subscribe(s){return k.subscribe(F,()=>{s(F)})},subscribeKey(s,e){return k.subscribeKey(F,s,e)},subscribeChainProp(s,e,t){let i;return k.subscribe(F.chains,()=>{var n;const r=t||F.activeChain;if(r){const o=(n=F.chains.get(r))==null?void 0:n[s];i!==o&&(i=o,e(o))}})},initialize(s,e,t){const{chainId:i,namespace:r}=X.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)&&(F.noAdapters=!0),F.noAdapters||(F.activeChain=a==null?void 0:a.namespace,F.activeCaipNetwork=n,this.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:n}),F.activeChain&&gi.set({activeChain:a==null?void 0:a.namespace})),c.forEach(l=>{const h=e==null?void 0:e.filter(d=>d.chainNamespace===l);I.state.chains.set(l,{namespace:l,networkState:k.proxy({...va,caipNetwork:h==null?void 0:h[0]}),accountState:k.proxy(rl),caipNetworks:h??[],...t}),this.setRequestedCaipNetworks(h??[],l)})},removeAdapter(s){var e,t;if(F.activeChain===s){const i=Array.from(F.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)}}F.chains.delete(s)},addAdapter(s,{networkControllerClient:e,connectionControllerClient:t},i){F.chains.set(s.namespace,{namespace:s.namespace,networkState:{...va,caipNetwork:i[0]},accountState:rl,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=F.chains.get(s.chainNamespace);if(e){const i=[...e.caipNetworks||[]];(t=e.caipNetworks)!=null&&t.find(r=>r.id===s.id)||i.push(s),F.chains.set(s.chainNamespace,{...e,caipNetworks:i}),this.setRequestedCaipNetworks(i,s.chainNamespace)}},removeNetwork(s,e){var i,r,n;const t=F.chains.get(s);if(t){const o=((i=F.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]),F.chains.set(s,{...t,caipNetworks:a}),this.setRequestedCaipNetworks(a||[],s)}},setAdapterNetworkState(s,e){const t=F.chains.get(s);t&&(t.networkState={...t.networkState||va,...e},F.chains.set(s,t))},setChainAccountData(s,e,t=!0){if(!s)throw new Error("Chain is required to update chain account data");const i=F.chains.get(s);if(i){const r={...i.accountState||rl,...e};F.chains.set(s,{...i,accountState:r}),(F.chains.size===1||F.activeChain===s)&&(e.caipAddress&&(F.activeCaipAddress=e.caipAddress),ie.replaceState(r))}},setChainNetworkData(s,e){if(!s)return;const t=F.chains.get(s);if(t){const i={...t.networkState||va,...e};F.chains.set(s,{...t,networkState:i})}},setAccountProp(s,e,t,i=!0){this.setChainAccountData(t,{[s]:e},i),s==="status"&&e==="disconnected"&&t&&ce.removeConnectorId(t)},setActiveNamespace(s){var i,r;F.activeChain=s;const e=s?F.chains.get(s):void 0,t=(i=e==null?void 0:e.networkState)==null?void 0:i.caipNetwork;t!=null&&t.id&&s&&(F.activeCaipAddress=(r=e==null?void 0:e.accountState)==null?void 0:r.caipAddress,F.activeCaipNetwork=t,this.setChainNetworkData(s,{caipNetwork:t}),X.setActiveCaipNetworkId(t==null?void 0:t.caipNetworkId),gi.set({activeChain:s,selectedNetworkId:t==null?void 0:t.caipNetworkId}))},setActiveCaipNetwork(s){var i,r,n;if(!s)return;F.activeChain!==s.chainNamespace&&this.setIsSwitchingNamespace(!0);const e=F.chains.get(s.chainNamespace);F.activeChain=s.chainNamespace,F.activeCaipNetwork=s,this.setChainNetworkData(s.chainNamespace,{caipNetwork:s}),(i=e==null?void 0:e.accountState)!=null&&i.address?F.activeCaipAddress=`${s.chainNamespace}:${s.id}:${(r=e==null?void 0:e.accountState)==null?void 0:r.address}`:F.activeCaipAddress=void 0,this.setAccountProp("caipAddress",F.activeCaipAddress,s.chainNamespace),e&&ie.replaceState(e.accountState),Sp.resetSend(),gi.set({activeChain:F.activeChain,selectedNetworkId:(n=F.activeCaipNetwork)==null?void 0:n.caipNetworkId}),X.setActiveCaipNetworkId(s.caipNetworkId),!this.checkIfSupportedNetwork(s.chainNamespace)&&R.state.enableNetworkSwitch&&!R.state.allowUnsupportedChain&&!Fe.state.wcBasic&&this.showUnsupportedChainUI()},addCaipNetwork(s){var t;if(!s)return;const e=F.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!==I.state.activeChain,t=(r=I.getNetworkData(s))==null?void 0:r.caipNetwork,i=I.getCaipNetworkByNamespace(s,t==null?void 0:t.id);e&&i&&await I.switchActiveNetwork(i)},async switchActiveNetwork(s){var r;const e=I.state.chains.get(I.state.activeChain);!((r=e==null?void 0:e.caipNetworks)!=null&&r.some(n=>{var o;return n.id===((o=F.activeCaipNetwork)==null?void 0:o.id)}))&&Me.goBack();const i=this.getNetworkControllerClient(s.chainNamespace);i&&(await i.switchCaipNetwork(s),qe.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:s.caipNetworkId}}))},getNetworkControllerClient(s){const e=s||F.activeChain,t=F.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||F.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const t=F.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=F.activeChain;if(e&&(t=e),!t)return;const i=(r=F.chains.get(t))==null?void 0:r.accountState;if(i)return i[s]},getNetworkProp(s,e){var i;const t=(i=F.chains.get(e))==null?void 0:i.networkState;if(t)return t[s]},getRequestedCaipNetworks(s){const e=F.chains.get(s),{approvedCaipNetworkIds:t=[],requestedCaipNetworks:i=[]}=(e==null?void 0:e.networkState)||{};return le.sortRequestedNetworks(t,i)},getAllRequestedCaipNetworks(){const s=[];return F.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 F.chains.forEach(e=>{const t=this.getApprovedCaipNetworkIds(e.namespace);s.push(...t)}),s},getActiveCaipNetwork(){return F.activeCaipNetwork},getActiveCaipAddress(){return F.activeCaipAddress},getApprovedCaipNetworkIds(s){var i;const e=F.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||F.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(!F.activeChain)return!0;const e=this.getRequestedCaipNetworks(F.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=ry.caipNetworkIdToNumber((i=F.activeCaipNetwork)==null?void 0:i.caipNetworkId),e=F.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=F.activeCaipNetwork)==null?void 0:i.chainNamespace)||"eip155",e=((r=F.activeCaipNetwork)==null?void 0:r.id)||1,t=Vt.NATIVE_TOKEN_ADDRESS[s];return`${s}:${e}:${t}`},showUnsupportedChainUI(){ot.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const s=F.activeCaipNetwork;return!!(s!=null&&s.chainNamespace&&Vt.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");F.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"}),ce.removeConnectorId(e)},async disconnect(s){const e=ex(s);try{Sp.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}`)}}));Fe.resetWcConnection();const i=t.filter(r=>r.status==="rejected");if(i.length>0)throw new Error(i.map(r=>r.reason.message).join(", "));X.deleteConnectedSocialProvider(),s?ce.removeConnectorId(s):ce.resetConnectorIds(),qe.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:s||"all"}})}catch(t){console.error(t.message||"Failed to disconnect chains"),qe.sendEvent({type:"track",event:"DISCONNECT_ERROR",properties:{message:t.message||"Failed to disconnect chains"}})}},setIsSwitchingNamespace(s){F.isSwitchingNamespace=s},getFirstCaipNetworkSupportsAuthConnector(){var t,i;const s=[];let e;if(F.chains.forEach(r=>{se.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=F.chains.get(r))==null?void 0:t.caipNetworks)==null?void 0:i[0]:void 0,e}},getAccountData(s){var e;return s?(e=I.state.chains.get(s))==null?void 0:e.accountState:ie.state},getNetworkData(s){var t;const e=s||F.activeChain;if(e)return(t=I.state.chains.get(e))==null?void 0:t.networkState},getCaipNetworkByNamespace(s,e){var r,n,o;if(!s)return;const t=I.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=ce.state.filterByNamespace;return(s?[F.chains.get(s)]:Array.from(F.chains.values())).flatMap(t=>(t==null?void 0:t.caipNetworks)||[]).map(t=>t.caipNetworkId)}},Ax={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"}]}]},oy=le.getBlockchainApiUrl(),is=k.proxy({clientId:null,api:new vc({baseUrl:oy,clientId:null}),supportedChains:{http:[],ws:[]}}),ne={state:is,async get(s){const{st:e,sv:t}=ne.getSdkProperties(),i=R.state.projectId,r={...s.params||{},st:e,sv:t,projectId:i};return is.api.get({...s,params:r})},getSdkProperties(){const{sdkType:s,sdkVersion:e}=R.state;return{st:s||"unknown",sv:e||"unknown"}},async isNetworkSupported(s){if(!s)return!1;try{is.supportedChains.http.length||await ne.getSupportedNetworks()}catch{return!1}return is.supportedChains.http.includes(s)},async getSupportedNetworks(){const s=await ne.get({path:"v1/supported-chains"});return is.supportedChains=s,s},async fetchIdentity({address:s,caipNetworkId:e}){if(!await ne.isNetworkSupported(e))return{avatar:"",name:""};const i=X.getIdentityFromCacheForAddress(s);if(i)return i;const r=await ne.get({path:`/v1/identity/${s}`,params:{sender:I.state.activeCaipAddress?le.getPlainAddress(I.state.activeCaipAddress):void 0}});return X.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 ne.isNetworkSupported((a=I.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?ne.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 ne.isNetworkSupported((o=I.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?ne.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 ne.isNetworkSupported((t=I.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?ne.get({path:"/v1/convert/tokens",params:{chainId:s}}):{tokens:[]}},async fetchTokenPrice({addresses:s}){var t;return await ne.isNetworkSupported((t=I.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?is.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:s,projectId:R.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:s,userAddress:e}){var i;return await ne.isNetworkSupported((i=I.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?ne.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}=ne.getSdkProperties();if(!await ne.isNetworkSupported((r=I.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))throw new Error("Network not supported for Gas Price");return ne.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 ne.isNetworkSupported((o=I.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return is.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:s,eip155:{slippage:Vt.CONVERT_SLIPPAGE_TOLERANCE},projectId:R.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}=ne.getSdkProperties();if(!await ne.isNetworkSupported((o=I.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return ne.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}=ne.getSdkProperties();if(!await ne.isNetworkSupported((l=I.state.activeCaipNetwork)==null?void 0:l.caipNetworkId))return vt.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${s}`,a=X.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await ne.get({path:`/v1/account/${s}/balance`,params:{currency:"usd",chainId:e,forceUpdate:t,st:i,sv:r}});return X.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(s){var t;return await ne.isNetworkSupported((t=I.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?ne.get({path:`/v1/profile/account/${s}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:s}){var t;return await ne.isNetworkSupported((t=I.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?ne.get({path:`/v1/profile/reverse/${s}`,params:{sender:ie.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(s){var t;return await ne.isNetworkSupported((t=I.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?ne.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 ne.isNetworkSupported((n=I.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?is.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 ne.isNetworkSupported((a=I.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await is.api.post({path:"/v1/generators/onrampurl",params:{projectId:R.state.projectId},body:{destinationWallets:s,defaultNetwork:t,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:i,presetFiatAmount:r}})).url:""},async getOnrampOptions(){var e;if(!await ne.isNetworkSupported((e=I.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await ne.get({path:"/v1/onramp/options"})}catch{return Ax}},async getOnrampQuote({purchaseCurrency:s,paymentCurrency:e,amount:t,network:i}){var r;try{return await ne.isNetworkSupported((r=I.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?await is.api.post({path:"/v1/onramp/quote",params:{projectId:R.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 ne.isNetworkSupported((t=I.state.activeCaipNetwork)==null?void 0:t.caipNetworkId)?ne.get({path:`/v1/sessions/${s}`}):[]},async revokeSmartSession(s,e,t){var r;return await ne.isNetworkSupported((r=I.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?is.api.post({path:`/v1/sessions/${s}/revoke`,params:{projectId:R.state.projectId},body:{pci:e,signature:t}}):{success:!1}},setClientId(s){is.clientId=s,is.api=new vc({baseUrl:oy,clientId:s})}},Hs=k.proxy({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),ie={state:Hs,replaceState(s){s&&Object.assign(Hs,k.ref(s))},subscribe(s){return I.subscribeChainProp("accountState",e=>{if(e)return s(e)})},subscribeKey(s,e,t){let i;return I.subscribeChainProp("accountState",r=>{if(r){const n=r[s];i!==n&&(i=n,e(n))}},t)},setStatus(s,e){I.setAccountProp("status",s,e)},getCaipAddress(s){return I.getAccountProp("caipAddress",s)},setCaipAddress(s,e){const t=s?le.getPlainAddress(s):void 0;e===I.state.activeChain&&(I.state.activeCaipAddress=s),I.setAccountProp("caipAddress",s,e),I.setAccountProp("address",t,e)},setBalance(s,e,t){I.setAccountProp("balance",s,t),I.setAccountProp("balanceSymbol",e,t)},setProfileName(s,e){I.setAccountProp("profileName",s,e)},setProfileImage(s,e){I.setAccountProp("profileImage",s,e)},setUser(s,e){I.setAccountProp("user",s,e)},setAddressExplorerUrl(s,e){I.setAccountProp("addressExplorerUrl",s,e)},setSmartAccountDeployed(s,e){I.setAccountProp("smartAccountDeployed",s,e)},setCurrentTab(s){I.setAccountProp("currentTab",s,I.state.activeChain)},setTokenBalance(s,e){s&&I.setAccountProp("tokenBalance",s,e)},setShouldUpdateToAddress(s,e){I.setAccountProp("shouldUpdateToAddress",s,e)},setAllAccounts(s,e){I.setAccountProp("allAccounts",s,e)},addAddressLabel(s,e,t){const i=I.getAccountProp("addressLabels",t)||new Map;i.set(s,e),I.setAccountProp("addressLabels",i,t)},removeAddressLabel(s,e){const t=I.getAccountProp("addressLabels",e)||new Map;t.delete(s),I.setAccountProp("addressLabels",t,e)},setConnectedWalletInfo(s,e){I.setAccountProp("connectedWalletInfo",s,e,!1)},setPreferredAccountType(s,e){I.setAccountProp("preferredAccountType",s,e)},setSocialProvider(s,e){s&&I.setAccountProp("socialProvider",s,e)},setSocialWindow(s,e){I.setAccountProp("socialWindow",s?k.ref(s):void 0,e)},setFarcasterUrl(s,e){I.setAccountProp("farcasterUrl",s,e)},async fetchTokenBalance(s){var n,o;Hs.balanceLoading=!0;const e=(n=I.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,t=(o=I.state.activeCaipNetwork)==null?void 0:o.chainNamespace,i=I.state.activeCaipAddress,r=i?le.getPlainAddress(i):void 0;if(Hs.lastRetry&&!le.isAllowedRetry(Hs.lastRetry,30*Vt.ONE_SEC_MS))return Hs.balanceLoading=!1,[];try{if(r&&e&&t){const c=(await ne.getBalance(r,e)).balances.filter(l=>l.quantity.decimals!=="0");return this.setTokenBalance(c,t),Hs.lastRetry=void 0,Hs.balanceLoading=!1,c}}catch(a){Hs.lastRetry=Date.now(),s==null||s(a),vt.showError("Token Balance Unavailable")}finally{Hs.balanceLoading=!1}return[]},resetAccount(s){I.resetAccount(s)}},Yt=k.proxy({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),ot={state:Yt,subscribe(s){return k.subscribe(Yt,()=>s(Yt))},subscribeKey(s,e){return k.subscribeKey(Yt,s,e)},async open(s){var r;const e=ie.state.status==="connected";Fe.state.wcBasic?he.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await he.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),s!=null&&s.namespace?(await I.switchActiveNamespace(s.namespace),ot.setLoading(!0,s.namespace)):ot.setLoading(!0),ce.setFilterByNamespace(s==null?void 0:s.namespace);const t=(r=I.getAccountData(s==null?void 0:s.namespace))==null?void 0:r.caipAddress;I.state.noAdapters&&!t?le.isMobile()?Me.reset("AllWallets"):Me.reset("ConnectingWalletConnectBasic"):s!=null&&s.view?Me.reset(s.view):t?Me.reset("Account"):Me.reset("Connect"),Yt.open=!0,gi.set({open:!0}),qe.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!t}})},close(){const s=R.state.enableEmbedded,e=!!I.state.activeCaipAddress;Yt.open&&qe.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),Yt.open=!1,ot.clearLoading(),s?e?Me.replace("Account"):Me.push("Connect"):gi.set({open:!1}),Fe.resetUri()},setLoading(s,e){e&&Yt.loadingNamespaceMap.set(e,s),Yt.loading=s,gi.set({loading:s})},clearLoading(){Yt.loadingNamespaceMap.clear(),Yt.loading=!1},shake(){Yt.shake||(Yt.shake=!0,setTimeout(()=>{Yt.shake=!1},500))}},Tp=2147483648,Nx={convertEVMChainIdToCoinType(s){if(s>=Tp)throw new Error("Invalid chainId");return(Tp|s)>>>0}},ws=k.proxy({suggestions:[],loading:!1}),ay={state:ws,subscribe(s){return k.subscribe(ws,()=>s(ws))},subscribeKey(s,e){return k.subscribeKey(ws,s,e)},async resolveName(s){var e,t;try{return await ne.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 ne.lookupEnsName(s),!0}catch{return!1}},async getSuggestions(s){try{ws.loading=!0,ws.suggestions=[];const e=await ne.getEnsNameSuggestions(s);return ws.suggestions=e.suggestions.map(t=>({...t,name:t.name}))||[],ws.suggestions}catch(e){const t=this.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(t)}finally{ws.loading=!1}},async getNamesForAddress(s){try{if(!I.state.activeCaipNetwork)return[];const t=X.getEnsFromCacheForAddress(s);if(t)return t;const i=await ne.reverseLookupEnsName({address:s});return X.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=I.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const t=ie.state.address,i=ce.getAuthConnector();if(!t||!i)throw new Error("Address or auth connector not found");ws.loading=!0;try{const r=JSON.stringify({name:s,attributes:{},timestamp:Math.floor(Date.now()/1e3)});Me.pushTransactionStack({view:"RegisterAccountNameSuccess",goBack:!1,replace:!0,onCancel(){ws.loading=!1}});const n=await Fe.signMessage(r),o=e.id;if(!o)throw new Error("Network not found");const a=Nx.convertEVMChainIdToCoinType(Number(o));await ne.registerEnsName({coinType:a,address:t,signature:n,message:r}),ie.setProfileName(s,e.chainNamespace),Me.replace("RegisterAccountNameSuccess")}catch(r){const n=this.parseEnsApiError(r,`Error registering name ${s}`);throw Me.replace("RegisterAccountName"),new Error(n)}finally{ws.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 $o(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function Pp(s){return $o(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const cy="2.23.2";let Zn={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${cy}`};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=Zn.getDocsUrl)==null?void 0:a.call(Zn,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...Zn.version?[`Version: ${Zn.version}`]:[]].join(`
|
|
12
|
+
`);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=cy}walk(e){return ly(this,e)}}function ly(s,e){return e!=null&&e(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?ly(s.cause,e):e?null:s}class hy 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 Mn(s,{dir:e,size:t=32}={}){return typeof s=="string"?_x(s,{dir:e,size:t}):Cx(s,{dir:e,size:t})}function _x(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new hy({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function Cx(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new hy({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 Sx 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 Tx extends dr{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function On(s,{size:e}){if(Pp(s)>e)throw new Tx({givenSize:Pp(s),maxSize:e})}function Zl(s,e={}){const{signed:t}=e;e.size&&On(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 Px(s,e={}){return Number(Zl(s,e))}const $x=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Xl(s,e={}){return typeof s=="number"||typeof s=="bigint"?dy(s,e):typeof s=="string"?xx(s,e):typeof s=="boolean"?Mx(s,e):uy(s,e)}function Mx(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(On(t,{size:e.size}),Mn(t,{size:e.size})):t}function uy(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=$x[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(On(i,{size:e.size}),Mn(i,{dir:"right",size:e.size})):i}function dy(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 Sx({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?Mn(a,{size:i}):a}const Ox=new TextEncoder;function xx(s,e={}){const t=Ox.encode(s);return uy(t,e)}const Dx=new TextEncoder;function kx(s,e={}){return typeof s=="number"||typeof s=="bigint"?Rx(s,e):typeof s=="boolean"?jx(s,e):$o(s)?py(s,e):gy(s,e)}function jx(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(On(t,{size:e.size}),Mn(t,{size:e.size})):t}const oi={zero:48,nine:57,A:65,F:70,a:97,f:102};function $p(s){if(s>=oi.zero&&s<=oi.nine)return s-oi.zero;if(s>=oi.A&&s<=oi.F)return s-(oi.A-10);if(s>=oi.a&&s<=oi.f)return s-(oi.a-10)}function py(s,e={}){let t=s;e.size&&(On(t,{size:e.size}),t=Mn(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=$p(i.charCodeAt(a++)),l=$p(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 Rx(s,e){const t=dy(s,e);return py(t)}function gy(s,e={}){const t=Dx.encode(s);return typeof e.size=="number"?(On(t,{size:e.size}),Mn(t,{dir:"right",size:e.size})):t}function Ja(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Ux(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ko(s,...e){if(!Ux(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 Lx(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ja(s.outputLen),Ja(s.blockLen)}function eh(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 fy(s,e){Ko(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Ia=BigInt(2**32-1),Mp=BigInt(32);function zx(s,e=!1){return e?{h:Number(s&Ia),l:Number(s>>Mp&Ia)}:{h:Number(s>>Mp&Ia)|0,l:Number(s&Ia)|0}}function Fx(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}=zx(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const qx=(s,e,t)=>s<<t|e>>>32-t,Bx=(s,e,t)=>e<<t|s>>>32-t,Hx=(s,e,t)=>e<<t-32|s>>>64-t,Wx=(s,e,t)=>s<<t-32|e>>>64-t,Fr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Vx(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Kx(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Gx(s,e){return s<<32-e|s>>>e}const Op=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Yx(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function xp(s){for(let e=0;e<s.length;e++)s[e]=Yx(s[e])}function Qx(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Gh(s){return typeof s=="string"&&(s=Qx(s)),Ko(s),s}function Jx(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Ko(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 wy{clone(){return this._cloneInto()}}function yy(s){const e=i=>s().update(Gh(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Zx(s=32){if(Fr&&typeof Fr.getRandomValues=="function")return Fr.getRandomValues(new Uint8Array(s));if(Fr&&typeof Fr.randomBytes=="function")return Fr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const my=[],by=[],vy=[],Xx=BigInt(0),Xn=BigInt(1),eD=BigInt(2),tD=BigInt(7),sD=BigInt(256),iD=BigInt(113);for(let s=0,e=Xn,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],my.push(2*(5*i+t)),by.push((s+1)*(s+2)/2%64);let r=Xx;for(let n=0;n<7;n++)e=(e<<Xn^(e>>tD)*iD)%sD,e&eD&&(r^=Xn<<(Xn<<BigInt(n))-Xn);vy.push(r)}const[rD,nD]=Fx(vy,!0),Dp=(s,e,t)=>t>32?Hx(s,e,t):qx(s,e,t),kp=(s,e,t)=>t>32?Wx(s,e,t):Bx(s,e,t);function oD(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],d=Dp(l,h,1)^t[a],p=kp(l,h,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=by[o],c=Dp(r,n,a),l=kp(r,n,a),h=my[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]^=rD[i],s[1]^=nD[i]}t.fill(0)}class Yh extends wy{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,Ja(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Vx(this.state)}keccak(){Op||xp(this.state32),oD(this.state32,this.rounds),Op||xp(this.state32),this.posOut=0,this.pos=0}update(e){eh(this);const{blockLen:t,state:i}=this;e=Gh(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){eh(this,!1),Ko(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 Ja(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(fy(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 Yh(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 aD=(s,e,t)=>yy(()=>new Yh(e,s,t)),cD=aD(1,136,256/8);function Iy(s,e){const t=e||"hex",i=cD($o(s,{strict:!1})?kx(s):s);return t==="bytes"?i:Xl(i)}class lD 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 nl=new lD(8192);function hD(s,e){if(nl.has(`${s}.${e}`))return nl.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=Iy(gy(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 nl.set(`${s}.${e}`,n),n}function uD(s){const e=Iy(`0x${s.substring(4)}`).substring(26);return hD(`0x${e}`)}async function dD({hash:s,signature:e}){const t=$o(s)?s:Xl(s),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-CHAR40au.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:h,v:d,yParity:p}=e,f=Number(p??d),g=jp(f);return new i.Signature(Zl(l),Zl(h)).addRecoveryBit(g)}const o=$o(e)?e:Xl(e),a=Px(`0x${o.slice(130)}`),c=jp(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function jp(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 pD({hash:s,signature:e}){return uD(await dD({hash:s,signature:e}))}function gD(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),d=h.charCodeAt(0);if(e[d]!==255)throw new TypeError(h+" is ambiguous");e[d]=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,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,h++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let y=l[p],A=0;for(let _=g-1;(y!==0||A<d)&&_!==-1;_--,A++)y+=256*w[_]>>>0,w[_]=y%t>>>0,y=y/t>>>0;if(y!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(h);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,d=0,p=0;for(;l[h]===i;)d++,h++;const f=(l.length-h)*r+1>>>0,g=new Uint8Array(f);for(;h<l.length;){const y=l.charCodeAt(h);if(y>255)return;let A=e[y];if(A===255)return;let _=0;for(let C=f-1;(A!==0||_<p)&&C!==-1;C--,_++)A+=t*g[C]>>>0,g[C]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=_,h++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 fD="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Ey=gD(fD),wD=":";function bn(s){const[e,t]=s.split(wD);return{namespace:e,reference:t}}function Ay(s,e){return s.includes(":")?[s]:e.chains||[]}const yD="ReactNative",hs={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},mD="js";function Za(){return typeof N.dist.process<"u"&&typeof N.dist.process.versions<"u"&&typeof N.dist.process.versions.node<"u"}function Fi(){return!u.getDocument_1()&&!!u.getNavigator_1()&&navigator.product===yD}function bD(){return Fi()&&typeof N.dist.global<"u"&&typeof(N.dist.global==null?void 0:N.dist.global.Platform)<"u"&&(N.dist.global==null?void 0:N.dist.global.Platform.OS)==="android"}function vD(){return Fi()&&typeof N.dist.global<"u"&&typeof(N.dist.global==null?void 0:N.dist.global.Platform)<"u"&&(N.dist.global==null?void 0:N.dist.global.Platform.OS)==="ios"}function Go(){return!Za()&&!!u.getNavigator_1()&&!!u.getDocument_1()}function Yo(){return Fi()?hs.reactNative:Za()?hs.node:Go()?hs.browser:hs.unknown}function Rp(){var s;try{return Fi()&&typeof N.dist.global<"u"&&typeof(N.dist.global==null?void 0:N.dist.global.Application)<"u"?(s=N.dist.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function ID(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 Ny(){return u.getWindowMetadata_1()||{name:"",description:"",url:"",icons:[""]}}function ED(){if(Yo()===hs.reactNative&&typeof N.dist.global<"u"&&typeof(N.dist.global==null?void 0:N.dist.global.Platform)<"u"){const{OS:t,Version:i}=N.dist.global.Platform;return[t,i].join("-")}const s=u.detect();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 AD(){var s;const e=Yo();return e===hs.browser?[e,((s=u.getLocation_1())==null?void 0:s.host)||"unknown"].join(":"):e}function _y(s,e,t){const i=ED(),r=AD();return[[s,e].join("-"),[mD,t].join("-"),i,r].join("/")}function ND({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=t.split("?"),h=_y(s,e,i),d={auth:r,ua:h,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=ID(l[1]||"",d);return l[0]+"?"+p}function or(s,e){return s.filter(t=>e.includes(t)).length===s.length}function th(s){return Object.fromEntries(s.entries())}function sh(s){return new Map(Object.entries(s))}function Xi(s=u.cjs.FIVE_MINUTES,e){const t=u.cjs.toMiliseconds(s||u.cjs.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 xi(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 Cy(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 _D(s){return Cy("topic",s)}function CD(s){return Cy("id",s)}function Sy(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 pt(s,e){return u.cjs.fromMiliseconds(Date.now()+u.cjs.toMiliseconds(s))}function Ti(s){return Date.now()>=u.cjs.toMiliseconds(s)}function $e(s,e){return`${s}${e?`:${e}`:""}`}function Ra(s=[],e=[]){return[...new Set([...s,...e])]}async function SD({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=TD(n,s,e),a=Yo();if(a===hs.browser){if(!((i=u.getDocument_1())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}PD(o)}else a===hs.reactNative&&typeof(N.dist.global==null?void 0:N.dist.global.Linking)<"u"&&await N.dist.global.Linking.openURL(o)}catch(r){console.error(r)}}function TD(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}${xD(i,!0)}`}else r=`${r}/wc?${i}`;return r}function PD(s){let e="_self";OD()?e="_top":(MD()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function $D(s,e){let t="";try{if(Go()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Up(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Lp(){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 Qh(){return typeof N.dist.process<"u"&&N.dist.process.env.IS_VITEST==="true"}function MD(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function OD(){try{return window.self!==window.top}catch{return!1}}function xD(s,e=!1){const t=N.dist.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Ty(s){return N.dist.Buffer.from(s,"base64").toString("utf-8")}function DD(s){return new Promise(e=>setTimeout(e,s))}function Mo(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function kD(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ic(s,...e){if(!kD(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 Jh(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Mo(s.outputLen),Mo(s.blockLen)}function Nn(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 Py(s,e){Ic(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Ea=BigInt(2**32-1),zp=BigInt(32);function jD(s,e=!1){return e?{h:Number(s&Ea),l:Number(s>>zp&Ea)}:{h:Number(s>>zp&Ea)|0,l:Number(s&Ea)|0}}function RD(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}=jD(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const UD=(s,e,t)=>s<<t|e>>>32-t,LD=(s,e,t)=>e<<t|s>>>32-t,zD=(s,e,t)=>e<<t-32|s>>>64-t,FD=(s,e,t)=>s<<t-32|e>>>64-t,qr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function qD(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function ol(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Ws(s,e){return s<<32-e|s>>>e}const Fp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function BD(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function qp(s){for(let e=0;e<s.length;e++)s[e]=BD(s[e])}function HD(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function _n(s){return typeof s=="string"&&(s=HD(s)),Ic(s),s}let Zh=class{clone(){return this._cloneInto()}};function $y(s){const e=i=>s().update(_n(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Qo(s=32){if(qr&&typeof qr.getRandomValues=="function")return qr.getRandomValues(new Uint8Array(s));if(qr&&typeof qr.randomBytes=="function")return qr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const My=[],Oy=[],xy=[],WD=BigInt(0),eo=BigInt(1),VD=BigInt(2),KD=BigInt(7),GD=BigInt(256),YD=BigInt(113);for(let s=0,e=eo,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],My.push(2*(5*i+t)),Oy.push((s+1)*(s+2)/2%64);let r=WD;for(let n=0;n<7;n++)e=(e<<eo^(e>>KD)*YD)%GD,e&VD&&(r^=eo<<(eo<<BigInt(n))-eo);xy.push(r)}const[QD,JD]=RD(xy,!0),Bp=(s,e,t)=>t>32?zD(s,e,t):UD(s,e,t),Hp=(s,e,t)=>t>32?FD(s,e,t):LD(s,e,t);function ZD(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],d=Bp(l,h,1)^t[a],p=Hp(l,h,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Oy[o],c=Bp(r,n,a),l=Hp(r,n,a),h=My[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]^=QD[i],s[1]^=JD[i]}t.fill(0)}let XD=class Dy extends Zh{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,Mo(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=qD(this.state)}keccak(){Fp||qp(this.state32),ZD(this.state32,this.rounds),Fp||qp(this.state32),this.posOut=0,this.pos=0}update(e){Nn(this);const{blockLen:t,state:i}=this;e=_n(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){Nn(this,!1),Ic(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 Mo(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Py(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 Dy(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 ek=(s,e,t)=>$y(()=>new XD(e,s,t)),tk=ek(1,136,256/8),sk="https://rpc.walletconnect.org/v1";function ky(s){const e=`Ethereum Signed Message:
|
|
13
|
+
${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+N.dist.Buffer.from(tk(t)).toString("hex")}async function ik(s,e,t,i,r,n){switch(t.t){case"eip191":return await rk(s,e,t.s);case"eip1271":return await nk(s,e,t.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function rk(s,e,t){return(await pD({hash:ky(e),signature:t})).toLowerCase()===s.toLowerCase()}async function nk(s,e,t,i,r,n){const o=bn(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),d=ky(e).substring(2),p=a+d+c+l+h,f=await fetch(`${n||sk}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:ok(),jsonrpc:"2.0",method:"eth_call",params:[{to:s,data:p},"latest"]})}),{result:g}=await f.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function ok(){return Date.now()+Math.floor(Math.random()*1e3)}function ak(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=N.dist.Buffer.from(s,"base64").slice(1,65);return Ey.encode(n)}var ck=Object.defineProperty,lk=Object.defineProperties,hk=Object.getOwnPropertyDescriptors,Wp=Object.getOwnPropertySymbols,uk=Object.prototype.hasOwnProperty,dk=Object.prototype.propertyIsEnumerable,Vp=(s,e,t)=>e in s?ck(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,pk=(s,e)=>{for(var t in e||(e={}))uk.call(e,t)&&Vp(s,t,e[t]);if(Wp)for(var t of Wp(e))dk.call(e,t)&&Vp(s,t,e[t]);return s},gk=(s,e)=>lk(s,hk(e));const fk="did:pkh:",Xh=s=>s==null?void 0:s.split(":"),wk=s=>{const e=s&&Xh(s);if(e)return s.includes(fk)?e[3]:e[1]},ih=s=>{const e=s&&Xh(s);if(e)return e[2]+":"+e[3]},Xa=s=>{const e=s&&Xh(s);if(e)return e.pop()};async function Kp(s){const{cacao:e,projectId:t}=s,{s:i,p:r}=e,n=jy(r,r.iss),o=Xa(r.iss);return await ik(o,n,i,ih(r.iss),t)}const jy=(s,e)=>{const t=`${s.domain} wants you to sign in with your Ethereum account:`,i=Xa(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: ${wk(e)}`,c=`Nonce: ${s.nonce}`,l=`Issued At: ${s.iat}`,h=s.exp?`Expiration Time: ${s.exp}`:void 0,d=s.nbf?`Not Before: ${s.nbf}`:void 0,p=s.requestId?`Request ID: ${s.requestId}`:void 0,f=s.resources?`Resources:${s.resources.map(w=>`
|
|
14
|
+
- ${w}`).join("")}`:void 0,g=Ua(s.resources);if(g){const w=Oo(g);r=_k(r,w)}return[t,i,"",r,"",n,o,a,c,l,h,d,p,f].filter(w=>w!=null).join(`
|
|
15
|
+
`)};function yk(s){return N.dist.Buffer.from(JSON.stringify(s)).toString("base64")}function mk(s){return JSON.parse(N.dist.Buffer.from(s,"base64").toString("utf-8"))}function pr(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 bk(s,e,t,i={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[s]:vk(e,t,i)}}}function vk(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 Ry(s){return pr(s),`urn:recap:${yk(s).replace(/=/g,"")}`}function Oo(s){const e=mk(s.replace("urn:recap:",""));return pr(e),e}function Ik(s,e,t){const i=bk(s,e,t);return Ry(i)}function Ek(s){return s&&s.includes("urn:recap:")}function Ak(s,e){const t=Oo(s),i=Oo(e),r=Nk(t,i);return Ry(r)}function Nk(s,e){pr(s),pr(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]=gk(pk({},i.att[r]),{[a]:((c=s.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),i}function _k(s="",e){pr(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(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));c.sort((d,p)=>d.action.localeCompare(p.action));const l={};c.forEach(d=>{l[d.ability]||(l[d.ability]=[]),l[d.ability].push(d.action)});const h=Object.keys(l).map(d=>(r++,`(${r}) '${d}': '${l[d].join("', '")}' for '${a}'.`));i.push(h.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${s?s+" ":""}${o}`}function Gp(s){var e;const t=Oo(s);pr(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function Yp(s){const e=Oo(s);pr(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 Ua(s){if(!s)return;const e=s==null?void 0:s[s.length-1];return Ek(e)?e:void 0}function al(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Uy(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function cs(s,...e){if(!Uy(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 Qp(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 Ck(s,e){cs(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Jp(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}const ji=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),Sk=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),Tk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Tk)throw new Error("Non little-endian hardware is not supported");function Pk(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function rh(s){if(typeof s=="string")s=Pk(s);else if(Uy(s))s=nh(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function $k(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function Mk(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 Ok=(s,e)=>{function t(i,...r){if(cs(i),s.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");s.varSizeNonce?cs(l):cs(l,s.nonceLength)}const n=s.tagLength;n&&r[1]!==void 0&&cs(r[1]);const o=e(i,...r),a=(l,h)=>{if(h!==void 0){if(l!==2)throw new Error("cipher output not supported");cs(h)}};let c=!1;return{encrypt(l,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,cs(l),a(o.encrypt.length,h),o.encrypt(l,h)},decrypt(l,h){if(cs(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 Zp(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&&!xk(e))throw new Error("invalid output, must be aligned");return e}function Xp(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 xk(s){return s.byteOffset%4===0}function nh(s){return Uint8Array.from(s)}function Cn(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}const Ly=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),Dk=Ly("expand 16-byte k"),kk=Ly("expand 32-byte k"),jk=ji(Dk),Rk=ji(kk);function Ae(s,e){return s<<e|s>>>32-e}function oh(s){return s.byteOffset%4===0}const Aa=64,Uk=16,zy=2**32-1,eg=new Uint32Array;function Lk(s,e,t,i,r,n,o,a){const c=r.length,l=new Uint8Array(Aa),h=ji(l),d=oh(r)&&oh(n),p=d?ji(r):eg,f=d?ji(n):eg;for(let g=0;g<c;o++){if(s(e,t,i,h,o,a),o>=zy)throw new Error("arx: counter overflow");const w=Math.min(Aa,c-g);if(d&&w===Aa){const v=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let b=0,y;b<Uk;b++)y=v+b,f[y]=p[y]^h[b];g+=Aa;continue}for(let v=0,b;v<w;v++)b=g+v,n[b]=r[b]^l[v];g+=w}}function zk(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=$k({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),Jp(n),Jp(t),(a,c,l,h,d=0)=>{cs(a),cs(c),cs(l);const p=l.length;if(h===void 0&&(h=new Uint8Array(p)),cs(h),al(d),d<0||d>=zy)throw new Error("arx: counter overflow");if(h.length<p)throw new Error(`arx: output (${h.length}) is shorter than data (${p})`);const f=[];let g=a.length,w,v;if(g===32)f.push(w=nh(a)),v=Rk;else if(g===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),v=jk,f.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);oh(c)||f.push(c=nh(c));const b=ji(w);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(v,b,ji(c.subarray(0,16)),b),c=c.subarray(16)}const y=16-r;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const _=new Uint8Array(12);_.set(c,n?0:12-c.length),c=_,f.push(c)}const A=ji(c);return Lk(s,v,b,A,l,h,d,o),Cn(...f),h}}const Tt=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let Fk=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=rh(e),cs(e,32);const t=Tt(e,0),i=Tt(e,2),r=Tt(e,4),n=Tt(e,6),o=Tt(e,8),a=Tt(e,10),c=Tt(e,12),l=Tt(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]=Tt(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],d=o[4],p=o[5],f=o[6],g=o[7],w=o[8],v=o[9],b=Tt(e,t+0),y=Tt(e,t+2),A=Tt(e,t+4),_=Tt(e,t+6),C=Tt(e,t+8),T=Tt(e,t+10),P=Tt(e,t+12),x=Tt(e,t+14);let $=n[0]+(b&8191),q=n[1]+((b>>>13|y<<3)&8191),j=n[2]+((y>>>10|A<<6)&8191),G=n[3]+((A>>>7|_<<9)&8191),B=n[4]+((_>>>4|C<<12)&8191),W=n[5]+(C>>>1&8191),V=n[6]+((C>>>14|T<<2)&8191),H=n[7]+((T>>>11|P<<5)&8191),K=n[8]+((P>>>8|x<<8)&8191),Q=n[9]+(x>>>5|r),S=0,z=S+$*a+q*(5*v)+j*(5*w)+G*(5*g)+B*(5*f);S=z>>>13,z&=8191,z+=W*(5*p)+V*(5*d)+H*(5*h)+K*(5*l)+Q*(5*c),S+=z>>>13,z&=8191;let ee=S+$*c+q*a+j*(5*v)+G*(5*w)+B*(5*g);S=ee>>>13,ee&=8191,ee+=W*(5*f)+V*(5*p)+H*(5*d)+K*(5*h)+Q*(5*l),S+=ee>>>13,ee&=8191;let J=S+$*l+q*c+j*a+G*(5*v)+B*(5*w);S=J>>>13,J&=8191,J+=W*(5*g)+V*(5*f)+H*(5*p)+K*(5*d)+Q*(5*h),S+=J>>>13,J&=8191;let be=S+$*h+q*l+j*c+G*a+B*(5*v);S=be>>>13,be&=8191,be+=W*(5*w)+V*(5*g)+H*(5*f)+K*(5*p)+Q*(5*d),S+=be>>>13,be&=8191;let de=S+$*d+q*h+j*l+G*c+B*a;S=de>>>13,de&=8191,de+=W*(5*v)+V*(5*w)+H*(5*g)+K*(5*f)+Q*(5*p),S+=de>>>13,de&=8191;let te=S+$*p+q*d+j*h+G*l+B*c;S=te>>>13,te&=8191,te+=W*a+V*(5*v)+H*(5*w)+K*(5*g)+Q*(5*f),S+=te>>>13,te&=8191;let st=S+$*f+q*p+j*d+G*h+B*l;S=st>>>13,st&=8191,st+=W*c+V*a+H*(5*v)+K*(5*w)+Q*(5*g),S+=st>>>13,st&=8191;let Ue=S+$*g+q*f+j*p+G*d+B*h;S=Ue>>>13,Ue&=8191,Ue+=W*l+V*c+H*a+K*(5*v)+Q*(5*w),S+=Ue>>>13,Ue&=8191;let ve=S+$*w+q*g+j*f+G*p+B*d;S=ve>>>13,ve&=8191,ve+=W*h+V*l+H*c+K*a+Q*(5*v),S+=ve>>>13,ve&=8191;let De=S+$*v+q*w+j*g+G*f+B*p;S=De>>>13,De&=8191,De+=W*d+V*h+H*l+K*c+Q*a,S+=De>>>13,De&=8191,S=(S<<2)+S|0,S=S+z|0,z=S&8191,S=S>>>13,ee+=S,n[0]=z,n[1]=ee,n[2]=J,n[3]=be,n[4]=de,n[5]=te,n[6]=st,n[7]=Ue,n[8]=ve,n[9]=De}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;Cn(i)}update(e){Qp(this);const{buffer:t,blockLen:i}=this;e=rh(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(){Cn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Qp(this),Ck(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 qk(s){const e=(i,r)=>s(r).update(rh(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const Bk=qk(s=>new Fk(s));function Hk(s,e,t,i,r,n=20){let o=s[0],a=s[1],c=s[2],l=s[3],h=e[0],d=e[1],p=e[2],f=e[3],g=e[4],w=e[5],v=e[6],b=e[7],y=r,A=t[0],_=t[1],C=t[2],T=o,P=a,x=c,$=l,q=h,j=d,G=p,B=f,W=g,V=w,H=v,K=b,Q=y,S=A,z=_,ee=C;for(let be=0;be<n;be+=2)T=T+q|0,Q=Ae(Q^T,16),W=W+Q|0,q=Ae(q^W,12),T=T+q|0,Q=Ae(Q^T,8),W=W+Q|0,q=Ae(q^W,7),P=P+j|0,S=Ae(S^P,16),V=V+S|0,j=Ae(j^V,12),P=P+j|0,S=Ae(S^P,8),V=V+S|0,j=Ae(j^V,7),x=x+G|0,z=Ae(z^x,16),H=H+z|0,G=Ae(G^H,12),x=x+G|0,z=Ae(z^x,8),H=H+z|0,G=Ae(G^H,7),$=$+B|0,ee=Ae(ee^$,16),K=K+ee|0,B=Ae(B^K,12),$=$+B|0,ee=Ae(ee^$,8),K=K+ee|0,B=Ae(B^K,7),T=T+j|0,ee=Ae(ee^T,16),H=H+ee|0,j=Ae(j^H,12),T=T+j|0,ee=Ae(ee^T,8),H=H+ee|0,j=Ae(j^H,7),P=P+G|0,Q=Ae(Q^P,16),K=K+Q|0,G=Ae(G^K,12),P=P+G|0,Q=Ae(Q^P,8),K=K+Q|0,G=Ae(G^K,7),x=x+B|0,S=Ae(S^x,16),W=W+S|0,B=Ae(B^W,12),x=x+B|0,S=Ae(S^x,8),W=W+S|0,B=Ae(B^W,7),$=$+q|0,z=Ae(z^$,16),V=V+z|0,q=Ae(q^V,12),$=$+q|0,z=Ae(z^$,8),V=V+z|0,q=Ae(q^V,7);let J=0;i[J++]=o+T|0,i[J++]=a+P|0,i[J++]=c+x|0,i[J++]=l+$|0,i[J++]=h+q|0,i[J++]=d+j|0,i[J++]=p+G|0,i[J++]=f+B|0,i[J++]=g+W|0,i[J++]=w+V|0,i[J++]=v+H|0,i[J++]=b+K|0,i[J++]=y+Q|0,i[J++]=A+S|0,i[J++]=_+z|0,i[J++]=C+ee|0}const Wk=zk(Hk,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Vk=new Uint8Array(16),tg=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(Vk.subarray(t))},Kk=new Uint8Array(32);function sg(s,e,t,i,r){const n=s(e,t,Kk),o=Bk.create(n);r&&tg(o,r),tg(o,i);const a=new Uint8Array(16),c=Sk(a);Xp(c,0,BigInt(r?r.length:0),!0),Xp(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return Cn(n,a),l}const Gk=s=>(e,t,i)=>({encrypt(r,n){const o=r.length;n=Zp(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);s(e,t,a,a,1);const c=sg(s,e,t,a,i);return n.set(c,o),Cn(c),n},decrypt(r,n){n=Zp(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=sg(s,e,t,o,i);if(!Mk(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),Cn(c),n}}),Fy=Ok({blockSize:64,nonceLength:12,tagLength:16},Gk(Wk));let qy=class extends Zh{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Jh(e);const i=_n(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 Nn(this),this.iHash.update(e),this}digestInto(e){Nn(this),Ic(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 eu=(s,e,t)=>new qy(s,e).update(t).digest();eu.create=(s,e)=>new qy(s,e);function Yk(s,e,t){return Jh(s),t===void 0&&(t=new Uint8Array(s.outputLen)),eu(s,_n(t),_n(e))}const cl=new Uint8Array([0]),ig=new Uint8Array;function Qk(s,e,t,i=32){if(Jh(s),Mo(i),i>255*s.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/s.outputLen);t===void 0&&(t=ig);const n=new Uint8Array(r*s.outputLen),o=eu.create(s,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)cl[0]=l+1,a.update(l===0?ig:c).update(t).update(cl).digestInto(c),n.set(c,s.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),cl.fill(0),n.slice(0,i)}const Jk=(s,e,t,i,r)=>Qk(s,Yk(s,e,t),i,r);function Zk(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 Xk(s,e,t){return s&e^~s&t}function e3(s,e,t){return s&e^s&t^e&t}class t3 extends Zh{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=ol(this.buffer)}update(e){Nn(this);const{view:t,buffer:i,blockLen:r}=this;e=_n(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=ol(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){Nn(this),Py(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 d=o;d<r;d++)t[d]=0;Zk(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=ol(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 d=0;d<l;d++)a.setUint32(4*d,h[d],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 s3=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]),Ai=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ni=new Uint32Array(64);let i3=class extends t3{constructor(){super(64,32,8,!1),this.A=Ai[0]|0,this.B=Ai[1]|0,this.C=Ai[2]|0,this.D=Ai[3]|0,this.E=Ai[4]|0,this.F=Ai[5]|0,this.G=Ai[6]|0,this.H=Ai[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 d=0;d<16;d++,t+=4)Ni[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const p=Ni[d-15],f=Ni[d-2],g=Ws(p,7)^Ws(p,18)^p>>>3,w=Ws(f,17)^Ws(f,19)^f>>>10;Ni[d]=w+Ni[d-7]+g+Ni[d-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:c,G:l,H:h}=this;for(let d=0;d<64;d++){const p=Ws(a,6)^Ws(a,11)^Ws(a,25),f=h+p+Xk(a,c,l)+s3[d]+Ni[d]|0,g=(Ws(i,2)^Ws(i,13)^Ws(i,22))+e3(i,r,n)|0;h=l,l=c,c=a,a=o+f|0,o=n,n=r,r=i,i=f+g|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(){Ni.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const Ec=$y(()=>new i3);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const By=BigInt(0);function tu(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Hy(s){if(!tu(s))throw new Error("Uint8Array expected")}const r3=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function n3(s){Hy(s);let e="";for(let t=0;t<s.length;t++)e+=r3[s[t]];return e}function o3(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?By:BigInt("0x"+s)}const ai={_0:48,_9:57,A:65,F:70,a:97,f:102};function rg(s){if(s>=ai._0&&s<=ai._9)return s-ai._0;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 Wy(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=rg(s.charCodeAt(n)),a=rg(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 ng(s){return Hy(s),o3(n3(Uint8Array.from(s).reverse()))}function a3(s,e){return Wy(s.toString(16).padStart(e*2,"0"))}function c3(s,e){return a3(s,e).reverse()}function og(s,e,t){let i;if(typeof e=="string")try{i=Wy(e)}catch(n){throw new Error(s+" must be hex string or Uint8Array, cause: "+n)}else if(tu(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 ll=s=>typeof s=="bigint"&&By<=s;function l3(s,e,t){return ll(s)&&ll(e)&&ll(t)&&e<=s&&s<t}function ag(s,e,t,i){if(!l3(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const h3={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"||tu(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 u3(s,e,t={}){const i=(r,n,o)=>{const a=h3[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 pn=BigInt(0),Na=BigInt(1);function Vy(s,e){const t=s%e;return t>=pn?t:e+t}function d3(s,e,t){if(e<pn)throw new Error("invalid exponent, negatives unsupported");if(t<=pn)throw new Error("invalid modulus");if(t===Na)return pn;let i=Na;for(;e>pn;)e&Na&&(i=i*s%t),s=s*s%t,e>>=Na;return i}function ks(s,e,t){let i=s;for(;e-- >pn;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Br=BigInt(0),hl=BigInt(1);function p3(s){return u3(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function g3(s){const e=p3(s),{P:t}=e,i=y=>Vy(y,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(y=>y),c=e.powPminus2||(y=>d3(y,t-BigInt(2),t));function l(y,A,_){const C=i(y*(A-_));return A=i(A-C),_=i(_+C),[A,_]}const h=(e.a-BigInt(2))/BigInt(4);function d(y,A){ag("u",y,Br,t),ag("scalar",A,Br,t);const _=A,C=y;let T=hl,P=Br,x=y,$=hl,q=Br,j;for(let B=BigInt(r-1);B>=Br;B--){const W=_>>B&hl;q^=W,j=l(q,T,x),T=j[0],x=j[1],j=l(q,P,$),P=j[0],$=j[1],q=W;const V=T+P,H=i(V*V),K=T-P,Q=i(K*K),S=H-Q,z=x+$,ee=x-$,J=i(ee*V),be=i(z*K),de=J+be,te=J-be;x=i(de*de),$=i(C*i(te*te)),T=i(H*Q),P=i(S*(H+i(h*S)))}j=l(q,T,x),T=j[0],x=j[1],j=l(q,P,$),P=j[0],$=j[1];const G=c(P);return i(T*G)}function p(y){return c3(i(y),n)}function f(y){const A=og("u coordinate",y,n);return o===32&&(A[31]&=127),ng(A)}function g(y){const A=og("scalar",y),_=A.length;if(_!==n&&_!==o){let C=""+n+" or "+o;throw new Error("invalid scalar, expected "+C+" bytes, got "+_)}return ng(a(A))}function w(y,A){const _=f(A),C=g(y),T=d(_,C);if(T===Br)throw new Error("invalid private or public key received");return p(T)}const v=p(e.Gu);function b(y){return w(y,v)}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(y,A)=>w(y,A),getPublicKey:y=>b(y),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}const ah=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const f3=BigInt(1),cg=BigInt(2),w3=BigInt(3),y3=BigInt(5);BigInt(8);function m3(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=ah,o=s*s%n*s%n,a=ks(o,cg,n)*o%n,c=ks(a,f3,n)*s%n,l=ks(c,y3,n)*c%n,h=ks(l,e,n)*l%n,d=ks(h,t,n)*h%n,p=ks(d,i,n)*d%n,f=ks(p,r,n)*p%n,g=ks(f,r,n)*p%n,w=ks(g,e,n)*l%n;return{pow_p_5_8:ks(w,cg,n)*s%n,b2:o}}function b3(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const ch=g3({P:ah,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=ah,{pow_p_5_8:t,b2:i}=m3(s);return Vy(ks(t,w3,e)*i,e)},adjustScalarBytes:b3,randomBytes:Qo}),Ky="base10",Bt="base16",Di="base64pad",to="base64url",Jo="utf8",Gy=0,fi=1,Zo=2,v3=0,lg=1,mo=12,su=32;function I3(){const s=ch.utils.randomPrivateKey(),e=ch.getPublicKey(s);return{privateKey:u.toString(s,Bt),publicKey:u.toString(e,Bt)}}function lh(){const s=Qo(su);return u.toString(s,Bt)}function E3(s,e){const t=ch.getSharedSecret(u.fromString(s,Bt),u.fromString(e,Bt)),i=Jk(Ec,t,void 0,void 0,su);return u.toString(i,Bt)}function La(s){const e=Ec(u.fromString(s,Bt));return u.toString(e,Bt)}function Qs(s){const e=Ec(u.fromString(s,Jo));return u.toString(e,Bt)}function Yy(s){return u.fromString(`${s}`,Ky)}function gr(s){return Number(u.toString(s,Ky))}function A3(s){const e=Yy(typeof s.type<"u"?s.type:Gy);if(gr(e)===fi&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?u.fromString(s.senderPublicKey,Bt):void 0,i=typeof s.iv<"u"?u.fromString(s.iv,Bt):Qo(mo),r=u.fromString(s.symKey,Bt),n=Fy(r,i).encrypt(u.fromString(s.message,Jo));return Qy({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function N3(s){const e=u.fromString(s.symKey,Bt),{sealed:t,iv:i}=xo(s),r=Fy(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return u.toString(r,Jo)}function _3(s,e){const t=Yy(Zo),i=Qo(mo),r=u.fromString(s,Jo);return Qy({type:t,sealed:r,iv:i,encoding:e})}function C3(s,e){const{sealed:t}=xo({encoded:s,encoding:e});return u.toString(t,Jo)}function Qy(s){const{encoding:e=Di}=s;if(gr(s.type)===Zo)return u.toString(u.concat([s.type,s.sealed]),e);if(gr(s.type)===fi){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return u.toString(u.concat([s.type,s.senderPublicKey,s.iv,s.sealed]),e)}return u.toString(u.concat([s.type,s.iv,s.sealed]),e)}function xo(s){const{encoded:e,encoding:t=Di}=s,i=u.fromString(e,t),r=i.slice(v3,lg),n=lg;if(gr(r)===fi){const l=n+su,h=l+mo,d=i.slice(n,l),p=i.slice(l,h),f=i.slice(h);return{type:r,sealed:f,iv:p,senderPublicKey:d}}if(gr(r)===Zo){const l=i.slice(n),h=Qo(mo);return{type:r,sealed:l,iv:h}}const o=n+mo,a=i.slice(n,o),c=i.slice(o);return{type:r,sealed:c,iv:a}}function S3(s,e){const t=xo({encoded:s,encoding:e==null?void 0:e.encoding});return Jy({type:gr(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?u.toString(t.senderPublicKey,Bt):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Jy(s){const e=(s==null?void 0:s.type)||Gy;if(e===fi){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 hg(s){return s.type===fi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function ug(s){return s.type===Zo}function T3(s){return new kf.ec("p256").keyFromPublic({x:N.dist.Buffer.from(s.x,"base64").toString("hex"),y:N.dist.Buffer.from(s.y,"base64").toString("hex")},"hex")}function P3(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function $3(s){return N.dist.Buffer.from(P3(s),"base64")}function M3(s,e){const[t,i,r]=s.split("."),n=$3(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=Ec(c),h=T3(e),d=u.toString(l,Bt);if(!h.verify(d,{r:o,s:a}))throw new Error("Invalid signature");return u.sn(s).payload}const O3="irn";function ec(s){return(s==null?void 0:s.relay)||{protocol:O3}}function ho(s){const e=u.C[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function x3(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 dg(s){if(!s.includes("wc:")){const l=Ty(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:D3(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:x3(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function D3(s){return s.startsWith("//")?s.substring(2):s}function k3(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 pg(s){const e=new URLSearchParams,t=k3(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 _a(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function xn(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function j3(s){const e=[];return Object.values(s).forEach(t=>{e.push(...xn(t.accounts))}),e}function R3(s,e){const t=[];return Object.values(s).forEach(i=>{xn(i.accounts).includes(e)&&t.push(...i.methods)}),t}function U3(s,e){const t=[];return Object.values(s).forEach(i=>{xn(i.accounts).includes(e)&&t.push(...i.events)}),t}function iu(s){return s.includes(":")}function uo(s){return iu(s)?s.split(":")[0]:s}function L3(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 gg(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=L3(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=Ra(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const z3={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}},F3={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 L(s,e){const{message:t,code:i}=F3[s];return{message:e?`${t} ${e}`:t,code:i}}function Re(s,e){const{message:t,code:i}=z3[s];return{message:e?`${t} ${e}`:t,code:i}}function fr(s,e){return!!Array.isArray(s)}function Do(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 ru(s,e){return e&&xt(s)?!0:typeof s=="number"&&!isNaN(s)}function q3(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return or(r,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=s.namespaces[o],h=xn(a),d=t[o];(!or(Ay(o,d),h)||!or(d.methods,c)||!or(d.events,l))&&(n=!1)}),n):!1}function tc(s){return ht(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function B3(s){if(ht(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&tc(t)}}return!1}function H3(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=Ty(s);return e(t)}}catch{}return!1}function W3(s){var e;return(e=s==null?void 0:s.proposer)==null?void 0:e.publicKey}function V3(s){return s==null?void 0:s.topic}function K3(s,e){let t=null;return ht(s==null?void 0:s.publicKey,!1)||(t=L("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function fg(s){let e=!0;return fr(s)?s.length&&(e=s.every(t=>ht(t,!1))):e=!1,e}function G3(s,e,t){let i=null;return fr(e)&&e.length?e.forEach(r=>{i||tc(r)||(i=Re("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):tc(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 Y3(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=G3(r,Ay(r,n),`${e} ${t}`);o&&(i=o)}),i}function Q3(s,e){let t=null;return fr(s)?s.forEach(i=>{t||B3(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 J3(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=Q3(i==null?void 0:i.accounts,`${e} namespace`);r&&(t=r)}),t}function Z3(s,e){let t=null;return fg(s==null?void 0:s.methods)?fg(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 Zy(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=Z3(i,`${e}, namespace`);r&&(t=r)}),t}function X3(s,e,t){let i=null;if(s&&Do(s)){const r=Zy(s,e);r&&(i=r);const n=Y3(s,e,t);n&&(i=n)}else i=L("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function ul(s,e){let t=null;if(s&&Do(s)){const i=Zy(s,e);i&&(t=i);const r=J3(s,e);r&&(t=r)}else t=L("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Xy(s){return ht(s.protocol,!0)}function ej(s,e){let t=!1;return s?s&&fr(s)&&s.length&&s.forEach(i=>{t=Xy(i)}):t=!0,t}function tj(s){return typeof s=="number"}function Xt(s){return typeof s<"u"&&typeof s!==null}function sj(s){return!(!s||typeof s!="object"||!s.code||!ru(s.code,!1)||!s.message||!ht(s.message,!1))}function ij(s){return!(xt(s)||!ht(s.method,!1))}function rj(s){return!(xt(s)||xt(s.result)&&xt(s.error)||!ru(s.id,!1)||!ht(s.jsonrpc,!1))}function nj(s){return!(xt(s)||!ht(s.name,!1))}function wg(s,e){return!(!tc(e)||!j3(s).includes(e))}function oj(s,e,t){return ht(t,!1)?R3(s,e).includes(t):!1}function aj(s,e,t){return ht(t,!1)?U3(s,e).includes(t):!1}function yg(s,e,t){let i=null;const r=cj(s),n=lj(e),o=Object.keys(r),a=Object.keys(n),c=mg(Object.keys(s)),l=mg(Object.keys(e)),h=c.filter(d=>!l.includes(d));return h.length&&(i=L("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
|
|
16
|
+
Required: ${h.toString()}
|
|
17
|
+
Received: ${Object.keys(e).toString()}`)),or(o,a)||(i=L("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces.
|
|
18
|
+
Required: ${o.toString()}
|
|
19
|
+
Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||i)return;const p=xn(e[d].accounts);p.includes(d)||(i=L("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${d}
|
|
20
|
+
Required: ${d}
|
|
21
|
+
Approved: ${p.toString()}`))}),o.forEach(d=>{i||(or(r[d].methods,n[d].methods)?or(r[d].events,n[d].events)||(i=L("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${d}`)):i=L("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${d}`))}),i}function cj(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 mg(s){return[...new Set(s.map(e=>e.includes(":")?e.split(":")[0]:e))]}function lj(s){const e={};return Object.keys(s).forEach(t=>{if(t.includes(":"))e[t]=s[t];else{const i=xn(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 hj(s,e){return ru(s,!1)&&s<=e.max&&s>=e.min}function bg(){const s=Yo();return new Promise(e=>{switch(s){case hs.browser:e(uj());break;case hs.reactNative:e(dj());break;case hs.node:e(pj());break;default:e(!0)}})}function uj(){return Go()&&(navigator==null?void 0:navigator.onLine)}async function dj(){if(Fi()&&typeof N.dist.global<"u"&&N.dist.global!=null&&N.dist.global.NetInfo){const s=await(N.dist.global==null?void 0:N.dist.global.NetInfo.fetch());return s==null?void 0:s.isConnected}return!0}function pj(){return!0}function gj(s){switch(Yo()){case hs.browser:fj(s);break;case hs.reactNative:wj(s);break}}function fj(s){!Fi()&&Go()&&(window.addEventListener("online",()=>s(!0)),window.addEventListener("offline",()=>s(!1)))}function wj(s){var e;Fi()&&typeof N.dist.global<"u"&&N.dist.global!=null&&N.dist.global.NetInfo&&((e=N.dist.global)==null||e.NetInfo.addEventListener(t=>s(t==null?void 0:t.isConnected)))}const dl={};class so{static get(e){return dl[e]}static set(e,t){dl[e]=t}static delete(e){delete dl[e]}}const em="wc",tm=2,hh="core",Zs=`${em}@2:${hh}:`,yj={logger:"error"},mj={database:":memory:"},bj="crypto",vg="client_ed25519_seed",vj=u.cjs.ONE_DAY,Ij="keychain",Ej="0.3",Aj="messages",Nj="0.3",Ig=u.cjs.SIX_HOURS,_j="publisher",sm="irn",Cj="error",im="wss://relay.walletconnect.org",Sj="relayer",Et={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"},Tj="_subscription",ys={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Pj=.1,uh="2.19.1",Je={link_mode:"link_mode",relay:"relay"},za={inbound:"inbound",outbound:"outbound"},$j="0.3",Mj="WALLETCONNECT_CLIENT_ID",Eg="WALLETCONNECT_LINK_MODE_APPS",os={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Oj="subscription",xj="0.3",Dj="pairing",kj="0.3",io={wc_pairingDelete:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:u.cjs.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:u.cjs.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:0},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:0}}},sr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ms={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},jj="history",Rj="0.3",Uj="expirer",vs={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Lj="0.3",zj="verify-api",Fj="https://verify.walletconnect.com",rm="https://verify.walletconnect.org",bo=rm,qj=`${bo}/v3`,Bj=[Fj,rm],Hj="echo",Wj="https://echo.walletconnect.com",Ys={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"},li={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"},Os={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"},Yi={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"},Qi={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"},ro={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"},Vj=.1,Kj="event-client",Gj=86400,Yj="https://pulse.walletconnect.org/batch";function Qj(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 d(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,v=0,b=0,y=g.length;b!==y&&g[b]===0;)b++,w++;for(var A=(y-b)*h+1>>>0,_=new Uint8Array(A);b!==y;){for(var C=g[b],T=0,P=A-1;(C!==0||T<v)&&P!==-1;P--,T++)C+=256*_[P]>>>0,_[P]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");v=T,b++}for(var x=A-v;x!==A&&_[x]===0;)x++;for(var $=c.repeat(w);x<A;++x)$+=s.charAt(_[x]);return $}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var v=0,b=0;g[w]===c;)v++,w++;for(var y=(g.length-w)*l+1>>>0,A=new Uint8Array(y);g[w];){var _=t[g.charCodeAt(w)];if(_===255)return;for(var C=0,T=y-1;(_!==0||C<b)&&T!==-1;T--,C++)_+=a*A[T]>>>0,A[T]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");b=C,w++}if(g[w]!==" "){for(var P=y-b;P!==y&&A[P]===0;)P++;for(var x=new Uint8Array(v+(y-P)),$=v;P!==y;)x[$++]=A[P++];return x}}}function f(g){var w=p(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var Jj=Qj,Zj=Jj;const nm=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")},Xj=s=>new TextEncoder().encode(s),eR=s=>new TextDecoder().decode(s);class tR{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")}}class sR{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 om(this,e)}}class iR{constructor(e){this.decoders=e}or(e){return om(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 om=(s,e)=>new iR({...s.decoders||{[s.prefix]:s},...e.decoders||{[e.prefix]:e}});class rR{constructor(e,t,i,r){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=r,this.encoder=new tR(e,t,i),this.decoder=new sR(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ac=({name:s,prefix:e,encode:t,decode:i})=>new rR(s,e,t,i),Xo=({prefix:s,name:e,alphabet:t})=>{const{encode:i,decode:r}=Zj(t,e);return Ac({prefix:s,name:e,encode:i,decode:n=>nm(r(n))})},nR=(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 d=r[s[h]];if(d===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|d,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},oR=(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},jt=({name:s,prefix:e,bitsPerChar:t,alphabet:i})=>Ac({prefix:e,name:s,encode(r){return oR(r,i,t)},decode(r){return nR(r,i,t,s)}}),aR=Ac({prefix:"\0",name:"identity",encode:s=>eR(s),decode:s=>Xj(s)});var cR=Object.freeze({__proto__:null,identity:aR});const lR=jt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var hR=Object.freeze({__proto__:null,base2:lR});const uR=jt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var dR=Object.freeze({__proto__:null,base8:uR});const pR=Xo({prefix:"9",name:"base10",alphabet:"0123456789"});var gR=Object.freeze({__proto__:null,base10:pR});const fR=jt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),wR=jt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yR=Object.freeze({__proto__:null,base16:fR,base16upper:wR});const mR=jt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),bR=jt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),vR=jt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),IR=jt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ER=jt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),AR=jt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),NR=jt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),_R=jt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),CR=jt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var SR=Object.freeze({__proto__:null,base32:mR,base32upper:bR,base32pad:vR,base32padupper:IR,base32hex:ER,base32hexupper:AR,base32hexpad:NR,base32hexpadupper:_R,base32z:CR});const TR=Xo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),PR=Xo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $R=Object.freeze({__proto__:null,base36:TR,base36upper:PR});const MR=Xo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),OR=Xo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xR=Object.freeze({__proto__:null,base58btc:MR,base58flickr:OR});const DR=jt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kR=jt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),jR=jt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),RR=jt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var UR=Object.freeze({__proto__:null,base64:DR,base64pad:kR,base64url:jR,base64urlpad:RR});const am=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),LR=am.reduce((s,e,t)=>(s[t]=e,s),[]),zR=am.reduce((s,e,t)=>(s[e.codePointAt(0)]=t,s),[]);function FR(s){return s.reduce((e,t)=>(e+=LR[t],e),"")}function qR(s){const e=[];for(const t of s){const i=zR[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const BR=Ac({prefix:"🚀",name:"base256emoji",encode:FR,decode:qR});var HR=Object.freeze({__proto__:null,base256emoji:BR}),WR=cm,Ag=128,VR=-128,KR=Math.pow(2,31);function cm(s,e,t){e=e||[],t=t||0;for(var i=t;s>=KR;)e[t++]=s&255|Ag,s/=128;for(;s&VR;)e[t++]=s&255|Ag,s>>>=7;return e[t]=s|0,cm.bytes=t-i+1,e}var GR=dh,YR=128,Ng=127;function dh(s,i){var t=0,i=i||0,r=0,n=i,o,a=s.length;do{if(n>=a)throw dh.bytes=0,new RangeError("Could not decode varint");o=s[n++],t+=r<28?(o&Ng)<<r:(o&Ng)*Math.pow(2,r),r+=7}while(o>=YR);return dh.bytes=n-i,t}var QR=Math.pow(2,7),JR=Math.pow(2,14),ZR=Math.pow(2,21),XR=Math.pow(2,28),e4=Math.pow(2,35),t4=Math.pow(2,42),s4=Math.pow(2,49),i4=Math.pow(2,56),r4=Math.pow(2,63),n4=function(s){return s<QR?1:s<JR?2:s<ZR?3:s<XR?4:s<e4?5:s<t4?6:s<s4?7:s<i4?8:s<r4?9:10},o4={encode:WR,decode:GR,encodingLength:n4},lm=o4;const _g=(s,e,t=0)=>(lm.encode(s,e,t),e),Cg=s=>lm.encodingLength(s),ph=(s,e)=>{const t=e.byteLength,i=Cg(s),r=i+Cg(t),n=new Uint8Array(r+t);return _g(s,n,0),_g(t,n,i),n.set(e,r),new a4(s,t,e,n)};class a4{constructor(e,t,i,r){this.code=e,this.size=t,this.digest=i,this.bytes=r}}const hm=({name:s,code:e,encode:t})=>new c4(s,e,t);class c4{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?ph(this.code,t):t.then(i=>ph(this.code,i))}else throw Error("Unknown type, must be binary type")}}const um=s=>async e=>new Uint8Array(await crypto.subtle.digest(s,e)),l4=hm({name:"sha2-256",code:18,encode:um("SHA-256")}),h4=hm({name:"sha2-512",code:19,encode:um("SHA-512")});var u4=Object.freeze({__proto__:null,sha256:l4,sha512:h4});const dm=0,d4="identity",pm=nm,p4=s=>ph(dm,pm(s)),g4={code:dm,name:d4,encode:pm,digest:p4};var f4=Object.freeze({__proto__:null,identity:g4});new TextEncoder,new TextDecoder;const Sg={...cR,...hR,...dR,...gR,...yR,...SR,...$R,...xR,...UR,...HR};({...u4,...f4});function w4(s=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(s):new Uint8Array(s)}function gm(s,e,t,i){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:i}}}const Tg=gm("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),pl=gm("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=w4(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),y4={utf8:Tg,"utf-8":Tg,hex:Sg.base16,latin1:pl,ascii:pl,binary:pl,...Sg};function m4(s,e="utf8"){const t=y4[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 b4=Object.defineProperty,v4=(s,e,t)=>e in s?b4(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Vs=(s,e,t)=>v4(s,typeof e!="symbol"?e+"":e,t);class I4{constructor(e,t){this.core=e,this.logger=t,Vs(this,"keychain",new Map),Vs(this,"name",Ij),Vs(this,"version",Ej),Vs(this,"initialized",!1),Vs(this,"storagePrefix",Zs),Vs(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Vs(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Vs(this,"set",async(i,r)=>{this.isInitialized(),this.keychain.set(i,r),await this.persist()}),Vs(this,"get",i=>{this.isInitialized();const r=this.keychain.get(i);if(typeof r>"u"){const{message:n}=L("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return r}),Vs(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,th(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?sh(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var E4=Object.defineProperty,A4=(s,e,t)=>e in s?E4(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Pt=(s,e,t)=>A4(s,typeof e!="symbol"?e+"":e,t);class N4{constructor(e,t,i){this.core=e,this.logger=t,Pt(this,"name",bj),Pt(this,"keychain"),Pt(this,"randomSessionIdentifier",lh()),Pt(this,"initialized",!1),Pt(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Pt(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Pt(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=u.Po(r);return u.Qe(n.publicKey)}),Pt(this,"generateKeyPair",()=>{this.isInitialized();const r=I3();return this.setPrivateKey(r.publicKey,r.privateKey)}),Pt(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=u.Po(n),a=this.randomSessionIdentifier,c=vj;return await u.Qo(a,r,c,o)}),Pt(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=E3(a,n);return this.setSymKey(c,o)}),Pt(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||La(r);return await this.keychain.set(o,r),o}),Pt(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Pt(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Pt(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Jy(o),c=u.safeJsonStringify(n);if(ug(a))return _3(c,o==null?void 0:o.encoding);if(hg(a)){const p=a.senderPublicKey,f=a.receiverPublicKey;r=await this.generateSharedKey(p,f)}const l=this.getSymKey(r),{type:h,senderPublicKey:d}=a;return A3({type:h,symKey:l,message:c,senderPublicKey:d,encoding:o==null?void 0:o.encoding})}),Pt(this,"decode",async(r,n,o)=>{this.isInitialized();const a=S3(n,o);if(ug(a)){const c=C3(n,o==null?void 0:o.encoding);return u.safeJsonParse(c)}if(hg(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=N3({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return u.safeJsonParse(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Pt(this,"getPayloadType",(r,n=Di)=>{const o=xo({encoded:r,encoding:n});return gr(o.type)}),Pt(this,"getPayloadSenderPublicKey",(r,n=Di)=>{const o=xo({encoded:r,encoding:n});return o.senderPublicKey?u.toString(o.senderPublicKey,Bt):void 0}),this.core=e,this.logger=u.E(t,this.name),this.keychain=i||new I4(this.core,this.logger)}get context(){return u.y(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(vg)}catch{e=lh(),await this.keychain.set(vg,e)}return m4(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _4=Object.defineProperty,C4=Object.defineProperties,S4=Object.getOwnPropertyDescriptors,Pg=Object.getOwnPropertySymbols,T4=Object.prototype.hasOwnProperty,P4=Object.prototype.propertyIsEnumerable,gh=(s,e,t)=>e in s?_4(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,$4=(s,e)=>{for(var t in e||(e={}))T4.call(e,t)&&gh(s,t,e[t]);if(Pg)for(var t of Pg(e))P4.call(e,t)&&gh(s,t,e[t]);return s},M4=(s,e)=>C4(s,S4(e)),rs=(s,e,t)=>gh(s,typeof e!="symbol"?e+"":e,t);class O4 extends cx{constructor(e,t){super(e,t),this.logger=e,this.core=t,rs(this,"messages",new Map),rs(this,"messagesWithoutClientAck",new Map),rs(this,"name",Aj),rs(this,"version",Nj),rs(this,"initialized",!1),rs(this,"storagePrefix",Zs),rs(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),rs(this,"set",async(i,r,n)=>{this.isInitialized();const o=Qs(r);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(i,a),n===za.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,M4($4({},c),{[o]:r}))}return await this.persist(),o}),rs(this,"get",i=>{this.isInitialized();let r=this.messages.get(i);return typeof r>"u"&&(r={}),r}),rs(this,"getWithoutAck",i=>{this.isInitialized();const r={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};r[n]=Object.values(o)}return r}),rs(this,"has",(i,r)=>{this.isInitialized();const n=this.get(i),o=Qs(r);return typeof n[o]<"u"}),rs(this,"ack",async(i,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=Qs(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),rs(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=u.E(e,this.name),this.core=t}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,th(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,th(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?sh(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?sh(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var x4=Object.defineProperty,D4=Object.defineProperties,k4=Object.getOwnPropertyDescriptors,$g=Object.getOwnPropertySymbols,j4=Object.prototype.hasOwnProperty,R4=Object.prototype.propertyIsEnumerable,fh=(s,e,t)=>e in s?x4(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ca=(s,e)=>{for(var t in e||(e={}))j4.call(e,t)&&fh(s,t,e[t]);if($g)for(var t of $g(e))R4.call(e,t)&&fh(s,t,e[t]);return s},gl=(s,e)=>D4(s,k4(e)),xs=(s,e,t)=>fh(s,typeof e!="symbol"?e+"":e,t);class U4 extends lx{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,xs(this,"events",new u.eventsExports.EventEmitter),xs(this,"name",_j),xs(this,"queue",new Map),xs(this,"publishTimeout",u.cjs.toMiliseconds(u.cjs.ONE_MINUTE)),xs(this,"initialPublishTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),xs(this,"needsTransportRestart",!1),xs(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)||Ig,c=ec(n),l=(n==null?void 0:n.prompt)||!1,h=(n==null?void 0:n.tag)||0,d=(n==null?void 0:n.id)||u.getBigIntRpcId().toString(),p={topic:i,message:r,opts:{ttl:a,relay:c,prompt:l,tag:h,id:d,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},f=`Failed to publish payload, please try again. id:${d} tag:${h}`;try{const g=new Promise(async w=>{const v=({id:y})=>{p.opts.id===y&&(this.removeRequestFromQueue(y),this.relayer.events.removeListener(Et.publish,v),w(p))};this.relayer.events.on(Et.publish,v);const b=xi(new Promise((y,A)=>{this.rpcPublish({topic:i,message:r,ttl:a,prompt:l,tag:h,id:d,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(y).catch(_=>{this.logger.warn(_,_==null?void 0:_.message),A(_)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${h}`);try{await b,this.events.removeListener(Et.publish,v)}catch(y){this.queue.set(d,gl(Ca({},p),{attempt:1})),this.logger.warn(y,y==null?void 0:y.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:i,message:r,opts:n}}),await xi(g,this.publishTimeout,f)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(d)}}),xs(this,"on",(i,r)=>{this.events.on(i,r)}),xs(this,"once",(i,r)=>{this.events.once(i,r)}),xs(this,"off",(i,r)=>{this.events.off(i,r)}),xs(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.relayer=e,this.logger=u.E(t,this.name),this.registerEventListeners()}get context(){return u.y(this.logger)}async rpcPublish(e){var t,i,r,n;const{topic:o,message:a,ttl:c=Ig,prompt:l,tag:h,id:d,attestation:p,tvf:f}=e,g={method:ho(ec().protocol).publish,params:Ca({topic:o,message:a,ttl:c,prompt:l,tag:h,attestation:p},f),id:d};xt((t=g.params)==null?void 0:t.prompt)&&((i=g.params)==null||delete i.prompt),xt((r=g.params)==null?void 0:r.tag)&&((n=g.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const w=await this.relayer.request(g);return this.relayer.events.emit(Et.publish,e),this.logger.debug("Successfully Published Payload"),w}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,gl(Ca({},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(gl(Ca({},e),{topic:r,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(u.r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Et.connection_stalled);return}this.checkQueue()}),this.relayer.on(Et.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var L4=Object.defineProperty,z4=(s,e,t)=>e in s?L4(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Hr=(s,e,t)=>z4(s,typeof e!="symbol"?e+"":e,t);class F4{constructor(){Hr(this,"map",new Map),Hr(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),Hr(this,"get",e=>this.map.get(e)||[]),Hr(this,"exists",(e,t)=>this.get(e).includes(t)),Hr(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)}),Hr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var q4=Object.defineProperty,B4=Object.defineProperties,H4=Object.getOwnPropertyDescriptors,Mg=Object.getOwnPropertySymbols,W4=Object.prototype.hasOwnProperty,V4=Object.prototype.propertyIsEnumerable,wh=(s,e,t)=>e in s?q4(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,no=(s,e)=>{for(var t in e||(e={}))W4.call(e,t)&&wh(s,t,e[t]);if(Mg)for(var t of Mg(e))V4.call(e,t)&&wh(s,t,e[t]);return s},fl=(s,e)=>B4(s,H4(e)),Le=(s,e,t)=>wh(s,typeof e!="symbol"?e+"":e,t);class K4 extends dx{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Le(this,"subscriptions",new Map),Le(this,"topicMap",new F4),Le(this,"events",new u.eventsExports.EventEmitter),Le(this,"name",Oj),Le(this,"version",xj),Le(this,"pending",new Map),Le(this,"cached",[]),Le(this,"initialized",!1),Le(this,"storagePrefix",Zs),Le(this,"subscribeTimeout",u.cjs.toMiliseconds(u.cjs.ONE_MINUTE)),Le(this,"initialSubscribeTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),Le(this,"clientId"),Le(this,"batchSubscribeTopicsLimit",500),Le(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Le(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=ec(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}}),Le(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)}),Le(this,"isSubscribed",i=>new Promise(r=>{r(this.topicMap.topics.includes(i))})),Le(this,"isKnownTopic",i=>new Promise(r=>{r(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),Le(this,"on",(i,r)=>{this.events.on(i,r)}),Le(this,"once",(i,r)=>{this.events.once(i,r)}),Le(this,"off",(i,r)=>{this.events.off(i,r)}),Le(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),Le(this,"start",async()=>{await this.onConnect()}),Le(this,"stop",async()=>{await this.onDisconnect()}),Le(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Le(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)}),Le(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(u.r.pulse,async()=>{await this.checkPending()}),this.events.on(os.created,async i=>{const r=os.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()}),this.events.on(os.deleted,async i=>{const r=os.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()})}),this.relayer=e,this.logger=u.E(t,this.name),this.clientId=""}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let 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=ec(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:ho(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))},u.cjs.toMiliseconds(u.cjs.ONE_SECOND)),a;const c=new Promise(async h=>{const d=p=>{p.topic===e&&(this.events.removeListener(os.created,d),h(p.id))};this.events.on(os.created,d);try{const p=await xi(new Promise((f,g)=>{this.relayer.request(n).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),g(w)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(os.created,d),h(p)}catch{}}),l=await xi(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(Et.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:ho(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 xi(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(Et.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:ho(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 xi(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(Et.connection_stalled)}return r}rpcUnsubscribe(e,t,i){const r={method:ho(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,fl(no({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,no({},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,no({},t)),this.topicMap.set(t.topic,e),this.events.emit(os.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}=L("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(os.deleted,fl(no({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(os.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(os.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=L("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=>fl(no({},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 DD(u.cjs.toMiliseconds(u.cjs.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=L("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 Qs(e+await this.getClientId())}}var G4=Object.defineProperty,Og=Object.getOwnPropertySymbols,Y4=Object.prototype.hasOwnProperty,Q4=Object.prototype.propertyIsEnumerable,yh=(s,e,t)=>e in s?G4(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,xg=(s,e)=>{for(var t in e||(e={}))Y4.call(e,t)&&yh(s,t,e[t]);if(Og)for(var t of Og(e))Q4.call(e,t)&&yh(s,t,e[t]);return s},Ne=(s,e,t)=>yh(s,typeof e!="symbol"?e+"":e,t);class J4 extends hx{constructor(e){super(e),Ne(this,"protocol","wc"),Ne(this,"version",2),Ne(this,"core"),Ne(this,"logger"),Ne(this,"events",new u.eventsExports.EventEmitter),Ne(this,"provider"),Ne(this,"messages"),Ne(this,"subscriber"),Ne(this,"publisher"),Ne(this,"name",Sj),Ne(this,"transportExplicitlyClosed",!1),Ne(this,"initialized",!1),Ne(this,"connectionAttemptInProgress",!1),Ne(this,"relayUrl"),Ne(this,"projectId"),Ne(this,"packageName"),Ne(this,"bundleId"),Ne(this,"hasExperiencedNetworkDisruption",!1),Ne(this,"pingTimeout"),Ne(this,"heartBeatTimeout",u.cjs.toMiliseconds(u.cjs.THIRTY_SECONDS+u.cjs.FIVE_SECONDS)),Ne(this,"reconnectTimeout"),Ne(this,"connectPromise"),Ne(this,"reconnectInProgress",!1),Ne(this,"requestsInFlight",[]),Ne(this,"connectTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),Ne(this,"request",async t=>{var i,r;this.logger.debug("Publishing Request Payload");const n=t.id||u.getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(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}}),Ne(this,"resetPingTimeout",()=>{Za()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),Ne(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),Ne(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Et.connect)}),Ne(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ne(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(Et.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ne(this,"registerProviderListeners",()=>{this.provider.on(ys.payload,this.onPayloadHandler),this.provider.on(ys.connect,this.onConnectHandler),this.provider.on(ys.disconnect,this.onDisconnectHandler),this.provider.on(ys.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?u.E(e.logger,this.name):u.Ot(u.k({level:e.logger||Cj})),this.messages=new O4(this.logger,e.core),this.subscriber=new K4(this,this.logger),this.publisher=new U4(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||im,this.projectId=e.projectId,bD()?this.packageName=Rp():vD()&&(this.bundleId=Rp()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return u.y(this.logger)}get connected(){var e,t,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},za.outbound)}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(os.created,l),c())};return await Promise.all([new Promise(h=>{c=h,this.subscriber.on(os.created,l)}),new Promise(async(h,d)=>{a=await this.subscriber.subscribe(e,xg({internal:{throwOnFailedPublish:o}},t)).catch(p=>{o&&d(p)})||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 xi(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 bg())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=pt(u.cjs.FIVE_MINUTES),n={topic:i,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(Et.message,e),await this.recordMessageEvent(e,za.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(ys.disconnect,n),await xi(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(ys.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(ys.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(ys.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,u.cjs.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,r,n;if(Za())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 u.o(new u.f(ND({sdkVersion:uh,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:i,message:r}=e;await this.messages.set(i,r,t)}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.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown 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}),u.isJsonRpcRequest(e)){if(!e.method.endsWith(Tj))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(xg({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else u.isJsonRpcResponse(e)&&this.events.emit(Et.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,za.inbound),this.events.emit(Et.message,e))}async acknowledgePayload(e){const t=u.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(ys.payload,this.onPayloadHandler),this.provider.off(ys.connect,this.onConnectHandler),this.provider.off(ys.disconnect,this.onDisconnectHandler),this.provider.off(ys.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await bg();gj(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(Et.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},u.cjs.toMiliseconds(Pj)))))}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}}function Z4(){}function Dg(s){if(!s||typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(s)==="[object Object]":!1}function kg(s){return Object.getOwnPropertySymbols(s).filter(e=>Object.prototype.propertyIsEnumerable.call(s,e))}function jg(s){return s==null?s===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(s)}const X4="[object RegExp]",e5="[object String]",t5="[object Number]",s5="[object Boolean]",Rg="[object Arguments]",i5="[object Symbol]",r5="[object Date]",n5="[object Map]",o5="[object Set]",a5="[object Array]",c5="[object Function]",l5="[object ArrayBuffer]",wl="[object Object]",h5="[object Error]",u5="[object DataView]",d5="[object Uint8Array]",p5="[object Uint8ClampedArray]",g5="[object Uint16Array]",f5="[object Uint32Array]",w5="[object BigUint64Array]",y5="[object Int8Array]",m5="[object Int16Array]",b5="[object Int32Array]",v5="[object BigInt64Array]",I5="[object Float32Array]",E5="[object Float64Array]";function A5(s,e){return s===e||Number.isNaN(s)&&Number.isNaN(e)}function N5(s,e,t){return po(s,e,void 0,void 0,void 0,void 0,t)}function po(s,e,t,i,r,n,o){const a=o(s,e,t,i,r,n);if(a!==void 0)return a;if(typeof s==typeof e)switch(typeof s){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return s===e;case"number":return s===e||Object.is(s,e);case"function":return s===e;case"object":return vo(s,e,n,o)}return vo(s,e,n,o)}function vo(s,e,t,i){if(Object.is(s,e))return!0;let r=jg(s),n=jg(e);if(r===Rg&&(r=wl),n===Rg&&(n=wl),r!==n)return!1;switch(r){case e5:return s.toString()===e.toString();case t5:{const c=s.valueOf(),l=e.valueOf();return A5(c,l)}case s5:case r5:case i5:return Object.is(s.valueOf(),e.valueOf());case X4:return s.source===e.source&&s.flags===e.flags;case c5:return s===e}t=t??new Map;const o=t.get(s),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(s,e),t.set(e,s);try{switch(r){case n5:{if(s.size!==e.size)return!1;for(const[c,l]of s.entries())if(!e.has(c)||!po(l,e.get(c),c,s,e,t,i))return!1;return!0}case o5:{if(s.size!==e.size)return!1;const c=Array.from(s.values()),l=Array.from(e.values());for(let h=0;h<c.length;h++){const d=c[h],p=l.findIndex(f=>po(d,f,void 0,s,e,t,i));if(p===-1)return!1;l.splice(p,1)}return!0}case a5:case d5:case p5:case g5:case f5:case w5:case y5:case m5:case b5:case v5:case I5:case E5:{if(typeof N.dist.Buffer<"u"&&N.dist.Buffer.isBuffer(s)!==N.dist.Buffer.isBuffer(e)||s.length!==e.length)return!1;for(let c=0;c<s.length;c++)if(!po(s[c],e[c],c,s,e,t,i))return!1;return!0}case l5:return s.byteLength!==e.byteLength?!1:vo(new Uint8Array(s),new Uint8Array(e),t,i);case u5:return s.byteLength!==e.byteLength||s.byteOffset!==e.byteOffset?!1:vo(new Uint8Array(s),new Uint8Array(e),t,i);case h5:return s.name===e.name&&s.message===e.message;case wl:{if(!(vo(s.constructor,e.constructor,t,i)||Dg(s)&&Dg(e)))return!1;const c=[...Object.keys(s),...kg(s)],l=[...Object.keys(e),...kg(e)];if(c.length!==l.length)return!1;for(let h=0;h<c.length;h++){const d=c[h],p=s[d];if(!Object.hasOwn(e,d))return!1;const f=e[d];if(!po(p,f,d,s,e,t,i))return!1}return!0}default:return!1}}finally{t.delete(s),t.delete(e)}}function _5(s,e){return N5(s,e,Z4)}var C5=Object.defineProperty,Ug=Object.getOwnPropertySymbols,S5=Object.prototype.hasOwnProperty,T5=Object.prototype.propertyIsEnumerable,mh=(s,e,t)=>e in s?C5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Lg=(s,e)=>{for(var t in e||(e={}))S5.call(e,t)&&mh(s,t,e[t]);if(Ug)for(var t of Ug(e))T5.call(e,t)&&mh(s,t,e[t]);return s},Qt=(s,e,t)=>mh(s,typeof e!="symbol"?e+"":e,t);class vr extends ux{constructor(e,t,i,r=Zs,n=void 0){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,Qt(this,"map",new Map),Qt(this,"version",$j),Qt(this,"cached",[]),Qt(this,"initialized",!1),Qt(this,"getKey"),Qt(this,"storagePrefix",Zs),Qt(this,"recentlyDeleted",[]),Qt(this,"recentlyDeletedLimit",200),Qt(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):W3(o)?this.map.set(o.id,o):V3(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Qt(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())}),Qt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Qt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>_5(a[c],o[c]))):this.values)),Qt(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=Lg(Lg({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Qt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=u.E(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=L("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:i}=L("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}=L("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}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var P5=Object.defineProperty,$5=(s,e,t)=>e in s?P5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,we=(s,e,t)=>$5(s,typeof e!="symbol"?e+"":e,t);class M5{constructor(e,t){this.core=e,this.logger=t,we(this,"name",Dj),we(this,"version",kj),we(this,"events",new u.Nt),we(this,"pairings"),we(this,"initialized",!1),we(this,"storagePrefix",Zs),we(this,"ignoredPayloadTypes",[fi]),we(this,"registeredMethods",[]),we(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),we(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),we(this,"create",async i=>{this.isInitialized();const r=lh(),n=await this.core.crypto.setSymKey(r),o=pt(u.cjs.FIVE_MINUTES),a={protocol:sm},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},l=pg({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(sr.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}}),we(this,"pair",async i=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[Ys.pairing_started]}});this.isValidPair(i,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=dg(i.uri);r.props.properties.topic=n,r.addTrace(Ys.pairing_uri_validation_success),r.addTrace(Ys.pairing_uri_not_expired);let h;if(this.pairings.keys.includes(n)){if(h=this.pairings.get(n),r.addTrace(Ys.existing_pairing),h.active)throw r.setError(li.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(Ys.pairing_not_expired)}const d=c||pt(u.cjs.FIVE_MINUTES),p={topic:n,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(n,d),await this.pairings.set(n,p),r.addTrace(Ys.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(sr.create,p),r.addTrace(Ys.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(Ys.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(li.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(f){throw r.setError(li.subscribe_pairing_topic_failure),f}return r.addTrace(Ys.subscribe_pairing_topic_success),p}),we(this,"activate",async({topic:i})=>{this.isInitialized();const r=pt(u.cjs.FIVE_MINUTES);this.core.expirer.set(i,r),await this.pairings.update(i,{active:!0,expiry:r})}),we(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}=Xi();this.events.once($e("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),we(this,"updateExpiry",async({topic:i,expiry:r})=>{this.isInitialized(),await this.pairings.update(i,{expiry:r})}),we(this,"updateMetadata",async({topic:i,metadata:r})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:r})}),we(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),we(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))}),we(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(r);return pg({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),we(this,"sendRequest",async(i,r,n)=>{const o=u.formatJsonRpcRequest(r,n),a=await this.core.crypto.encode(i,o),c=io[r].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),we(this,"sendResult",async(i,r,n)=>{const o=u.formatJsonRpcResult(i,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,i)).request.method,l=io[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),we(this,"sendError",async(i,r,n)=>{const o=u.formatJsonRpcError(i,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,i)).request.method,l=io[c]?io[c].res:io.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),we(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)])}),we(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(r=>Ti(r.expiry));await Promise.all(i.map(r=>this.deletePairing(r.topic)))}),we(this,"onRelayEventRequest",async i=>{const{topic:r,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,n);default:return await this.onUnknownRpcMethodRequest(r,n)}}),we(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)}}),we(this,"onPairingPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(sr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),we(this,"onPairingPingResponse",(i,r)=>{const{id:n}=r;setTimeout(()=>{u.isJsonRpcResult(r)?this.events.emit($e("pairing_ping",n),{}):u.isJsonRpcError(r)&&this.events.emit($e("pairing_ping",n),{error:r.error})},500)}),we(this,"onPairingDeleteRequest",async(i,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(sr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),we(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)}}),we(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(Re("WC_METHOD_UNSUPPORTED",i))}),we(this,"isValidPair",(i,r)=>{var n;if(!Xt(i)){const{message:a}=L("MISSING_OR_INVALID",`pair() params: ${i}`);throw r.setError(li.malformed_pairing_uri),new Error(a)}if(!H3(i.uri)){const{message:a}=L("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw r.setError(li.malformed_pairing_uri),new Error(a)}const o=dg(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=L("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(li.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=L("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(li.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&u.cjs.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(li.pairing_expired);const{message:a}=L("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),we(this,"isValidPing",async i=>{if(!Xt(i)){const{message:n}=L("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),we(this,"isValidDisconnect",async i=>{if(!Xt(i)){const{message:n}=L("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),we(this,"isValidPairingTopic",async i=>{if(!ht(i,!1)){const{message:r}=L("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(r)}if(!this.pairings.keys.includes(i)){const{message:r}=L("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(r)}if(Ti(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:r}=L("EXPIRED",`pairing topic: ${i}`);throw new Error(r)}}),this.core=e,this.logger=u.E(t,this.name),this.pairings=new vr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return u.y(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Et.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)))try{const n=await this.core.crypto.decode(t,i);u.isJsonRpcRequest(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):u.isJsonRpcResponse(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(vs.expired,async e=>{const{topic:t}=Sy(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(sr.expire,{topic:t}))})}}var O5=Object.defineProperty,x5=(s,e,t)=>e in s?O5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,$t=(s,e,t)=>x5(s,typeof e!="symbol"?e+"":e,t);class D5 extends ax{constructor(e,t){super(e,t),this.core=e,this.logger=t,$t(this,"records",new Map),$t(this,"events",new u.eventsExports.EventEmitter),$t(this,"name",jj),$t(this,"version",Rj),$t(this,"cached",[]),$t(this,"initialized",!1),$t(this,"storagePrefix",Zs),$t(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)}),$t(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:pt(u.cjs.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ms.created,o)}),$t(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=u.isJsonRpcError(i)?{error:i.error}:{result:i.result},this.records.set(r.id,r),this.persist(),this.events.emit(Ms.updated,r))}),$t(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))),$t(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(Ms.deleted,n)}}),this.persist()}),$t(this,"exists",async(i,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===i:!1)),$t(this,"on",(i,r)=>{this.events.on(i,r)}),$t(this,"once",(i,r)=>{this.events.once(i,r)}),$t(this,"off",(i,r)=>{this.events.off(i,r)}),$t(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:u.formatJsonRpcRequest(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}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ms.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=L("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(Ms.created,e=>{const t=Ms.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ms.updated,e=>{const t=Ms.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ms.deleted,e=>{const t=Ms.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(u.r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{u.cjs.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Ms.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var k5=Object.defineProperty,j5=(s,e,t)=>e in s?k5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,zt=(s,e,t)=>j5(s,typeof e!="symbol"?e+"":e,t);class R5 extends px{constructor(e,t){super(e,t),this.core=e,this.logger=t,zt(this,"expirations",new Map),zt(this,"events",new u.eventsExports.EventEmitter),zt(this,"name",Uj),zt(this,"version",Lj),zt(this,"cached",[]),zt(this,"initialized",!1),zt(this,"storagePrefix",Zs),zt(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)}),zt(this,"has",i=>{try{const r=this.formatTarget(i);return typeof this.getExpiration(r)<"u"}catch{return!1}}),zt(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(vs.created,{target:n,expiration:o})}),zt(this,"get",i=>{this.isInitialized();const r=this.formatTarget(i);return this.getExpiration(r)}),zt(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(vs.deleted,{target:r,expiration:n})}}),zt(this,"on",(i,r)=>{this.events.on(i,r)}),zt(this,"once",(i,r)=>{this.events.once(i,r)}),zt(this,"off",(i,r)=>{this.events.off(i,r)}),zt(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return _D(e);if(typeof e=="number")return CD(e);const{message:t}=L("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(vs.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=L("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}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;u.cjs.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(vs.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(u.r.pulse,()=>this.checkExpirations()),this.events.on(vs.created,e=>{const t=vs.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(vs.expired,e=>{const t=vs.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(vs.deleted,e=>{const t=vs.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var U5=Object.defineProperty,L5=(s,e,t)=>e in s?U5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ct=(s,e,t)=>L5(s,typeof e!="symbol"?e+"":e,t);class z5 extends gx{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,ct(this,"name",zj),ct(this,"abortController"),ct(this,"isDevEnv"),ct(this,"verifyUrlV3",qj),ct(this,"storagePrefix",Zs),ct(this,"version",tm),ct(this,"publicKey"),ct(this,"fetchPromise"),ct(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&u.cjs.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ct(this,"register",async r=>{if(!Go()||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=u.getDocument_1(),h=this.startAbortTimer(u.cjs.ONE_SECOND*5),d=await new Promise((p,f)=>{const g=()=>{window.removeEventListener("message",v),l.body.removeChild(w),f("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const w=l.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",g,{signal:this.abortController.signal});const v=b=>{if(b.data&&typeof b.data=="string")try{const y=JSON.parse(b.data);if(y.type==="verify_attestation"){if(u.sn(y.attestation).payload.id!==o)return;clearInterval(h),l.body.removeChild(w),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",v),p(y.attestation===null?"":y.attestation)}}catch(y){this.logger.warn(y)}};l.body.appendChild(w),window.addEventListener("message",v,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),ct(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(u.sn(n).payload.id!==a)return;const 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)}),ct(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(u.cjs.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ct(this,"getVerifyUrl",r=>{let n=r||bo;return Bj.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${bo}`),n=bo),n}),ct(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(u.cjs.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),ct(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),ct(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ct(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")}}),ct(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ct(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}),ct(this,"validateAttestation",(r,n)=>{const o=M3(r,n.publicKey),a={hasExpired:u.cjs.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=u.E(t,this.name),this.abortController=new AbortController,this.isDevEnv=Qh(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return u.y(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),u.cjs.toMiliseconds(e))}}var F5=Object.defineProperty,q5=(s,e,t)=>e in s?F5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,zg=(s,e,t)=>q5(s,typeof e!="symbol"?e+"":e,t);class B5 extends fx{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,zg(this,"context",Hj),zg(this,"registerDeviceToken",async i=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${Wj}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=u.E(t,this.context)}}var H5=Object.defineProperty,Fg=Object.getOwnPropertySymbols,W5=Object.prototype.hasOwnProperty,V5=Object.prototype.propertyIsEnumerable,bh=(s,e,t)=>e in s?H5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,oo=(s,e)=>{for(var t in e||(e={}))W5.call(e,t)&&bh(s,t,e[t]);if(Fg)for(var t of Fg(e))V5.call(e,t)&&bh(s,t,e[t]);return s},mt=(s,e,t)=>bh(s,typeof e!="symbol"?e+"":e,t);class K5 extends wx{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,mt(this,"context",Kj),mt(this,"storagePrefix",Zs),mt(this,"storageVersion",Vj),mt(this,"events",new Map),mt(this,"shouldPersist",!1),mt(this,"init",async()=>{if(!Qh())try{const r={eventId:Lp(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:_y(this.core.relayer.protocol,this.core.relayer.version,uh)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),mt(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=Lp(),h=this.core.projectId||"",d=Date.now(),p=oo({eventId:l,timestamp:d,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,p),this.shouldPersist=!0),p}),mt(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 oo(oo({},a),this.setMethods(a.eventId))}),mt(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),mt(this,"setEventListeners",()=>{this.core.heartbeat.on(u.r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{u.cjs.fromMiliseconds(Date.now())-u.cjs.fromMiliseconds(r.timestamp)>Gj&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),mt(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),mt(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)}),mt(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)}),mt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),mt(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,oo(oo({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),mt(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)}}),mt(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Yj}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${uh}${n}`,{method:"POST",body:JSON.stringify(r)})}),mt(this,"getAppDomain",()=>Ny().url),this.logger=u.E(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 G5=Object.defineProperty,qg=Object.getOwnPropertySymbols,Y5=Object.prototype.hasOwnProperty,Q5=Object.prototype.propertyIsEnumerable,vh=(s,e,t)=>e in s?G5(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Bg=(s,e)=>{for(var t in e||(e={}))Y5.call(e,t)&&vh(s,t,e[t]);if(qg)for(var t of qg(e))Q5.call(e,t)&&vh(s,t,e[t]);return s},Ve=(s,e,t)=>vh(s,typeof e!="symbol"?e+"":e,t);let J5=class fm extends ix{constructor(e){var t;super(e),Ve(this,"protocol",em),Ve(this,"version",tm),Ve(this,"name",hh),Ve(this,"relayUrl"),Ve(this,"projectId"),Ve(this,"customStoragePrefix"),Ve(this,"events",new u.eventsExports.EventEmitter),Ve(this,"logger"),Ve(this,"heartbeat"),Ve(this,"relayer"),Ve(this,"crypto"),Ve(this,"storage"),Ve(this,"history"),Ve(this,"expirer"),Ve(this,"pairing"),Ve(this,"verify"),Ve(this,"echoClient"),Ve(this,"linkModeSupportedApps"),Ve(this,"eventClient"),Ve(this,"initialized",!1),Ve(this,"logChunkController"),Ve(this,"on",(o,a)=>this.events.on(o,a)),Ve(this,"once",(o,a)=>this.events.once(o,a)),Ve(this,"off",(o,a)=>this.events.off(o,a)),Ve(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),Ve(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)||im,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=u.k({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:yj.logger,name:hh}),{logger:r,chunkLoggerController:n}=u.A({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=u.E(r,this.name),this.heartbeat=new u.i,this.crypto=new N4(this,this.logger,e==null?void 0:e.keychain),this.history=new D5(this,this.logger),this.expirer=new R5(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new u.h(Bg(Bg({},mj),e==null?void 0:e.storageOptions)),this.relayer=new J4({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new M5(this,this.logger),this.verify=new z5(this,this.logger,this.storage),this.echoClient=new B5(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new K5(this,this.logger,e==null?void 0:e.telemetryEnabled)}static async init(e){const t=new fm(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(Mj,i),t}get context(){return u.y(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Eg,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(Eg)||[],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 Z5=J5,wm="wc",ym=2,mm="client",nu=`${wm}@${ym}:${mm}:`,yl={name:mm,logger:"error"},Hg="WALLETCONNECT_DEEPLINK_CHOICE",X5="proposal",Wg="Proposal expired",eU="session",Wr=u.cjs.SEVEN_DAYS,tU="engine",bt={wc_sessionPropose:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1104},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1106},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1112},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1114},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:u.cjs.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:u.cjs.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1119}}},ml={min:u.cjs.FIVE_MINUTES,max:u.cjs.SEVEN_DAYS},Ks={idle:"IDLE",active:"ACTIVE"},Vg={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},sU="request",iU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],rU="wc",nU="auth",oU="authKeys",aU="pairingTopics",cU="requests",Nc=`${rU}@${1.5}:${nU}:`,Fa=`${Nc}:PUB_KEY`;var lU=Object.defineProperty,hU=Object.defineProperties,uU=Object.getOwnPropertyDescriptors,Kg=Object.getOwnPropertySymbols,dU=Object.prototype.hasOwnProperty,pU=Object.prototype.propertyIsEnumerable,Ih=(s,e,t)=>e in s?lU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ze=(s,e)=>{for(var t in e||(e={}))dU.call(e,t)&&Ih(s,t,e[t]);if(Kg)for(var t of Kg(e))pU.call(e,t)&&Ih(s,t,e[t]);return s},Ht=(s,e)=>hU(s,uU(e)),O=(s,e,t)=>Ih(s,typeof e!="symbol"?e+"":e,t);class gU extends vx{constructor(e){super(e),O(this,"name",tU),O(this,"events",new u.Nt),O(this,"initialized",!1),O(this,"requestQueue",{state:Ks.idle,queue:[]}),O(this,"sessionRequestQueue",{state:Ks.idle,queue:[]}),O(this,"requestQueueDelay",u.cjs.ONE_SECOND),O(this,"expectedPairingMethodMap",new Map),O(this,"recentlyDeletedMap",new Map),O(this,"recentlyDeletedLimit",200),O(this,"relayMessageCache",[]),O(this,"pendingSessions",new Map),O(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(bt)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},u.cjs.toMiliseconds(this.requestQueueDelay)))}),O(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Ht(ze({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=i;let h=r,d,p=!1;try{if(h){const T=this.client.core.pairing.pairings.get(h);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),p=T.active}}catch(T){throw this.client.logger.error(`connect() -> pairing.get(${h}) failed`),T}if(!h||!p){const{topic:T,uri:P}=await this.client.core.pairing.create();h=T,d=P}if(!h){const{message:T}=L("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(T)}const f=await this.client.core.crypto.generateKeyPair(),g=bt.wc_sessionPropose.req.ttl||u.cjs.FIVE_MINUTES,w=pt(g),v=Ht(ze(ze({requiredNamespaces:n,optionalNamespaces:o,relays:l??[{protocol:sm}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:w,pairingTopic:h},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:u.payloadId()}),b=$e("session_connect",v.id),{reject:y,resolve:A,done:_}=Xi(g,Wg),C=({id:T})=>{T===v.id&&(this.client.events.off("proposal_expire",C),this.pendingSessions.delete(v.id),this.events.emit(b,{error:{message:Wg,code:0}}))};return this.client.events.on("proposal_expire",C),this.events.once(b,({error:T,session:P})=>{this.client.events.off("proposal_expire",C),T?y(T):P&&A(P)}),await this.sendRequest({topic:h,method:"wc_sessionPropose",params:v,throwOnFailedPublish:!0,clientRpcId:v.id}),await this.setProposal(v.id,v),{uri:d,approval:_}}),O(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}}),O(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:[Os.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch($){throw o.setError(Yi.no_internet_connection),$}try{await this.isValidProposalId(t==null?void 0:t.id)}catch($){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(Yi.proposal_not_found),$}try{await this.isValidApprove(t)}catch($){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Yi.session_approve_namespace_validation_failure),$}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:h,scopedProperties:d,sessionConfig:p}=t,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:v,optionalNamespaces:b}=f;let y=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});y||(y=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Os.session_approve_started,properties:{topic:g,trace:[Os.session_approve_started,Os.session_namespaces_validation_success]}}));const A=await this.client.core.crypto.generateKeyPair(),_=w.publicKey,C=await this.client.core.crypto.generateSharedKey(A,_),T=ze(ze(ze({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:A,metadata:this.client.metadata},expiry:pt(Wr)},h&&{sessionProperties:h}),d&&{scopedProperties:d}),p&&{sessionConfig:p}),P=Je.relay;y.addTrace(Os.subscribing_session_topic);try{await this.client.core.relayer.subscribe(C,{transportType:P})}catch($){throw y.setError(Yi.subscribe_session_topic_failure),$}y.addTrace(Os.subscribe_session_topic_success);const x=Ht(ze({},T),{topic:C,requiredNamespaces:v,optionalNamespaces:b,pairingTopic:g,acknowledged:!1,self:T.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:A,transportType:Je.relay});await this.client.session.set(C,x),y.addTrace(Os.store_session);try{y.addTrace(Os.publishing_session_settle),await this.sendRequest({topic:C,method:"wc_sessionSettle",params:T,throwOnFailedPublish:!0}).catch($=>{throw y==null||y.setError(Yi.session_settle_publish_failure),$}),y.addTrace(Os.session_settle_publish_success),y.addTrace(Os.publishing_session_approve),await this.sendResult({id:a,topic:g,result:{relay:{protocol:c??"irn"},responderPublicKey:A},throwOnFailedPublish:!0}).catch($=>{throw y==null||y.setError(Yi.session_approve_publish_failure),$}),y.addTrace(Os.session_approve_publish_success)}catch($){throw this.client.logger.error($),this.client.session.delete(C,Re("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(C),$}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:w.metadata}),await this.client.proposal.delete(a,Re("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(C,pt(Wr)),{topic:C,acknowledged:()=>Promise.resolve(this.client.session.get(C))}}),O(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:bt.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Re("USER_DISCONNECTED")))}),O(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:i,namespaces:r}=t,{done:n,resolve:o,reject:a}=Xi(),c=u.payloadId(),l=u.getBigIntRpcId().toString(),h=this.client.session.get(i).namespaces;return this.events.once($e("session_update",c),({error:d})=>{d?a(d):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(d=>{this.client.logger.error(d),this.client.session.update(i,{namespaces:h}),a(d)}),{acknowledged:n}}),O(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=u.payloadId(),{done:n,resolve:o,reject:a}=Xi();return this.events.once($e("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,pt(Wr)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),O(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:i,request:r,topic:n,expiry:o=bt.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===Je.relay&&await this.confirmOnlineStateOrThrow();const c=u.payloadId(),l=u.getBigIntRpcId().toString(),{done:h,resolve:d,reject:p}=Xi(o,"Request expired. Please try again.");this.events.once($e("session_request",c),({error:b,result:y})=>{b?p(b):d(y)});const f="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:f,params:{request:Ht(ze({},r),{expiryTimestamp:pt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(b=>p(b)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),await h();const w={request:Ht(ze({},r),{expiryTimestamp:pt(o)}),chainId:i},v=this.shouldSetTVF(f,w);return await Promise.all([new Promise(async b=>{await this.sendRequest(ze({clientRpcId:c,relayRpcId:l,topic:n,method:f,params:w,expiry:o,throwOnFailedPublish:!0},v&&{tvf:this.getTVFParams(c,w)})).catch(y=>p(y)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),b()}),new Promise(async b=>{var y;if(!((y=a.sessionConfig)!=null&&y.disableDeepLink)){const A=await $D(this.client.core.storage,Hg);await SD({id:c,topic:n,wcDeepLink:A})}b()}),h()]).then(b=>b[2])}),O(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);u.isJsonRpcResult(r)?await this.sendResult({id:n,topic:i,result:r.result,throwOnFailedPublish:!0,appLink:a}):u.isJsonRpcError(r)&&await this.sendError({id:n,topic:i,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),O(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=u.payloadId(),n=u.getBigIntRpcId().toString(),{done:o,resolve:a,reject:c}=Xi();this.events.once($e("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}))}),O(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:r,chainId:n}=t,o=u.getBigIntRpcId().toString(),a=u.payloadId();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),O(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}=L("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(r)}}),O(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(i=>q3(i,t)))),O(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),O(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:d,type:p,exp:f,nbf:g,methods:w=[],expiry:v}=t,b=[...t.resources||[]],{topic:y,uri:A}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:y,uri:A}});const _=await this.client.core.crypto.generateKeyPair(),C=La(_);if(await Promise.all([this.client.auth.authKeys.set(Fa,{responseTopic:C,publicKey:_}),this.client.auth.pairingTopics.set(C,{topic:C,pairingTopic:y})]),await this.client.core.relayer.subscribe(C,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${y}`),w.length>0){const{namespace:S}=bn(a[0]);let z=Ik(S,"request",w);Ua(b)&&(z=Ak(z,b.pop())),b.push(z)}const T=v&&v>bt.wc_sessionAuthenticate.req.ttl?v:bt.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:p??"caip122",chains:a,statement:c,aud:l,domain:h,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:g,resources:b},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:pt(T)},x={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:x,relays:[{protocol:"irn"}],pairingTopic:y,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:pt(bt.wc_sessionPropose.req.ttl),id:u.payloadId()},{done:q,resolve:j,reject:G}=Xi(T,"Request expired"),B=u.payloadId(),W=$e("session_connect",$.id),V=$e("session_request",B),H=async({error:S,session:z})=>{this.events.off(V,K),S?G(S):z&&j({session:z})},K=async S=>{var z,ee,J;if(await this.deletePendingAuthRequest(B,{message:"fulfilled",code:0}),S.error){const De=Re("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return S.error.code===De.code?void 0:(this.events.off(W,H),G(S.error.message))}await this.deleteProposal($.id),this.events.off(W,H);const{cacaos:be,responder:de}=S.result,te=[],st=[];for(const De of be){await Kp({cacao:De,projectId:this.client.core.projectId})||(this.client.logger.error(De,"Signature verification failed"),G(Re("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:js}=De,Rs=Ua(js.resources),Xs=[ih(js.iss)],Er=Xa(js.iss);if(Rs){const Us=Gp(Rs),Dn=Yp(Rs);te.push(...Us),Xs.push(...Dn)}for(const Us of Xs)st.push(`${Us}:${Er}`)}const Ue=await this.client.core.crypto.generateSharedKey(_,de.publicKey);let ve;te.length>0&&(ve={topic:Ue,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:de,controller:de.publicKey,expiry:pt(Wr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:y,namespaces:gg([...new Set(te)],[...new Set(st)]),transportType:o},await this.client.core.relayer.subscribe(Ue,{transportType:o}),await this.client.session.set(Ue,ve),y&&await this.client.core.pairing.updateMetadata({topic:y,metadata:de.metadata}),ve=this.client.session.get(Ue)),(z=this.client.metadata.redirect)!=null&&z.linkMode&&(ee=de.metadata.redirect)!=null&&ee.linkMode&&(J=de.metadata.redirect)!=null&&J.universal&&i&&(this.client.core.addLinkModeSupportedApp(de.metadata.redirect.universal),this.client.session.update(Ue,{transportType:Je.link_mode})),j({auths:be,session:ve})};this.events.once(W,H),this.events.once(V,K);let Q;try{if(n){const S=u.formatJsonRpcRequest("wc_sessionAuthenticate",P,B);this.client.core.history.set(y,S);const z=await this.client.core.crypto.encode("",S,{type:Zo,encoding:to});Q=_a(i,y,z)}else await Promise.all([this.sendRequest({topic:y,method:"wc_sessionAuthenticate",params:P,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:B}),this.sendRequest({topic:y,method:"wc_sessionPropose",params:$,expiry:bt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(S){throw this.events.off(W,H),this.events.off(V,K),S}return await this.setProposal($.id,$),await this.setAuthRequest(B,{request:Ht(ze({},P),{verifyContext:{}}),pairingTopic:y,transportType:o}),{uri:Q??A,response:q}}),O(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Qi.authenticated_session_approve_started]}});try{this.isInitialized()}catch(v){throw n.setError(ro.no_internet_connection),v}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(ro.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=La(c),d={type:fi,receiverPublicKey:c,senderPublicKey:l},p=[],f=[];for(const v of r){if(!await Kp({cacao:v,projectId:this.client.core.projectId})){n.setError(ro.invalid_cacao);const C=Re("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:h,error:C,encodeOpts:d}),new Error(C.message)}n.addTrace(Qi.cacaos_verified);const{p:b}=v,y=Ua(b.resources),A=[ih(b.iss)],_=Xa(b.iss);if(y){const C=Gp(y),T=Yp(y);p.push(...C),A.push(...T)}for(const C of A)f.push(`${C}:${_}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Qi.create_authenticated_session_topic);let w;if((p==null?void 0:p.length)>0){w={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:pt(Wr),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:gg([...new Set(p)],[...new Set(f)]),transportType:a},n.addTrace(Qi.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(v){throw n.setError(ro.subscribe_authenticated_session_topic_failure),v}n.addTrace(Qi.subscribe_authenticated_session_topic_success),await this.client.session.set(g,w),n.addTrace(Qi.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Qi.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:i,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(v){throw n.setError(ro.authenticated_session_approve_publish_failure),v}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:w}}),O(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=La(o),l={type:fi,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:r,encodeOpts:l,rpcOpts:bt.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"))}),O(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:r}=t;return jy(i,r)}),O(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)}),O(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)}}),O(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(Hg).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=Ks.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),O(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(Yi.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")}),O(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=Ks.idle,this.client.events.emit("session_request_expire",{id:t}))}),O(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)])}),O(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}))}),O(this,"setProposal",async(t,i)=>{this.client.core.expirer.set(t,pt(bt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),O(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})}),O(this,"setPendingSessionRequest",async t=>{const{id:i,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||pt(bt.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})}),O(this,"sendRequest",async t=>{const{topic:i,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:h,tvf:d}=t,p=u.formatJsonRpcRequest(r,n,c);let f;const g=!!h;try{const b=g?to:Di;f=await this.client.core.crypto.encode(i,p,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),b}let w;if(iU.includes(r)){const b=Qs(JSON.stringify(p)),y=Qs(f);w=await this.client.core.verify.register({id:y,decryptedId:b})}const v=bt[r].req;if(v.attestation=w,o&&(v.ttl=o),a&&(v.id=a),this.client.core.history.set(i,p),g){const b=_a(h,i,f);await N.dist.global.Linking.openURL(b,this.client.name)}else{const b=bt[r].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=Ht(ze({},d),{correlationId:p.id}),l?(b.internal=Ht(ze({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,b)):this.client.core.relayer.publish(i,f,b).catch(y=>this.client.logger.error(y))}return p.id}),O(this,"sendResult",async t=>{const{id:i,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,l=u.formatJsonRpcResult(i,n);let h;const d=c&&typeof(N.dist.global==null?void 0:N.dist.global.Linking)<"u";try{const g=d?to:Di;h=await this.client.core.crypto.encode(r,l,Ht(ze({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let p,f;try{p=await this.client.core.history.get(r,i);const g=p.request;try{this.shouldSetTVF(g.method,g.params)&&(f=this.getTVFParams(i,g.params,n))}catch(w){this.client.logger.warn("sendResult() -> getTVFParams() failed",w)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${i}) failed`),g}if(d){const g=_a(c,r,h);await N.dist.global.Linking.openURL(g,this.client.name)}else{const g=p.request.method,w=bt[g].res;w.tvf=Ht(ze({},f),{correlationId:i}),o?(w.internal=Ht(ze({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,h,w)):this.client.core.relayer.publish(r,h,w).catch(v=>this.client.logger.error(v))}await this.client.core.history.resolve(l)}),O(this,"sendError",async t=>{const{id:i,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,l=u.formatJsonRpcError(i,n);let h;const d=c&&typeof(N.dist.global==null?void 0:N.dist.global.Linking)<"u";try{const f=d?to:Di;h=await this.client.core.crypto.encode(r,l,Ht(ze({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),f}let p;try{p=await this.client.core.history.get(r,i)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${r}, ${i}) failed`),f}if(d){const f=_a(c,r,h);await N.dist.global.Linking.openURL(f,this.client.name)}else{const f=p.request.method,g=a||bt[f].res;this.client.core.relayer.publish(r,h,g)}await this.client.core.history.resolve(l)}),O(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(r=>{let n=!1;Ti(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=>{Ti(r.expiryTimestamp)&&i.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...i.map(r=>this.deleteProposal(r))])}),O(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),O(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),O(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Ks.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=Ks.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Ks.idle}),O(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}`)}}),O(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}`)}}),O(this,"onRelayEventUnknownPayload",t=>{const{topic:i}=t,{message:r}=L("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),O(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)}),O(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(li.proposal_listener_not_found)),this.isValidConnect(ze({},r.params));const h=a.expiryTimestamp||pt(bt.wc_sessionPropose.req.ttl),d=ze({id:c,pairingTopic:i,expiryTimestamp:h},a);await this.setProposal(c,d);const p=await this.getVerifyContext({attestationId:n,hash:Qs(JSON.stringify(r)),encryptedId:o,metadata:d.proposer.metadata});l==null||l.addTrace(Ys.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:p})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:bt.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),O(this,"onSessionProposeResponse",async(t,i,r)=>{const{id:n}=i;if(u.isJsonRpcResult(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 d=await this.client.core.relayer.subscribe(h,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:t})}else if(u.isJsonRpcError(i)){await this.client.proposal.delete(n,Re("USER_DISCONNECTED"));const o=$e("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})}}),O(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,scopedProperties:d,sessionConfig:p}=i.params,f=[...this.pendingSessions.values()].find(v=>v.sessionTopic===t);if(!f)return this.client.logger.error(`Pending session not found for topic ${t}`);const g=this.client.proposal.get(f.proposalId),w=Ht(ze(ze(ze({topic:t,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},h&&{sessionProperties:h}),d&&{scopedProperties:d}),p&&{sessionConfig:p}),{transportType:Je.relay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:w.peer.metadata}),this.client.events.emit("session_connect",{session:w}),this.events.emit($e("session_connect",f.proposalId),{session:w}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(w),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)}}),O(this,"onSessionSettleResponse",async(t,i)=>{const{id:r}=i;u.isJsonRpcResult(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit($e("session_approve",r),{})):u.isJsonRpcError(i)&&(await this.client.session.delete(t,Re("USER_DISCONNECTED")),this.events.emit($e("session_approve",r),{error:i.error}))}),O(this,"onSessionUpdateRequest",async(t,i)=>{const{params:r,id:n}=i;try{const o=`${t}_session_update`,a=so.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(ze({topic:t},r));try{so.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 so.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)}}),O(this,"isRequestOutOfSync",(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3)),O(this,"onSessionUpdateResponse",(t,i)=>{const{id:r}=i,n=$e("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(i)?this.events.emit($e("session_update",r),{}):u.isJsonRpcError(i)&&this.events.emit($e("session_update",r),{error:i.error})}),O(this,"onSessionExtendRequest",async(t,i)=>{const{id:r}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,pt(Wr)),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)}}),O(this,"onSessionExtendResponse",(t,i)=>{const{id:r}=i,n=$e("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(i)?this.events.emit($e("session_extend",r),{}):u.isJsonRpcError(i)&&this.events.emit($e("session_extend",r),{error:i.error})}),O(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)}}),O(this,"onSessionPingResponse",(t,i)=>{const{id:r}=i,n=$e("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);u.isJsonRpcResult(i)?this.events.emit($e("session_ping",r),{}):u.isJsonRpcError(i)&&this.events.emit($e("session_ping",r),{error:i.error})},500)}),O(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(Et.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)}}),O(this,"onSessionRequest",async t=>{var i,r,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:h}=t,{id:d,params:p}=a;try{await this.isValidRequest(ze({topic:o},p));const f=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:Qs(JSON.stringify(u.formatJsonRpcRequest("wc_sessionRequest",p,d))),encryptedId:l,metadata:f.peer.metadata,transportType:h}),w={id:d,topic:o,params:p,verifyContext:g};await this.setPendingSessionRequest(w),h===Je.link_mode&&(i=f.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((r=f.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),O(this,"onSessionRequestResponse",(t,i)=>{const{id:r}=i,n=$e("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(i)?this.events.emit($e("session_request",r),{result:i.result}):u.isJsonRpcError(i)&&this.events.emit($e("session_request",r),{error:i.error})}),O(this,"onSessionEventRequest",async(t,i)=>{const{id:r,params:n}=i;try{const o=`${t}_session_event_${n.event.name}`,a=so.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(ze({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),so.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),O(this,"onSessionAuthenticateResponse",(t,i)=>{const{id:r}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),u.isJsonRpcResult(i)?this.events.emit($e("session_request",r),{result:i.result}):u.isJsonRpcError(i)&&this.events.emit($e("session_request",r),{error:i.error})}),O(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:d}=n.params,p=await this.getVerifyContext({attestationId:o,hash:Qs(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:r,id:n.id,authPayload:h,verifyContext:p,expiryTimestamp:d};await this.setAuthRequest(n.id,{request:f,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:p})}catch(l){this.client.logger.error(l);const h=n.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(n.params.requester.metadata,c),f={type:fi,receiverPublicKey:h,senderPublicKey:d};await this.sendError({id:n.id,topic:r,error:l,encodeOpts:f,rpcOpts:bt.wc_sessionAuthenticate.autoReject,appLink:p})}}),O(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),O(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ks.idle,this.processSessionRequestQueue()},u.cjs.toMiliseconds(this.requestQueueDelay))}),O(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=$e("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit($e("session_request",n.request.id),{error:i})})}),O(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Ks.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=Ks.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}}),O(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),O(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:u.formatJsonRpcRequest("wc_sessionPropose",Ht(ze({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id)})}),O(this,"isValidConnect",async t=>{if(!Xt(t)){const{message:l}=L("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(xt(i)||await this.isValidPairingTopic(i),!ej(c)){const{message:l}=L("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!xt(r)&&Do(r)!==0&&this.validateNamespaces(r,"requiredNamespaces"),!xt(n)&&Do(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),xt(o)||this.validateSessionProps(o,"sessionProperties"),!xt(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(h=>l.includes(h)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),O(this,"validateNamespaces",(t,i)=>{const r=X3(t,"connect()",i);if(r)throw new Error(r.message)}),O(this,"isValidApprove",async t=>{if(!Xt(t))throw new Error(L("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:r,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),l=ul(r,"approve()");if(l)throw new Error(l.message);const h=yg(c.requiredNamespaces,r,"approve()");if(h)throw new Error(h.message);if(!ht(n,!0)){const{message:d}=L("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(d)}if(xt(o)||this.validateSessionProps(o,"sessionProperties"),!xt(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(r));if(!Object.keys(a).every(p=>d.has(p)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),O(this,"isValidReject",async t=>{if(!Xt(t)){const{message:n}=L("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:r}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!sj(r)){const{message:n}=L("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),O(this,"isValidSessionSettleRequest",t=>{if(!Xt(t)){const{message:l}=L("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(l)}const{relay:i,controller:r,namespaces:n,expiry:o}=t;if(!Xy(i)){const{message:l}=L("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=K3(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=ul(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Ti(o)){const{message:l}=L("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),O(this,"isValidUpdate",async t=>{if(!Xt(t)){const{message:c}=L("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=ul(r,"update()");if(o)throw new Error(o.message);const a=yg(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),O(this,"isValidExtend",async t=>{if(!Xt(t)){const{message:r}=L("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),O(this,"isValidRequest",async t=>{if(!Xt(t)){const{message:c}=L("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(!wg(a,n)){const{message:c}=L("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!ij(r)){const{message:c}=L("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!oj(a,n,r.method)){const{message:c}=L("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!hj(o,ml)){const{message:c}=L("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${ml.min} and ${ml.max}`);throw new Error(c)}}),O(this,"isValidRespond",async t=>{var i;if(!Xt(t)){const{message:o}=L("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(!rj(n)){const{message:o}=L("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),O(this,"isValidPing",async t=>{if(!Xt(t)){const{message:r}=L("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),O(this,"isValidEmit",async t=>{if(!Xt(t)){const{message:a}=L("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(!wg(o,n)){const{message:a}=L("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!nj(r)){const{message:a}=L("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!aj(o,n,r.name)){const{message:a}=L("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),O(this,"isValidDisconnect",async t=>{if(!Xt(t)){const{message:r}=L("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),O(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=>bn(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=bn(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),O(this,"getVerifyContext",async t=>{const{attestationId:i,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||bo,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}),O(this,"validateSessionProps",(t,i)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=L("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),O(this,"getPendingAuthRequest",t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0}),O(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)}}}),O(this,"checkRecentlyDeleted",t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:r}=L("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(r)}}),O(this,"isLinkModeEnabled",(t,i)=>{var r,n,o,a,c,l,h,d,p;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&&((d=t==null?void 0:t.redirect)==null?void 0:d.universal)!==""&&((p=t==null?void 0:t.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(N.dist.global==null?void 0:N.dist.global.Linking)<"u"}),O(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}),O(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Up(t,"topic")||"",r=decodeURIComponent(Up(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})}),O(this,"registerLinkModeListeners",async()=>{var t;if(Qh()||Fi()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=N.dist.global==null?void 0:N.dist.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)}}}),O(this,"shouldSetTVF",(t,i)=>{if(!i||t!=="wc_sessionRequest")return!1;const{request:r}=i;return Object.keys(Vg).includes(r.method)}),O(this,"getTVFParams",(t,i,r)=>{var n,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,r);return Ht(ze({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{}}),O(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}),O(this,"extractTxHashesFromResult",(t,i)=>{try{const r=Vg[t];if(typeof i=="string")return[i];const n=i[r.key];if(fr(n))return t==="solana_signAllTransactions"?n.map(o=>ak(o)):n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,r]of Object.entries(t))for(const n of r)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Et.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Fa)?this.client.auth.authKeys.get(Fa):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===Je.link_mode?to:Di});u.isJsonRpcRequest(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:Qs(i)})):u.isJsonRpcResponse(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,i)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(vs.expired,async e=>{const{topic:t,id:i}=Sy(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,L("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,L("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(sr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(sr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ht(e,!1)){const{message:t}=L("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}=L("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Ti(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=L("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ht(e,!1)){const{message:t}=L("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}=L("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Ti(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=L("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=L("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}=L("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=L("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!tj(e)){const{message:t}=L("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=L("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Ti(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=L("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class fU extends vr{constructor(e,t){super(e,t,X5,nu),this.core=e,this.logger=t}}let wU=class extends vr{constructor(e,t){super(e,t,eU,nu),this.core=e,this.logger=t}};class yU extends vr{constructor(e,t){super(e,t,sU,nu,i=>i.id),this.core=e,this.logger=t}}class mU extends vr{constructor(e,t){super(e,t,oU,Nc,()=>Fa),this.core=e,this.logger=t}}class bU extends vr{constructor(e,t){super(e,t,aU,Nc),this.core=e,this.logger=t}}class vU extends vr{constructor(e,t){super(e,t,cU,Nc,i=>i.id),this.core=e,this.logger=t}}var IU=Object.defineProperty,EU=(s,e,t)=>e in s?IU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,bl=(s,e,t)=>EU(s,typeof e!="symbol"?e+"":e,t);class AU{constructor(e,t){this.core=e,this.logger=t,bl(this,"authKeys"),bl(this,"pairingTopics"),bl(this,"requests"),this.authKeys=new mU(this.core,this.logger),this.pairingTopics=new bU(this.core,this.logger),this.requests=new vU(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var NU=Object.defineProperty,_U=(s,e,t)=>e in s?NU(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ye=(s,e,t)=>_U(s,typeof e!="symbol"?e+"":e,t);let CU=class bm extends bx{constructor(e){super(e),ye(this,"protocol",wm),ye(this,"version",ym),ye(this,"name",yl.name),ye(this,"metadata"),ye(this,"core"),ye(this,"logger"),ye(this,"events",new u.eventsExports.EventEmitter),ye(this,"engine"),ye(this,"session"),ye(this,"proposal"),ye(this,"pendingRequest"),ye(this,"auth"),ye(this,"signConfig"),ye(this,"on",(i,r)=>this.events.on(i,r)),ye(this,"once",(i,r)=>this.events.once(i,r)),ye(this,"off",(i,r)=>this.events.off(i,r)),ye(this,"removeListener",(i,r)=>this.events.removeListener(i,r)),ye(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),ye(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"update",async i=>{try{return await this.engine.update(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"request",async i=>{try{return await this.engine.request(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"find",i=>{try{return this.engine.find(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),ye(this,"authenticate",async(i,r)=>{try{return await this.engine.authenticate(i,r)}catch(n){throw this.logger.error(n.message),n}}),ye(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(r){throw this.logger.error(r.message),r}}),ye(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),ye(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)||yl.name,this.metadata=(e==null?void 0:e.metadata)||Ny(),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:u.Ot(u.k({level:(e==null?void 0:e.logger)||yl.logger}));this.core=(e==null?void 0:e.core)||new Z5(e),this.logger=u.E(t,this.name),this.session=new wU(this.core,this.logger),this.proposal=new fU(this.core,this.logger),this.pendingRequest=new yU(this.core,this.logger),this.engine=new gU(this),this.auth=new AU(this.core,this.logger)}static async init(e){const t=new bm(e);return await t.initialize(),t}get context(){return u.y(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},u.cjs.toMiliseconds(u.cjs.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Gg="error",SU="wss://relay.walletconnect.org",TU="wc",PU="universal_provider",Sa=`${TU}@2:${PU}:`,vm="https://rpc.walletconnect.org/v1/",ln="generic",$U=`${vm}bundler`,_s={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function MU(){}function ou(s){return s==null||typeof s!="object"&&typeof s!="function"}function au(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)}function OU(s){if(ou(s))return s;if(Array.isArray(s)||au(s)||s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer)return s.slice(0);const e=Object.getPrototypeOf(s),t=e.constructor;if(s instanceof Date||s instanceof Map||s instanceof Set)return new t(s);if(s instanceof RegExp){const i=new t(s);return i.lastIndex=s.lastIndex,i}if(s instanceof DataView)return new t(s.buffer.slice(0));if(s instanceof Error){const i=new t(s.message);return i.stack=s.stack,i.name=s.name,i.cause=s.cause,i}if(typeof File<"u"&&s instanceof File)return new t([s],s.name,{type:s.type,lastModified:s.lastModified});if(typeof s=="object"){const i=Object.create(e);return Object.assign(i,s)}return s}function Yg(s){return typeof s=="object"&&s!==null}function Im(s){return Object.getOwnPropertySymbols(s).filter(e=>Object.prototype.propertyIsEnumerable.call(s,e))}function Em(s){return s==null?s===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(s)}const xU="[object RegExp]",Am="[object String]",Nm="[object Number]",_m="[object Boolean]",Cm="[object Arguments]",DU="[object Symbol]",kU="[object Date]",jU="[object Map]",RU="[object Set]",UU="[object Array]",LU="[object ArrayBuffer]",zU="[object Object]",FU="[object DataView]",qU="[object Uint8Array]",BU="[object Uint8ClampedArray]",HU="[object Uint16Array]",WU="[object Uint32Array]",VU="[object Int8Array]",KU="[object Int16Array]",GU="[object Int32Array]",YU="[object Float32Array]",QU="[object Float64Array]";function JU(s,e){return gn(s,void 0,s,new Map,e)}function gn(s,e,t,i=new Map,r=void 0){const n=r==null?void 0:r(s,e,t,i);if(n!=null)return n;if(ou(s))return s;if(i.has(s))return i.get(s);if(Array.isArray(s)){const o=new Array(s.length);i.set(s,o);for(let a=0;a<s.length;a++)o[a]=gn(s[a],a,t,i,r);return Object.hasOwn(s,"index")&&(o.index=s.index),Object.hasOwn(s,"input")&&(o.input=s.input),o}if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp){const o=new RegExp(s.source,s.flags);return o.lastIndex=s.lastIndex,o}if(s instanceof Map){const o=new Map;i.set(s,o);for(const[a,c]of s)o.set(a,gn(c,a,t,i,r));return o}if(s instanceof Set){const o=new Set;i.set(s,o);for(const a of s)o.add(gn(a,void 0,t,i,r));return o}if(typeof N.dist.Buffer<"u"&&N.dist.Buffer.isBuffer(s))return s.subarray();if(au(s)){const o=new(Object.getPrototypeOf(s)).constructor(s.length);i.set(s,o);for(let a=0;a<s.length;a++)o[a]=gn(s[a],a,t,i,r);return o}if(s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer)return s.slice(0);if(s instanceof DataView){const o=new DataView(s.buffer.slice(0),s.byteOffset,s.byteLength);return i.set(s,o),ir(o,s,t,i,r),o}if(typeof File<"u"&&s instanceof File){const o=new File([s],s.name,{type:s.type});return i.set(s,o),ir(o,s,t,i,r),o}if(s instanceof Blob){const o=new Blob([s],{type:s.type});return i.set(s,o),ir(o,s,t,i,r),o}if(s instanceof Error){const o=new s.constructor;return i.set(s,o),o.message=s.message,o.name=s.name,o.stack=s.stack,o.cause=s.cause,ir(o,s,t,i,r),o}if(typeof s=="object"&&ZU(s)){const o=Object.create(Object.getPrototypeOf(s));return i.set(s,o),ir(o,s,t,i,r),o}return s}function ir(s,e,t=s,i,r){const n=[...Object.keys(e),...Im(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(s,a);(c==null||c.writable)&&(s[a]=gn(e[a],a,t,i,r))}}function ZU(s){switch(Em(s)){case Cm:case UU:case LU:case FU:case _m:case kU:case YU:case QU:case VU:case KU:case GU:case jU:case Nm:case zU:case xU:case RU:case Am:case DU:case qU:case BU:case HU:case WU:return!0;default:return!1}}function XU(s,e){return JU(s,(t,i,r,n)=>{if(typeof s=="object")switch(Object.prototype.toString.call(s)){case Nm:case Am:case _m:{const o=new s.constructor(s==null?void 0:s.valueOf());return ir(o,s),o}case Cm:{const o={};return ir(o,s),o.length=s.length,o[Symbol.iterator]=s[Symbol.iterator],o}default:return}})}function Qg(s){return XU(s)}function Jg(s){return s!==null&&typeof s=="object"&&Em(s)==="[object Arguments]"}function eL(s){return au(s)}function tL(s){var t;if(typeof s!="object"||s==null)return!1;if(Object.getPrototypeOf(s)===null)return!0;if(Object.prototype.toString.call(s)!=="[object Object]"){const i=s[Symbol.toStringTag];return i==null||!((t=Object.getOwnPropertyDescriptor(s,Symbol.toStringTag))!=null&&t.writable)?!1:s.toString()===`[object ${i}]`}let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}function sL(s,...e){const t=e.slice(0,-1),i=e[e.length-1];let r=s;for(let n=0;n<t.length;n++){const o=t[n];r=Eh(r,o,i,new Map)}return r}function Eh(s,e,t,i){if(ou(s)&&(s=Object(s)),e==null||typeof e!="object")return s;if(i.has(e))return OU(i.get(e));if(i.set(e,s),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const r=[...Object.keys(e),...Im(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=s[o];if(Jg(a)&&(a={...a}),Jg(c)&&(c={...c}),typeof N.dist.Buffer<"u"&&N.dist.Buffer.isBuffer(a)&&(a=Qg(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const h=[],d=Reflect.ownKeys(c);for(let p=0;p<d.length;p++){const f=d[p];h[f]=c[f]}c=h}else c=[];const l=t(c,a,o,s,e,i);l!=null?s[o]=l:Array.isArray(a)||Yg(c)&&Yg(a)?s[o]=Eh(c,a,t,i):c==null&&tL(a)?s[o]=Eh({},a,t,i):c==null&&eL(a)?s[o]=Qg(a):(c===void 0||a!==void 0)&&(s[o]=a)}return s}function iL(s,...e){return sL(s,...e,MU)}var rL=Object.defineProperty,nL=Object.defineProperties,oL=Object.getOwnPropertyDescriptors,Zg=Object.getOwnPropertySymbols,aL=Object.prototype.hasOwnProperty,cL=Object.prototype.propertyIsEnumerable,Xg=(s,e,t)=>e in s?rL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ta=(s,e)=>{for(var t in e||(e={}))aL.call(e,t)&&Xg(s,t,e[t]);if(Zg)for(var t of Zg(e))cL.call(e,t)&&Xg(s,t,e[t]);return s},lL=(s,e)=>nL(s,oL(e));function ds(s,e,t){var i;const r=bn(s);return((i=e.rpcMap)==null?void 0:i[r.reference])||`${vm}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Ir(s){return s.includes(":")?s.split(":")[1]:s}function Sm(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function hL(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 vl(s={},e={}){const t=ef(s),i=ef(e);return iL(t,i)}function ef(s){var e,t,i,r;const n={};if(!Do(s))return n;for(const[o,a]of Object.entries(s)){const c=iu(o)?[o]:a.chains,l=a.methods||[],h=a.events||[],d=a.rpcMap||{},p=uo(o);n[p]=lL(Ta(Ta({},n[p]),a),{chains:Ra(c,(e=n[p])==null?void 0:e.chains),methods:Ra(l,(t=n[p])==null?void 0:t.methods),events:Ra(h,(i=n[p])==null?void 0:i.events),rpcMap:Ta(Ta({},d),(r=n[p])==null?void 0:r.rpcMap)})}return n}function uL(s){return s.includes(":")?s.split(":")[2]:s}function tf(s){const e={};for(const[t,i]of Object.entries(s)){const r=i.methods||[],n=i.events||[],o=i.accounts||[],a=iu(t)?[t]:i.chains?i.chains:Sm(i.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Il(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 Tm={},Se=s=>Tm[s],El=(s,e)=>{Tm[s]=e};var dL=Object.defineProperty,pL=(s,e,t)=>e in s?dL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Vr=(s,e,t)=>pL(s,typeof e!="symbol"?e+"":e,t);class gL{constructor(e){Vr(this,"name","polkadot"),Vr(this,"client"),Vr(this,"httpProviders"),Vr(this,"events"),Vr(this,"namespace"),Vr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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(_s.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=Ir(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||ds(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Se("disableProviderPing")))}}var fL=Object.defineProperty,wL=Object.defineProperties,yL=Object.getOwnPropertyDescriptors,sf=Object.getOwnPropertySymbols,mL=Object.prototype.hasOwnProperty,bL=Object.prototype.propertyIsEnumerable,Ah=(s,e,t)=>e in s?fL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,rf=(s,e)=>{for(var t in e||(e={}))mL.call(e,t)&&Ah(s,t,e[t]);if(sf)for(var t of sf(e))bL.call(e,t)&&Ah(s,t,e[t]);return s},nf=(s,e)=>wL(s,yL(e)),Kr=(s,e,t)=>Ah(s,typeof e!="symbol"?e+"":e,t);class vL{constructor(e){Kr(this,"name","eip155"),Kr(this,"client"),Kr(this,"chainId"),Kr(this,"namespace"),Kr(this,"httpProviders"),Kr(this,"events"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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(_s.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||ds(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Se("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(Ir(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:nf(rf({},o.sessionProperties||{}),{capabilities:nf(rf({},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(u.formatJsonRpcRequest("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`${$U}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var IL=Object.defineProperty,EL=(s,e,t)=>e in s?IL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Gr=(s,e,t)=>EL(s,typeof e!="symbol"?e+"":e,t);class AL{constructor(e){Gr(this,"name","solana"),Gr(this,"client"),Gr(this,"httpProviders"),Gr(this,"events"),Gr(this,"namespace"),Gr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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(_s.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=Ir(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||ds(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Se("disableProviderPing")))}}var NL=Object.defineProperty,_L=(s,e,t)=>e in s?NL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Yr=(s,e,t)=>_L(s,typeof e!="symbol"?e+"":e,t);class CL{constructor(e){Yr(this,"name","cosmos"),Yr(this,"client"),Yr(this,"httpProviders"),Yr(this,"events"),Yr(this,"namespace"),Yr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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(_s.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=Ir(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||ds(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Se("disableProviderPing")))}}var SL=Object.defineProperty,TL=(s,e,t)=>e in s?SL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Qr=(s,e,t)=>TL(s,typeof e!="symbol"?e+"":e,t);class PL{constructor(e){Qr(this,"name","algorand"),Qr(this,"client"),Qr(this,"httpProviders"),Qr(this,"events"),Qr(this,"namespace"),Qr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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||ds(`${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(_s.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||ds(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new u.o(new u.f$1(i,Se("disableProviderPing")))}}var $L=Object.defineProperty,ML=(s,e,t)=>e in s?$L(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Jr=(s,e,t)=>ML(s,typeof e!="symbol"?e+"":e,t);class OL{constructor(e){Jr(this,"name","cip34"),Jr(this,"client"),Jr(this,"httpProviders"),Jr(this,"events"),Jr(this,"namespace"),Jr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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(_s.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=Ir(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 u.o(new u.f$1(i,Se("disableProviderPing")))}}var xL=Object.defineProperty,DL=(s,e,t)=>e in s?xL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Zr=(s,e,t)=>DL(s,typeof e!="symbol"?e+"":e,t);class kL{constructor(e){Zr(this,"name","elrond"),Zr(this,"client"),Zr(this,"httpProviders"),Zr(this,"events"),Zr(this,"namespace"),Zr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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(_s.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=Ir(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||ds(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Se("disableProviderPing")))}}var jL=Object.defineProperty,RL=(s,e,t)=>e in s?jL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Xr=(s,e,t)=>RL(s,typeof e!="symbol"?e+"":e,t);class UL{constructor(e){Xr(this,"name","multiversx"),Xr(this,"client"),Xr(this,"httpProviders"),Xr(this,"events"),Xr(this,"namespace"),Xr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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(_s.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=Ir(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||ds(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Se("disableProviderPing")))}}var LL=Object.defineProperty,zL=(s,e,t)=>e in s?LL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,en=(s,e,t)=>zL(s,typeof e!="symbol"?e+"":e,t);class FL{constructor(e){en(this,"name","near"),en(this,"client"),en(this,"httpProviders"),en(this,"events"),en(this,"namespace"),en(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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||ds(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(_s.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||ds(e,this.namespace);return typeof i>"u"?void 0:new u.o(new u.f$1(i,Se("disableProviderPing")))}}var qL=Object.defineProperty,BL=(s,e,t)=>e in s?qL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,tn=(s,e,t)=>BL(s,typeof e!="symbol"?e+"":e,t);class HL{constructor(e){tn(this,"name","tezos"),tn(this,"client"),tn(this,"httpProviders"),tn(this,"events"),tn(this,"namespace"),tn(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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||ds(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(_s.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||ds(e,this.namespace);return typeof i>"u"?void 0:new u.o(new u.f$1(i))}}var WL=Object.defineProperty,VL=(s,e,t)=>e in s?WL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,sn=(s,e,t)=>VL(s,typeof e!="symbol"?e+"":e,t);class KL{constructor(e){sn(this,"name",ln),sn(this,"client"),sn(this,"httpProviders"),sn(this,"events"),sn(this,"namespace"),sn(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("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(_s.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=bn(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||ds(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(i,Se("disableProviderPing")))}}var GL=Object.defineProperty,YL=Object.defineProperties,QL=Object.getOwnPropertyDescriptors,of=Object.getOwnPropertySymbols,JL=Object.prototype.hasOwnProperty,ZL=Object.prototype.propertyIsEnumerable,Nh=(s,e,t)=>e in s?GL(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Pa=(s,e)=>{for(var t in e||(e={}))JL.call(e,t)&&Nh(s,t,e[t]);if(of)for(var t of of(e))ZL.call(e,t)&&Nh(s,t,e[t]);return s},Al=(s,e)=>YL(s,QL(e)),ms=(s,e,t)=>Nh(s,typeof e!="symbol"?e+"":e,t);class cu{constructor(e){ms(this,"client"),ms(this,"namespaces"),ms(this,"optionalNamespaces"),ms(this,"sessionProperties"),ms(this,"scopedProperties"),ms(this,"events",new u.Nt),ms(this,"rpcProviders",{}),ms(this,"session"),ms(this,"providerOpts"),ms(this,"logger"),ms(this,"uri"),ms(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:u.Ot(u.k({level:(e==null?void 0:e.logger)||Gg})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new cu(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:Pa({},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,u.formatJsonRpcResult(n,o))).catch(o=>t(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason: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=tf(this.session.namespaces);this.namespaces=vl(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await i();this.session=r;const n=tf(r.namespaces);return this.namespaces=vl(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,r]=this.validateChain(e),n=this.getProvider(i);n.name===ln?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(fr(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(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,t;if(this.client=this.providerOpts.client||await CU.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Gg,relayUrl:this.providerOpts.relayUrl||SU,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>uo(t)))];El("client",this.client),El("events",this.events),El("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=hL(t,this.session),r=Sm(i),n=vl(this.namespaces,this.optionalNamespaces),o=Al(Pa({},n[t]),{accounts:i,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new vL({namespace:o});break;case"algorand":this.rpcProviders[t]=new PL({namespace:o});break;case"solana":this.rpcProviders[t]=new AL({namespace:o});break;case"cosmos":this.rpcProviders[t]=new CL({namespace:o});break;case"polkadot":this.rpcProviders[t]=new gL({namespace:o});break;case"cip34":this.rpcProviders[t]=new OL({namespace:o});break;case"elrond":this.rpcProviders[t]=new kL({namespace:o});break;case"multiversx":this.rpcProviders[t]=new UL({namespace:o});break;case"near":this.rpcProviders[t]=new FL({namespace:o});break;case"tezos":this.rpcProviders[t]=new HL({namespace:o});break;default:this.rpcProviders[ln]?this.rpcProviders[ln].updateNamespace(o):this.rpcProviders[ln]=new KL({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:i}=e;i===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:i,topic:r}=e;if(r!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&fr(o)&&this.events.emit("accountsChanged",o.map(uL))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=uo(o),l=Il(o)!==Il(a)?`${c}:${Il(a)}`:o;this.onChainChanged(l)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i,r;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=t,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Al(Pa({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Al(Pa({},Re("USER_DISCONNECTED")),{data:e.topic})))}),this.on(_s.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[ln]}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,scopedProperties:n}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=r,this.scopedProperties=n}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=>uo(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=uo(Object.keys(this.namespaces)[0]),n=this.rpcProviders[r].getDefaultChain();return[r,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[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.events.emit("chainChanged",r),await this.persist("namespaces",this.namespaces))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var i;const r=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${Sa}/${e}${r}`,t)}async getFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${Sa}/${e}${i}`)}async deleteFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${Sa}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const i of t)i.startsWith(Sa)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}}const _i={EIP155:"eip155",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED"},sc={NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200"},ConnectorImageIds:{[se.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[se.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[se.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[se.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[se.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[se.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[se.CONNECTOR_ID.INJECTED]:"Browser Wallet",[se.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[se.CONNECTOR_ID.COINBASE]:"Coinbase",[se.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[se.CONNECTOR_ID.LEDGER]:"Ledger",[se.CONNECTOR_ID.SAFE]:"Safe"}},Pm={getCaipTokens(s){if(!s)return;const e={};return Object.entries(s).forEach(([t,i])=>{e[`${_i.EIP155}:${t}`]=i}),e},isLowerCaseMatch(s,e){return(s==null?void 0:s.toLowerCase())===(e==null?void 0:e.toLowerCase())}},$a={UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"INVALID_APP_CONFIGURATION"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{shortMessage:"Network Not Found",longMessage:"Network not found - please make sure it is included in 'networks' array in createAppKit function"},INVALID_APP_CONFIGURATION:{shortMessage:"Invalid App Configuration",longMessage:()=>`Origin ${XL()?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},SOCIALS_TIMEOUT:{shortMessage:"Invalid App Configuration",longMessage:()=>"There was an issue loading the embedded wallet. Please verify that your domain is allowed at cloud.reown.com"},JWT_TOKEN_NOT_VALID:{shortMessage:"Session Expired",longMessage:"Invalid session found on UniversalProvider - please check your time settings and connect again"},INVALID_PROJECT_ID:{shortMessage:"Invalid App Configuration",longMessage:"Invalid Project ID - update configuration"},PROJECT_ID_NOT_CONFIGURED:{shortMessage:"Project ID Not Configured",longMessage:"Project ID Not Configured - update configuration on cloud.reown.com"}}};function XL(){return typeof window<"u"}const ez={createLogger(s,e="error"){const t=u.k({level:e}),{logger:i}=u.A({opts:t});return i.error=(...r)=>{for(const n of r)if(n instanceof Error){s(n,...r);return}s(void 0,...r)},i}},tz="rpc.walletconnect.org";function sz(s,e){const t=new URL("https://rpc.walletconnect.org/v1/");return t.searchParams.set("chainId",s),t.searchParams.set("projectId",e),t.toString()}const Nl=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],hn={extendRpcUrlWithProjectId(s,e){let t=!1;try{t=new URL(s).host===tz}catch{t=!1}if(t){const i=new URL(s);return i.searchParams.has("projectId")||i.searchParams.set("projectId",e),i.toString()}return s},isCaipNetwork(s){return"chainNamespace"in s&&"caipNetworkId"in s},getChainNamespace(s){return this.isCaipNetwork(s)?s.chainNamespace:se.CHAIN.EVM},getCaipNetworkId(s){return this.isCaipNetwork(s)?s.caipNetworkId:`${se.CHAIN.EVM}:${s.id}`},getDefaultRpcUrl(s,e,t){var r,n,o;const i=(o=(n=(r=s.rpcUrls)==null?void 0:r.default)==null?void 0:n.http)==null?void 0:o[0];return Nl.includes(e)?sz(e,t):i||""},extendCaipNetwork(s,{customNetworkImageUrls:e,projectId:t,customRpcUrls:i}){var p,f,g,w,v;const r=this.getChainNamespace(s),n=this.getCaipNetworkId(s),o=(p=s.rpcUrls.default.http)==null?void 0:p[0],a=this.getDefaultRpcUrl(s,n,t),c=((w=(g=(f=s==null?void 0:s.rpcUrls)==null?void 0:f.chainDefault)==null?void 0:g.http)==null?void 0:w[0])||o,l=((v=i==null?void 0:i[n])==null?void 0:v.map(b=>b.url))||[],h=[...l,a],d=[...l];return c&&!d.includes(c)&&d.push(c),{...s,chainNamespace:r,caipNetworkId:n,assets:{imageId:sc.NetworkImageIds[s.id],imageUrl:e==null?void 0:e[s.id]},rpcUrls:{...s.rpcUrls,default:{http:h},chainDefault:{http:d}}}},extendCaipNetworks(s,{customNetworkImageUrls:e,projectId:t,customRpcUrls:i}){return s.map(r=>hn.extendCaipNetwork(r,{customNetworkImageUrls:e,customRpcUrls:i,projectId:t}))},getViemTransport(s,e,t){const i=[];if(t==null||t.forEach(r=>{i.push(wn.http(r.url,r.config))}),Nl.includes(s.caipNetworkId)){const r=this.getDefaultRpcUrl(s,s.caipNetworkId,e);i.push(wn.http(r,{fetchOptions:{headers:{"Content-Type":"text/plain"}}}))}return k.fallback(i)},extendWagmiTransports(s,e,t){if(Nl.includes(s.caipNetworkId)){const i=this.getDefaultRpcUrl(s,s.caipNetworkId,e);return k.fallback([t,wn.http(i)])}return t},getUnsupportedNetwork(s){return{id:s.split(":")[1],caipNetworkId:s,name:se.UNSUPPORTED_NETWORK_NAME,chainNamespace:s.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(s){var c;const e=X.getActiveCaipNetworkId(),t=I.getAllRequestedCaipNetworks(),i=Array.from(((c=I.state.chains)==null?void 0:c.keys())||[]),r=e==null?void 0:e.split(":")[0],n=r?i.includes(r):!1,o=t==null?void 0:t.find(l=>l.caipNetworkId===e);return n&&!o&&e?this.getUnsupportedNetwork(e):o||s||(t==null?void 0:t[0])}},ic={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0},Jt=k.proxy({providers:{...ic},providerIds:{...ic}}),et={state:Jt,subscribeKey(s,e){return k.subscribeKey(Jt,s,e)},subscribe(s){return k.subscribe(Jt,()=>{s(Jt)})},subscribeProviders(s){return k.subscribe(Jt.providers,()=>s(Jt.providers))},setProvider(s,e){e&&(Jt.providers[s]=k.ref(e))},getProvider(s){return Jt.providers[s]},setProviderId(s,e){e&&(Jt.providerIds[s]=e)},getProviderId(s){if(s)return Jt.providerIds[s]},reset(){Jt.providers={...ic},Jt.providerIds={...ic}},resetChain(s){Jt.providers[s]=void 0,Jt.providerIds[s]=void 0}},$m={SECURE_SITE_ORIGIN:(typeof N.dist.process<"u"&&typeof N.dist.process.env<"u"?N.dist.process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},rc={filterOutDuplicatesByRDNS(s){const e=R.state.enableEIP6963?ce.state.connectors:[],t=X.getRecentWallets(),i=e.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}).filter(Boolean),r=t.map(a=>a.rdns).filter(Boolean),n=i.concat(r);if(n.includes("io.metamask.mobile")&&le.isMobile()){const a=n.indexOf("io.metamask.mobile");n[a]="io.metamask"}return s.filter(a=>!n.includes(String(a==null?void 0:a.rdns)))},filterOutDuplicatesByIds(s){const e=ce.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),t=X.getRecentWallets(),i=e.map(a=>a.explorerId),r=t.map(a=>a.id),n=i.concat(r);return s.filter(a=>!n.includes(a==null?void 0:a.id))},filterOutDuplicateWallets(s){const e=this.filterOutDuplicatesByRDNS(s);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(s){const{connectors:e}=ce.state,t=e.filter(n=>n.type==="ANNOUNCED").reduce((n,o)=>{var a;return(a=o.info)!=null&&a.rdns&&(n[o.info.rdns]=!0),n},{});return s.map(n=>({...n,installed:!!n.rdns&&!!t[n.rdns??""]})).sort((n,o)=>Number(o.installed)-Number(n.installed))},getConnectOrderMethod(s,e){var c;const t=(s==null?void 0:s.connectMethodsOrder)||((c=R.state.features)==null?void 0:c.connectMethodsOrder),i=e||ce.state.connectors;if(t)return t;const{injected:r,announced:n}=Io.getConnectorsByType(i,he.state.recommended,he.state.featured),o=r.filter(Io.showConnector),a=n.filter(Io.showConnector);return o.length||a.length?["wallet","email","social"]:$m.DEFAULT_CONNECT_METHOD_ORDER}},Io={getConnectorsByType(s,e,t){const{customWallets:i}=R.state,r=X.getRecentWallets(),n=rc.filterOutDuplicateWallets(e),o=rc.filterOutDuplicateWallets(t),a=s.filter(d=>d.type==="MULTI_CHAIN"),c=s.filter(d=>d.type==="ANNOUNCED"),l=s.filter(d=>d.type==="INJECTED"),h=s.filter(d=>d.type==="EXTERNAL");return{custom:i,recent:r,external:h,multiChain:a,announced:c,injected:l,recommended:n,featured:o}},showConnector(s){var r;const e=(r=s.info)==null?void 0:r.rdns,t=!!e&&he.state.excludedWallets.some(n=>n.rdns===e),i=!!s.name&&he.state.excludedWallets.some(n=>Pm.isLowerCaseMatch(n.name,s.name));return!(s.type==="INJECTED"&&(!le.isMobile()&&s.name==="Browser Wallet"||!e&&!Fe.checkInstalled()||t||i)||s.type==="ANNOUNCED"&&(t||i))},getIsConnectedWithWC(){return Array.from(I.state.chains.values()).some(t=>ce.getConnectorId(t.namespace)===se.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:s,featured:e,custom:t,recent:i,announced:r,injected:n,multiChain:o,external:a,overriddenConnectors:c=(l=>(l=R.state.features)==null?void 0:l.connectorTypeOrder)()??[]}){const h=Io.getIsConnectedWithWC(),f=[{type:"walletConnect",isEnabled:R.state.enableWalletConnect&&!h},{type:"recent",isEnabled:i.length>0},{type:"injected",isEnabled:[...n,...r,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:t&&t.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:s.length>0}].filter(b=>b.isEnabled),g=new Set(f.map(b=>b.type)),w=c.filter(b=>g.has(b)).map(b=>({type:b,isEnabled:!0})),v=f.filter(({type:b})=>!w.some(({type:A})=>A===b));return Array.from(new Set([...w,...v].map(({type:b})=>b)))}};let Eo,Ri,Ui;function iz(s,e){Eo=document.createElement("style"),Ri=document.createElement("style"),Ui=document.createElement("style"),Eo.textContent=vn(s).core.cssText,Ri.textContent=vn(s).dark.cssText,Ui.textContent=vn(s).light.cssText,document.head.appendChild(Eo),document.head.appendChild(Ri),document.head.appendChild(Ui),Mm(e)}function Mm(s){Ri&&Ui&&(s==="light"?(Ri.removeAttribute("media"),Ui.media="enabled"):(Ui.removeAttribute("media"),Ri.media="enabled"))}function rz(s){Eo&&Ri&&Ui&&(Eo.textContent=vn(s).core.cssText,Ri.textContent=vn(s).dark.cssText,Ui.textContent=vn(s).light.cssText)}function vn(s){return{core:k.i`
|
|
22
|
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
|
23
|
+
@keyframes w3m-shake {
|
|
24
|
+
0% {
|
|
25
|
+
transform: scale(1) rotate(0deg);
|
|
26
|
+
}
|
|
27
|
+
20% {
|
|
28
|
+
transform: scale(1) rotate(-1deg);
|
|
29
|
+
}
|
|
30
|
+
40% {
|
|
31
|
+
transform: scale(1) rotate(1.5deg);
|
|
32
|
+
}
|
|
33
|
+
60% {
|
|
34
|
+
transform: scale(1) rotate(-1.5deg);
|
|
35
|
+
}
|
|
36
|
+
80% {
|
|
37
|
+
transform: scale(1) rotate(1deg);
|
|
38
|
+
}
|
|
39
|
+
100% {
|
|
40
|
+
transform: scale(1) rotate(0deg);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
@keyframes w3m-iframe-fade-out {
|
|
44
|
+
0% {
|
|
45
|
+
opacity: 1;
|
|
46
|
+
}
|
|
47
|
+
100% {
|
|
48
|
+
opacity: 0;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
@keyframes w3m-iframe-zoom-in {
|
|
52
|
+
0% {
|
|
53
|
+
transform: translateY(50px);
|
|
54
|
+
opacity: 0;
|
|
55
|
+
}
|
|
56
|
+
100% {
|
|
57
|
+
transform: translateY(0px);
|
|
58
|
+
opacity: 1;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
@keyframes w3m-iframe-zoom-in-mobile {
|
|
62
|
+
0% {
|
|
63
|
+
transform: scale(0.95);
|
|
64
|
+
opacity: 0;
|
|
65
|
+
}
|
|
66
|
+
100% {
|
|
67
|
+
transform: scale(1);
|
|
68
|
+
opacity: 1;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
:root {
|
|
72
|
+
--w3m-modal-width: 360px;
|
|
73
|
+
--w3m-color-mix-strength: ${k.r(s!=null&&s["--w3m-color-mix-strength"]?`${s["--w3m-color-mix-strength"]}%`:"0%")};
|
|
74
|
+
--w3m-font-family: ${k.r((s==null?void 0:s["--w3m-font-family"])||"Inter, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;")};
|
|
75
|
+
--w3m-font-size-master: ${k.r((s==null?void 0:s["--w3m-font-size-master"])||"10px")};
|
|
76
|
+
--w3m-border-radius-master: ${k.r((s==null?void 0:s["--w3m-border-radius-master"])||"4px")};
|
|
77
|
+
--w3m-z-index: ${k.r((s==null?void 0:s["--w3m-z-index"])||999)};
|
|
78
|
+
|
|
79
|
+
--wui-font-family: var(--w3m-font-family);
|
|
80
|
+
|
|
81
|
+
--wui-font-size-mini: calc(var(--w3m-font-size-master) * 0.8);
|
|
82
|
+
--wui-font-size-micro: var(--w3m-font-size-master);
|
|
83
|
+
--wui-font-size-tiny: calc(var(--w3m-font-size-master) * 1.2);
|
|
84
|
+
--wui-font-size-small: calc(var(--w3m-font-size-master) * 1.4);
|
|
85
|
+
--wui-font-size-paragraph: calc(var(--w3m-font-size-master) * 1.6);
|
|
86
|
+
--wui-font-size-medium: calc(var(--w3m-font-size-master) * 1.8);
|
|
87
|
+
--wui-font-size-large: calc(var(--w3m-font-size-master) * 2);
|
|
88
|
+
--wui-font-size-title-6: calc(var(--w3m-font-size-master) * 2.2);
|
|
89
|
+
--wui-font-size-medium-title: calc(var(--w3m-font-size-master) * 2.4);
|
|
90
|
+
--wui-font-size-2xl: calc(var(--w3m-font-size-master) * 4);
|
|
91
|
+
|
|
92
|
+
--wui-border-radius-5xs: var(--w3m-border-radius-master);
|
|
93
|
+
--wui-border-radius-4xs: calc(var(--w3m-border-radius-master) * 1.5);
|
|
94
|
+
--wui-border-radius-3xs: calc(var(--w3m-border-radius-master) * 2);
|
|
95
|
+
--wui-border-radius-xxs: calc(var(--w3m-border-radius-master) * 3);
|
|
96
|
+
--wui-border-radius-xs: calc(var(--w3m-border-radius-master) * 4);
|
|
97
|
+
--wui-border-radius-s: calc(var(--w3m-border-radius-master) * 5);
|
|
98
|
+
--wui-border-radius-m: calc(var(--w3m-border-radius-master) * 7);
|
|
99
|
+
--wui-border-radius-l: calc(var(--w3m-border-radius-master) * 9);
|
|
100
|
+
--wui-border-radius-3xl: calc(var(--w3m-border-radius-master) * 20);
|
|
101
|
+
|
|
102
|
+
--wui-font-weight-light: 400;
|
|
103
|
+
--wui-font-weight-regular: 500;
|
|
104
|
+
--wui-font-weight-medium: 600;
|
|
105
|
+
--wui-font-weight-bold: 700;
|
|
106
|
+
|
|
107
|
+
--wui-letter-spacing-2xl: -1.6px;
|
|
108
|
+
--wui-letter-spacing-medium-title: -0.96px;
|
|
109
|
+
--wui-letter-spacing-title-6: -0.88px;
|
|
110
|
+
--wui-letter-spacing-large: -0.8px;
|
|
111
|
+
--wui-letter-spacing-medium: -0.72px;
|
|
112
|
+
--wui-letter-spacing-paragraph: -0.64px;
|
|
113
|
+
--wui-letter-spacing-small: -0.56px;
|
|
114
|
+
--wui-letter-spacing-tiny: -0.48px;
|
|
115
|
+
--wui-letter-spacing-micro: -0.2px;
|
|
116
|
+
--wui-letter-spacing-mini: -0.16px;
|
|
117
|
+
|
|
118
|
+
--wui-spacing-0: 0px;
|
|
119
|
+
--wui-spacing-4xs: 2px;
|
|
120
|
+
--wui-spacing-3xs: 4px;
|
|
121
|
+
--wui-spacing-xxs: 6px;
|
|
122
|
+
--wui-spacing-2xs: 7px;
|
|
123
|
+
--wui-spacing-xs: 8px;
|
|
124
|
+
--wui-spacing-1xs: 10px;
|
|
125
|
+
--wui-spacing-s: 12px;
|
|
126
|
+
--wui-spacing-m: 14px;
|
|
127
|
+
--wui-spacing-l: 16px;
|
|
128
|
+
--wui-spacing-2l: 18px;
|
|
129
|
+
--wui-spacing-xl: 20px;
|
|
130
|
+
--wui-spacing-xxl: 24px;
|
|
131
|
+
--wui-spacing-2xl: 32px;
|
|
132
|
+
--wui-spacing-3xl: 40px;
|
|
133
|
+
--wui-spacing-4xl: 90px;
|
|
134
|
+
--wui-spacing-5xl: 95px;
|
|
135
|
+
|
|
136
|
+
--wui-icon-box-size-xxs: 14px;
|
|
137
|
+
--wui-icon-box-size-xs: 20px;
|
|
138
|
+
--wui-icon-box-size-sm: 24px;
|
|
139
|
+
--wui-icon-box-size-md: 32px;
|
|
140
|
+
--wui-icon-box-size-mdl: 36px;
|
|
141
|
+
--wui-icon-box-size-lg: 40px;
|
|
142
|
+
--wui-icon-box-size-2lg: 48px;
|
|
143
|
+
--wui-icon-box-size-xl: 64px;
|
|
144
|
+
|
|
145
|
+
--wui-icon-size-inherit: inherit;
|
|
146
|
+
--wui-icon-size-xxs: 10px;
|
|
147
|
+
--wui-icon-size-xs: 12px;
|
|
148
|
+
--wui-icon-size-sm: 14px;
|
|
149
|
+
--wui-icon-size-md: 16px;
|
|
150
|
+
--wui-icon-size-mdl: 18px;
|
|
151
|
+
--wui-icon-size-lg: 20px;
|
|
152
|
+
--wui-icon-size-xl: 24px;
|
|
153
|
+
--wui-icon-size-xxl: 28px;
|
|
154
|
+
|
|
155
|
+
--wui-wallet-image-size-inherit: inherit;
|
|
156
|
+
--wui-wallet-image-size-sm: 40px;
|
|
157
|
+
--wui-wallet-image-size-md: 56px;
|
|
158
|
+
--wui-wallet-image-size-lg: 80px;
|
|
159
|
+
|
|
160
|
+
--wui-visual-size-size-inherit: inherit;
|
|
161
|
+
--wui-visual-size-sm: 40px;
|
|
162
|
+
--wui-visual-size-md: 55px;
|
|
163
|
+
--wui-visual-size-lg: 80px;
|
|
164
|
+
|
|
165
|
+
--wui-box-size-md: 100px;
|
|
166
|
+
--wui-box-size-lg: 120px;
|
|
167
|
+
|
|
168
|
+
--wui-ease-out-power-2: cubic-bezier(0, 0, 0.22, 1);
|
|
169
|
+
--wui-ease-out-power-1: cubic-bezier(0, 0, 0.55, 1);
|
|
170
|
+
|
|
171
|
+
--wui-ease-in-power-3: cubic-bezier(0.66, 0, 1, 1);
|
|
172
|
+
--wui-ease-in-power-2: cubic-bezier(0.45, 0, 1, 1);
|
|
173
|
+
--wui-ease-in-power-1: cubic-bezier(0.3, 0, 1, 1);
|
|
174
|
+
|
|
175
|
+
--wui-ease-inout-power-1: cubic-bezier(0.45, 0, 0.55, 1);
|
|
176
|
+
|
|
177
|
+
--wui-duration-lg: 200ms;
|
|
178
|
+
--wui-duration-md: 125ms;
|
|
179
|
+
--wui-duration-sm: 75ms;
|
|
180
|
+
|
|
181
|
+
--wui-path-network-sm: path(
|
|
182
|
+
'M15.4 2.1a5.21 5.21 0 0 1 5.2 0l11.61 6.7a5.21 5.21 0 0 1 2.61 4.52v13.4c0 1.87-1 3.59-2.6 4.52l-11.61 6.7c-1.62.93-3.6.93-5.22 0l-11.6-6.7a5.21 5.21 0 0 1-2.61-4.51v-13.4c0-1.87 1-3.6 2.6-4.52L15.4 2.1Z'
|
|
183
|
+
);
|
|
184
|
+
|
|
185
|
+
--wui-path-network-md: path(
|
|
186
|
+
'M43.4605 10.7248L28.0485 1.61089C25.5438 0.129705 22.4562 0.129705 19.9515 1.61088L4.53951 10.7248C2.03626 12.2051 0.5 14.9365 0.5 17.886V36.1139C0.5 39.0635 2.03626 41.7949 4.53951 43.2752L19.9515 52.3891C22.4562 53.8703 25.5438 53.8703 28.0485 52.3891L43.4605 43.2752C45.9637 41.7949 47.5 39.0635 47.5 36.114V17.8861C47.5 14.9365 45.9637 12.2051 43.4605 10.7248Z'
|
|
187
|
+
);
|
|
188
|
+
|
|
189
|
+
--wui-path-network-lg: path(
|
|
190
|
+
'M78.3244 18.926L50.1808 2.45078C45.7376 -0.150261 40.2624 -0.150262 35.8192 2.45078L7.6756 18.926C3.23322 21.5266 0.5 26.3301 0.5 31.5248V64.4752C0.5 69.6699 3.23322 74.4734 7.6756 77.074L35.8192 93.5492C40.2624 96.1503 45.7376 96.1503 50.1808 93.5492L78.3244 77.074C82.7668 74.4734 85.5 69.6699 85.5 64.4752V31.5248C85.5 26.3301 82.7668 21.5266 78.3244 18.926Z'
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
--wui-width-network-sm: 36px;
|
|
194
|
+
--wui-width-network-md: 48px;
|
|
195
|
+
--wui-width-network-lg: 86px;
|
|
196
|
+
|
|
197
|
+
--wui-height-network-sm: 40px;
|
|
198
|
+
--wui-height-network-md: 54px;
|
|
199
|
+
--wui-height-network-lg: 96px;
|
|
200
|
+
|
|
201
|
+
--wui-icon-size-network-xs: 12px;
|
|
202
|
+
--wui-icon-size-network-sm: 16px;
|
|
203
|
+
--wui-icon-size-network-md: 24px;
|
|
204
|
+
--wui-icon-size-network-lg: 42px;
|
|
205
|
+
|
|
206
|
+
--wui-color-inherit: inherit;
|
|
207
|
+
|
|
208
|
+
--wui-color-inverse-100: #fff;
|
|
209
|
+
--wui-color-inverse-000: #000;
|
|
210
|
+
|
|
211
|
+
--wui-cover: rgba(20, 20, 20, 0.8);
|
|
212
|
+
|
|
213
|
+
--wui-color-modal-bg: var(--wui-color-modal-bg-base);
|
|
214
|
+
|
|
215
|
+
--wui-color-accent-100: var(--wui-color-accent-base-100);
|
|
216
|
+
--wui-color-accent-090: var(--wui-color-accent-base-090);
|
|
217
|
+
--wui-color-accent-080: var(--wui-color-accent-base-080);
|
|
218
|
+
|
|
219
|
+
--wui-color-success-100: var(--wui-color-success-base-100);
|
|
220
|
+
--wui-color-success-125: var(--wui-color-success-base-125);
|
|
221
|
+
|
|
222
|
+
--wui-color-warning-100: var(--wui-color-warning-base-100);
|
|
223
|
+
|
|
224
|
+
--wui-color-error-100: var(--wui-color-error-base-100);
|
|
225
|
+
--wui-color-error-125: var(--wui-color-error-base-125);
|
|
226
|
+
|
|
227
|
+
--wui-color-blue-100: var(--wui-color-blue-base-100);
|
|
228
|
+
--wui-color-blue-90: var(--wui-color-blue-base-90);
|
|
229
|
+
|
|
230
|
+
--wui-icon-box-bg-error-100: var(--wui-icon-box-bg-error-base-100);
|
|
231
|
+
--wui-icon-box-bg-blue-100: var(--wui-icon-box-bg-blue-base-100);
|
|
232
|
+
--wui-icon-box-bg-success-100: var(--wui-icon-box-bg-success-base-100);
|
|
233
|
+
--wui-icon-box-bg-inverse-100: var(--wui-icon-box-bg-inverse-base-100);
|
|
234
|
+
|
|
235
|
+
--wui-all-wallets-bg-100: var(--wui-all-wallets-bg-100);
|
|
236
|
+
|
|
237
|
+
--wui-avatar-border: var(--wui-avatar-border-base);
|
|
238
|
+
|
|
239
|
+
--wui-thumbnail-border: var(--wui-thumbnail-border-base);
|
|
240
|
+
|
|
241
|
+
--wui-wallet-button-bg: var(--wui-wallet-button-bg-base);
|
|
242
|
+
|
|
243
|
+
--wui-box-shadow-blue: var(--wui-color-accent-glass-020);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
@supports (background: color-mix(in srgb, white 50%, black)) {
|
|
247
|
+
:root {
|
|
248
|
+
--wui-color-modal-bg: color-mix(
|
|
249
|
+
in srgb,
|
|
250
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
251
|
+
var(--wui-color-modal-bg-base)
|
|
252
|
+
);
|
|
253
|
+
|
|
254
|
+
--wui-box-shadow-blue: color-mix(in srgb, var(--wui-color-accent-100) 20%, transparent);
|
|
255
|
+
|
|
256
|
+
--wui-color-accent-100: color-mix(
|
|
257
|
+
in srgb,
|
|
258
|
+
var(--wui-color-accent-base-100) 100%,
|
|
259
|
+
transparent
|
|
260
|
+
);
|
|
261
|
+
--wui-color-accent-090: color-mix(
|
|
262
|
+
in srgb,
|
|
263
|
+
var(--wui-color-accent-base-100) 90%,
|
|
264
|
+
transparent
|
|
265
|
+
);
|
|
266
|
+
--wui-color-accent-080: color-mix(
|
|
267
|
+
in srgb,
|
|
268
|
+
var(--wui-color-accent-base-100) 80%,
|
|
269
|
+
transparent
|
|
270
|
+
);
|
|
271
|
+
--wui-color-accent-glass-090: color-mix(
|
|
272
|
+
in srgb,
|
|
273
|
+
var(--wui-color-accent-base-100) 90%,
|
|
274
|
+
transparent
|
|
275
|
+
);
|
|
276
|
+
--wui-color-accent-glass-080: color-mix(
|
|
277
|
+
in srgb,
|
|
278
|
+
var(--wui-color-accent-base-100) 80%,
|
|
279
|
+
transparent
|
|
280
|
+
);
|
|
281
|
+
--wui-color-accent-glass-020: color-mix(
|
|
282
|
+
in srgb,
|
|
283
|
+
var(--wui-color-accent-base-100) 20%,
|
|
284
|
+
transparent
|
|
285
|
+
);
|
|
286
|
+
--wui-color-accent-glass-015: color-mix(
|
|
287
|
+
in srgb,
|
|
288
|
+
var(--wui-color-accent-base-100) 15%,
|
|
289
|
+
transparent
|
|
290
|
+
);
|
|
291
|
+
--wui-color-accent-glass-010: color-mix(
|
|
292
|
+
in srgb,
|
|
293
|
+
var(--wui-color-accent-base-100) 10%,
|
|
294
|
+
transparent
|
|
295
|
+
);
|
|
296
|
+
--wui-color-accent-glass-005: color-mix(
|
|
297
|
+
in srgb,
|
|
298
|
+
var(--wui-color-accent-base-100) 5%,
|
|
299
|
+
transparent
|
|
300
|
+
);
|
|
301
|
+
--wui-color-accent-002: color-mix(
|
|
302
|
+
in srgb,
|
|
303
|
+
var(--wui-color-accent-base-100) 2%,
|
|
304
|
+
transparent
|
|
305
|
+
);
|
|
306
|
+
|
|
307
|
+
--wui-color-fg-100: color-mix(
|
|
308
|
+
in srgb,
|
|
309
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
310
|
+
var(--wui-color-fg-100)
|
|
311
|
+
);
|
|
312
|
+
--wui-color-fg-125: color-mix(
|
|
313
|
+
in srgb,
|
|
314
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
315
|
+
var(--wui-color-fg-125)
|
|
316
|
+
);
|
|
317
|
+
--wui-color-fg-150: color-mix(
|
|
318
|
+
in srgb,
|
|
319
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
320
|
+
var(--wui-color-fg-150)
|
|
321
|
+
);
|
|
322
|
+
--wui-color-fg-175: color-mix(
|
|
323
|
+
in srgb,
|
|
324
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
325
|
+
var(--wui-color-fg-175)
|
|
326
|
+
);
|
|
327
|
+
--wui-color-fg-200: color-mix(
|
|
328
|
+
in srgb,
|
|
329
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
330
|
+
var(--wui-color-fg-200)
|
|
331
|
+
);
|
|
332
|
+
--wui-color-fg-225: color-mix(
|
|
333
|
+
in srgb,
|
|
334
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
335
|
+
var(--wui-color-fg-225)
|
|
336
|
+
);
|
|
337
|
+
--wui-color-fg-250: color-mix(
|
|
338
|
+
in srgb,
|
|
339
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
340
|
+
var(--wui-color-fg-250)
|
|
341
|
+
);
|
|
342
|
+
--wui-color-fg-275: color-mix(
|
|
343
|
+
in srgb,
|
|
344
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
345
|
+
var(--wui-color-fg-275)
|
|
346
|
+
);
|
|
347
|
+
--wui-color-fg-300: color-mix(
|
|
348
|
+
in srgb,
|
|
349
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
350
|
+
var(--wui-color-fg-300)
|
|
351
|
+
);
|
|
352
|
+
--wui-color-fg-325: color-mix(
|
|
353
|
+
in srgb,
|
|
354
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
355
|
+
var(--wui-color-fg-325)
|
|
356
|
+
);
|
|
357
|
+
--wui-color-fg-350: color-mix(
|
|
358
|
+
in srgb,
|
|
359
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
360
|
+
var(--wui-color-fg-350)
|
|
361
|
+
);
|
|
362
|
+
|
|
363
|
+
--wui-color-bg-100: color-mix(
|
|
364
|
+
in srgb,
|
|
365
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
366
|
+
var(--wui-color-bg-100)
|
|
367
|
+
);
|
|
368
|
+
--wui-color-bg-125: color-mix(
|
|
369
|
+
in srgb,
|
|
370
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
371
|
+
var(--wui-color-bg-125)
|
|
372
|
+
);
|
|
373
|
+
--wui-color-bg-150: color-mix(
|
|
374
|
+
in srgb,
|
|
375
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
376
|
+
var(--wui-color-bg-150)
|
|
377
|
+
);
|
|
378
|
+
--wui-color-bg-175: color-mix(
|
|
379
|
+
in srgb,
|
|
380
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
381
|
+
var(--wui-color-bg-175)
|
|
382
|
+
);
|
|
383
|
+
--wui-color-bg-200: color-mix(
|
|
384
|
+
in srgb,
|
|
385
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
386
|
+
var(--wui-color-bg-200)
|
|
387
|
+
);
|
|
388
|
+
--wui-color-bg-225: color-mix(
|
|
389
|
+
in srgb,
|
|
390
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
391
|
+
var(--wui-color-bg-225)
|
|
392
|
+
);
|
|
393
|
+
--wui-color-bg-250: color-mix(
|
|
394
|
+
in srgb,
|
|
395
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
396
|
+
var(--wui-color-bg-250)
|
|
397
|
+
);
|
|
398
|
+
--wui-color-bg-275: color-mix(
|
|
399
|
+
in srgb,
|
|
400
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
401
|
+
var(--wui-color-bg-275)
|
|
402
|
+
);
|
|
403
|
+
--wui-color-bg-300: color-mix(
|
|
404
|
+
in srgb,
|
|
405
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
406
|
+
var(--wui-color-bg-300)
|
|
407
|
+
);
|
|
408
|
+
--wui-color-bg-325: color-mix(
|
|
409
|
+
in srgb,
|
|
410
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
411
|
+
var(--wui-color-bg-325)
|
|
412
|
+
);
|
|
413
|
+
--wui-color-bg-350: color-mix(
|
|
414
|
+
in srgb,
|
|
415
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
416
|
+
var(--wui-color-bg-350)
|
|
417
|
+
);
|
|
418
|
+
|
|
419
|
+
--wui-color-success-100: color-mix(
|
|
420
|
+
in srgb,
|
|
421
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
422
|
+
var(--wui-color-success-base-100)
|
|
423
|
+
);
|
|
424
|
+
--wui-color-success-125: color-mix(
|
|
425
|
+
in srgb,
|
|
426
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
427
|
+
var(--wui-color-success-base-125)
|
|
428
|
+
);
|
|
429
|
+
|
|
430
|
+
--wui-color-warning-100: color-mix(
|
|
431
|
+
in srgb,
|
|
432
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
433
|
+
var(--wui-color-warning-base-100)
|
|
434
|
+
);
|
|
435
|
+
|
|
436
|
+
--wui-color-error-100: color-mix(
|
|
437
|
+
in srgb,
|
|
438
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
439
|
+
var(--wui-color-error-base-100)
|
|
440
|
+
);
|
|
441
|
+
--wui-color-blue-100: color-mix(
|
|
442
|
+
in srgb,
|
|
443
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
444
|
+
var(--wui-color-blue-base-100)
|
|
445
|
+
);
|
|
446
|
+
--wui-color-blue-90: color-mix(
|
|
447
|
+
in srgb,
|
|
448
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
449
|
+
var(--wui-color-blue-base-90)
|
|
450
|
+
);
|
|
451
|
+
--wui-color-error-125: color-mix(
|
|
452
|
+
in srgb,
|
|
453
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
454
|
+
var(--wui-color-error-base-125)
|
|
455
|
+
);
|
|
456
|
+
|
|
457
|
+
--wui-icon-box-bg-error-100: color-mix(
|
|
458
|
+
in srgb,
|
|
459
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
460
|
+
var(--wui-icon-box-bg-error-base-100)
|
|
461
|
+
);
|
|
462
|
+
--wui-icon-box-bg-accent-100: color-mix(
|
|
463
|
+
in srgb,
|
|
464
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
465
|
+
var(--wui-icon-box-bg-blue-base-100)
|
|
466
|
+
);
|
|
467
|
+
--wui-icon-box-bg-success-100: color-mix(
|
|
468
|
+
in srgb,
|
|
469
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
470
|
+
var(--wui-icon-box-bg-success-base-100)
|
|
471
|
+
);
|
|
472
|
+
--wui-icon-box-bg-inverse-100: color-mix(
|
|
473
|
+
in srgb,
|
|
474
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
475
|
+
var(--wui-icon-box-bg-inverse-base-100)
|
|
476
|
+
);
|
|
477
|
+
|
|
478
|
+
--wui-all-wallets-bg-100: color-mix(
|
|
479
|
+
in srgb,
|
|
480
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
481
|
+
var(--wui-all-wallets-bg-100)
|
|
482
|
+
);
|
|
483
|
+
|
|
484
|
+
--wui-avatar-border: color-mix(
|
|
485
|
+
in srgb,
|
|
486
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
487
|
+
var(--wui-avatar-border-base)
|
|
488
|
+
);
|
|
489
|
+
|
|
490
|
+
--wui-thumbnail-border: color-mix(
|
|
491
|
+
in srgb,
|
|
492
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
493
|
+
var(--wui-thumbnail-border-base)
|
|
494
|
+
);
|
|
495
|
+
|
|
496
|
+
--wui-wallet-button-bg: color-mix(
|
|
497
|
+
in srgb,
|
|
498
|
+
var(--w3m-color-mix) var(--w3m-color-mix-strength),
|
|
499
|
+
var(--wui-wallet-button-bg-base)
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
`,light:k.i`
|
|
504
|
+
:root {
|
|
505
|
+
--w3m-color-mix: ${k.r((s==null?void 0:s["--w3m-color-mix"])||"#fff")};
|
|
506
|
+
--w3m-accent: ${k.r(Oi(s,"dark")["--w3m-accent"])};
|
|
507
|
+
--w3m-default: #fff;
|
|
508
|
+
|
|
509
|
+
--wui-color-modal-bg-base: ${k.r(Oi(s,"dark")["--w3m-background"])};
|
|
510
|
+
--wui-color-accent-base-100: var(--w3m-accent);
|
|
511
|
+
|
|
512
|
+
--wui-color-blueberry-100: hsla(230, 100%, 67%, 1);
|
|
513
|
+
--wui-color-blueberry-090: hsla(231, 76%, 61%, 1);
|
|
514
|
+
--wui-color-blueberry-080: hsla(230, 59%, 55%, 1);
|
|
515
|
+
--wui-color-blueberry-050: hsla(231, 100%, 70%, 0.1);
|
|
516
|
+
|
|
517
|
+
--wui-color-fg-100: #e4e7e7;
|
|
518
|
+
--wui-color-fg-125: #d0d5d5;
|
|
519
|
+
--wui-color-fg-150: #a8b1b1;
|
|
520
|
+
--wui-color-fg-175: #a8b0b0;
|
|
521
|
+
--wui-color-fg-200: #949e9e;
|
|
522
|
+
--wui-color-fg-225: #868f8f;
|
|
523
|
+
--wui-color-fg-250: #788080;
|
|
524
|
+
--wui-color-fg-275: #788181;
|
|
525
|
+
--wui-color-fg-300: #6e7777;
|
|
526
|
+
--wui-color-fg-325: #9a9a9a;
|
|
527
|
+
--wui-color-fg-350: #363636;
|
|
528
|
+
|
|
529
|
+
--wui-color-bg-100: #141414;
|
|
530
|
+
--wui-color-bg-125: #191a1a;
|
|
531
|
+
--wui-color-bg-150: #1e1f1f;
|
|
532
|
+
--wui-color-bg-175: #222525;
|
|
533
|
+
--wui-color-bg-200: #272a2a;
|
|
534
|
+
--wui-color-bg-225: #2c3030;
|
|
535
|
+
--wui-color-bg-250: #313535;
|
|
536
|
+
--wui-color-bg-275: #363b3b;
|
|
537
|
+
--wui-color-bg-300: #3b4040;
|
|
538
|
+
--wui-color-bg-325: #252525;
|
|
539
|
+
--wui-color-bg-350: #ffffff;
|
|
540
|
+
|
|
541
|
+
--wui-color-success-base-100: #26d962;
|
|
542
|
+
--wui-color-success-base-125: #30a46b;
|
|
543
|
+
|
|
544
|
+
--wui-color-warning-base-100: #f3a13f;
|
|
545
|
+
|
|
546
|
+
--wui-color-error-base-100: #f25a67;
|
|
547
|
+
--wui-color-error-base-125: #df4a34;
|
|
548
|
+
|
|
549
|
+
--wui-color-blue-base-100: rgba(102, 125, 255, 1);
|
|
550
|
+
--wui-color-blue-base-90: rgba(102, 125, 255, 0.9);
|
|
551
|
+
|
|
552
|
+
--wui-color-success-glass-001: rgba(38, 217, 98, 0.01);
|
|
553
|
+
--wui-color-success-glass-002: rgba(38, 217, 98, 0.02);
|
|
554
|
+
--wui-color-success-glass-005: rgba(38, 217, 98, 0.05);
|
|
555
|
+
--wui-color-success-glass-010: rgba(38, 217, 98, 0.1);
|
|
556
|
+
--wui-color-success-glass-015: rgba(38, 217, 98, 0.15);
|
|
557
|
+
--wui-color-success-glass-020: rgba(38, 217, 98, 0.2);
|
|
558
|
+
--wui-color-success-glass-025: rgba(38, 217, 98, 0.25);
|
|
559
|
+
--wui-color-success-glass-030: rgba(38, 217, 98, 0.3);
|
|
560
|
+
--wui-color-success-glass-060: rgba(38, 217, 98, 0.6);
|
|
561
|
+
--wui-color-success-glass-080: rgba(38, 217, 98, 0.8);
|
|
562
|
+
|
|
563
|
+
--wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2);
|
|
564
|
+
|
|
565
|
+
--wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2);
|
|
566
|
+
|
|
567
|
+
--wui-color-error-glass-001: rgba(242, 90, 103, 0.01);
|
|
568
|
+
--wui-color-error-glass-002: rgba(242, 90, 103, 0.02);
|
|
569
|
+
--wui-color-error-glass-005: rgba(242, 90, 103, 0.05);
|
|
570
|
+
--wui-color-error-glass-010: rgba(242, 90, 103, 0.1);
|
|
571
|
+
--wui-color-error-glass-015: rgba(242, 90, 103, 0.15);
|
|
572
|
+
--wui-color-error-glass-020: rgba(242, 90, 103, 0.2);
|
|
573
|
+
--wui-color-error-glass-025: rgba(242, 90, 103, 0.25);
|
|
574
|
+
--wui-color-error-glass-030: rgba(242, 90, 103, 0.3);
|
|
575
|
+
--wui-color-error-glass-060: rgba(242, 90, 103, 0.6);
|
|
576
|
+
--wui-color-error-glass-080: rgba(242, 90, 103, 0.8);
|
|
577
|
+
|
|
578
|
+
--wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2);
|
|
579
|
+
|
|
580
|
+
--wui-color-gray-glass-001: rgba(255, 255, 255, 0.01);
|
|
581
|
+
--wui-color-gray-glass-002: rgba(255, 255, 255, 0.02);
|
|
582
|
+
--wui-color-gray-glass-005: rgba(255, 255, 255, 0.05);
|
|
583
|
+
--wui-color-gray-glass-010: rgba(255, 255, 255, 0.1);
|
|
584
|
+
--wui-color-gray-glass-015: rgba(255, 255, 255, 0.15);
|
|
585
|
+
--wui-color-gray-glass-020: rgba(255, 255, 255, 0.2);
|
|
586
|
+
--wui-color-gray-glass-025: rgba(255, 255, 255, 0.25);
|
|
587
|
+
--wui-color-gray-glass-030: rgba(255, 255, 255, 0.3);
|
|
588
|
+
--wui-color-gray-glass-060: rgba(255, 255, 255, 0.6);
|
|
589
|
+
--wui-color-gray-glass-080: rgba(255, 255, 255, 0.8);
|
|
590
|
+
--wui-color-gray-glass-090: rgba(255, 255, 255, 0.9);
|
|
591
|
+
|
|
592
|
+
--wui-color-dark-glass-100: rgba(42, 42, 42, 1);
|
|
593
|
+
|
|
594
|
+
--wui-icon-box-bg-error-base-100: #3c2426;
|
|
595
|
+
--wui-icon-box-bg-blue-base-100: #20303f;
|
|
596
|
+
--wui-icon-box-bg-success-base-100: #1f3a28;
|
|
597
|
+
--wui-icon-box-bg-inverse-base-100: #243240;
|
|
598
|
+
|
|
599
|
+
--wui-all-wallets-bg-100: #222b35;
|
|
600
|
+
|
|
601
|
+
--wui-avatar-border-base: #252525;
|
|
602
|
+
|
|
603
|
+
--wui-thumbnail-border-base: #252525;
|
|
604
|
+
|
|
605
|
+
--wui-wallet-button-bg-base: var(--wui-color-bg-125);
|
|
606
|
+
|
|
607
|
+
--w3m-card-embedded-shadow-color: rgb(17 17 18 / 25%);
|
|
608
|
+
}
|
|
609
|
+
`,dark:k.i`
|
|
610
|
+
:root {
|
|
611
|
+
--w3m-color-mix: ${k.r((s==null?void 0:s["--w3m-color-mix"])||"#000")};
|
|
612
|
+
--w3m-accent: ${k.r(Oi(s,"light")["--w3m-accent"])};
|
|
613
|
+
--w3m-default: #000;
|
|
614
|
+
|
|
615
|
+
--wui-color-modal-bg-base: ${k.r(Oi(s,"light")["--w3m-background"])};
|
|
616
|
+
--wui-color-accent-base-100: var(--w3m-accent);
|
|
617
|
+
|
|
618
|
+
--wui-color-blueberry-100: hsla(231, 100%, 70%, 1);
|
|
619
|
+
--wui-color-blueberry-090: hsla(231, 97%, 72%, 1);
|
|
620
|
+
--wui-color-blueberry-080: hsla(231, 92%, 74%, 1);
|
|
621
|
+
|
|
622
|
+
--wui-color-fg-100: #141414;
|
|
623
|
+
--wui-color-fg-125: #2d3131;
|
|
624
|
+
--wui-color-fg-150: #474d4d;
|
|
625
|
+
--wui-color-fg-175: #636d6d;
|
|
626
|
+
--wui-color-fg-200: #798686;
|
|
627
|
+
--wui-color-fg-225: #828f8f;
|
|
628
|
+
--wui-color-fg-250: #8b9797;
|
|
629
|
+
--wui-color-fg-275: #95a0a0;
|
|
630
|
+
--wui-color-fg-300: #9ea9a9;
|
|
631
|
+
--wui-color-fg-325: #9a9a9a;
|
|
632
|
+
--wui-color-fg-350: #d0d0d0;
|
|
633
|
+
|
|
634
|
+
--wui-color-bg-100: #ffffff;
|
|
635
|
+
--wui-color-bg-125: #f5fafa;
|
|
636
|
+
--wui-color-bg-150: #f3f8f8;
|
|
637
|
+
--wui-color-bg-175: #eef4f4;
|
|
638
|
+
--wui-color-bg-200: #eaf1f1;
|
|
639
|
+
--wui-color-bg-225: #e5eded;
|
|
640
|
+
--wui-color-bg-250: #e1e9e9;
|
|
641
|
+
--wui-color-bg-275: #dce7e7;
|
|
642
|
+
--wui-color-bg-300: #d8e3e3;
|
|
643
|
+
--wui-color-bg-325: #f3f3f3;
|
|
644
|
+
--wui-color-bg-350: #202020;
|
|
645
|
+
|
|
646
|
+
--wui-color-success-base-100: #26b562;
|
|
647
|
+
--wui-color-success-base-125: #30a46b;
|
|
648
|
+
|
|
649
|
+
--wui-color-warning-base-100: #f3a13f;
|
|
650
|
+
|
|
651
|
+
--wui-color-error-base-100: #f05142;
|
|
652
|
+
--wui-color-error-base-125: #df4a34;
|
|
653
|
+
|
|
654
|
+
--wui-color-blue-base-100: rgba(102, 125, 255, 1);
|
|
655
|
+
--wui-color-blue-base-90: rgba(102, 125, 255, 0.9);
|
|
656
|
+
|
|
657
|
+
--wui-color-success-glass-001: rgba(38, 181, 98, 0.01);
|
|
658
|
+
--wui-color-success-glass-002: rgba(38, 181, 98, 0.02);
|
|
659
|
+
--wui-color-success-glass-005: rgba(38, 181, 98, 0.05);
|
|
660
|
+
--wui-color-success-glass-010: rgba(38, 181, 98, 0.1);
|
|
661
|
+
--wui-color-success-glass-015: rgba(38, 181, 98, 0.15);
|
|
662
|
+
--wui-color-success-glass-020: rgba(38, 181, 98, 0.2);
|
|
663
|
+
--wui-color-success-glass-025: rgba(38, 181, 98, 0.25);
|
|
664
|
+
--wui-color-success-glass-030: rgba(38, 181, 98, 0.3);
|
|
665
|
+
--wui-color-success-glass-060: rgba(38, 181, 98, 0.6);
|
|
666
|
+
--wui-color-success-glass-080: rgba(38, 181, 98, 0.8);
|
|
667
|
+
|
|
668
|
+
--wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2);
|
|
669
|
+
|
|
670
|
+
--wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2);
|
|
671
|
+
|
|
672
|
+
--wui-color-error-glass-001: rgba(240, 81, 66, 0.01);
|
|
673
|
+
--wui-color-error-glass-002: rgba(240, 81, 66, 0.02);
|
|
674
|
+
--wui-color-error-glass-005: rgba(240, 81, 66, 0.05);
|
|
675
|
+
--wui-color-error-glass-010: rgba(240, 81, 66, 0.1);
|
|
676
|
+
--wui-color-error-glass-015: rgba(240, 81, 66, 0.15);
|
|
677
|
+
--wui-color-error-glass-020: rgba(240, 81, 66, 0.2);
|
|
678
|
+
--wui-color-error-glass-025: rgba(240, 81, 66, 0.25);
|
|
679
|
+
--wui-color-error-glass-030: rgba(240, 81, 66, 0.3);
|
|
680
|
+
--wui-color-error-glass-060: rgba(240, 81, 66, 0.6);
|
|
681
|
+
--wui-color-error-glass-080: rgba(240, 81, 66, 0.8);
|
|
682
|
+
|
|
683
|
+
--wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2);
|
|
684
|
+
|
|
685
|
+
--wui-icon-box-bg-error-base-100: #f4dfdd;
|
|
686
|
+
--wui-icon-box-bg-blue-base-100: #d9ecfb;
|
|
687
|
+
--wui-icon-box-bg-success-base-100: #daf0e4;
|
|
688
|
+
--wui-icon-box-bg-inverse-base-100: #dcecfc;
|
|
689
|
+
|
|
690
|
+
--wui-all-wallets-bg-100: #e8f1fa;
|
|
691
|
+
|
|
692
|
+
--wui-avatar-border-base: #f3f4f4;
|
|
693
|
+
|
|
694
|
+
--wui-thumbnail-border-base: #eaefef;
|
|
695
|
+
|
|
696
|
+
--wui-wallet-button-bg-base: var(--wui-color-bg-125);
|
|
697
|
+
|
|
698
|
+
--wui-color-gray-glass-001: rgba(0, 0, 0, 0.01);
|
|
699
|
+
--wui-color-gray-glass-002: rgba(0, 0, 0, 0.02);
|
|
700
|
+
--wui-color-gray-glass-005: rgba(0, 0, 0, 0.05);
|
|
701
|
+
--wui-color-gray-glass-010: rgba(0, 0, 0, 0.1);
|
|
702
|
+
--wui-color-gray-glass-015: rgba(0, 0, 0, 0.15);
|
|
703
|
+
--wui-color-gray-glass-020: rgba(0, 0, 0, 0.2);
|
|
704
|
+
--wui-color-gray-glass-025: rgba(0, 0, 0, 0.25);
|
|
705
|
+
--wui-color-gray-glass-030: rgba(0, 0, 0, 0.3);
|
|
706
|
+
--wui-color-gray-glass-060: rgba(0, 0, 0, 0.6);
|
|
707
|
+
--wui-color-gray-glass-080: rgba(0, 0, 0, 0.8);
|
|
708
|
+
--wui-color-gray-glass-090: rgba(0, 0, 0, 0.9);
|
|
709
|
+
|
|
710
|
+
--wui-color-dark-glass-100: rgba(233, 233, 233, 1);
|
|
711
|
+
|
|
712
|
+
--w3m-card-embedded-shadow-color: rgb(224 225 233 / 25%);
|
|
713
|
+
}
|
|
714
|
+
`}}const nz=k.i`
|
|
715
|
+
*,
|
|
716
|
+
*::after,
|
|
717
|
+
*::before,
|
|
718
|
+
:host {
|
|
719
|
+
margin: 0;
|
|
720
|
+
padding: 0;
|
|
721
|
+
box-sizing: border-box;
|
|
722
|
+
font-style: normal;
|
|
723
|
+
text-rendering: optimizeSpeed;
|
|
724
|
+
-webkit-font-smoothing: antialiased;
|
|
725
|
+
-moz-osx-font-smoothing: grayscale;
|
|
726
|
+
-webkit-tap-highlight-color: transparent;
|
|
727
|
+
font-family: var(--wui-font-family);
|
|
728
|
+
backface-visibility: hidden;
|
|
729
|
+
}
|
|
730
|
+
`,oz=k.i`
|
|
731
|
+
button,
|
|
732
|
+
a {
|
|
733
|
+
cursor: pointer;
|
|
734
|
+
display: flex;
|
|
735
|
+
justify-content: center;
|
|
736
|
+
align-items: center;
|
|
737
|
+
position: relative;
|
|
738
|
+
transition:
|
|
739
|
+
color var(--wui-duration-lg) var(--wui-ease-out-power-1),
|
|
740
|
+
background-color var(--wui-duration-lg) var(--wui-ease-out-power-1),
|
|
741
|
+
border var(--wui-duration-lg) var(--wui-ease-out-power-1),
|
|
742
|
+
border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1),
|
|
743
|
+
box-shadow var(--wui-duration-lg) var(--wui-ease-out-power-1);
|
|
744
|
+
will-change: background-color, color, border, box-shadow, border-radius;
|
|
745
|
+
outline: none;
|
|
746
|
+
border: none;
|
|
747
|
+
column-gap: var(--wui-spacing-3xs);
|
|
748
|
+
background-color: transparent;
|
|
749
|
+
text-decoration: none;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
wui-flex {
|
|
753
|
+
transition: border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1);
|
|
754
|
+
will-change: border-radius;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
button:disabled > wui-wallet-image,
|
|
758
|
+
button:disabled > wui-all-wallets-image,
|
|
759
|
+
button:disabled > wui-network-image,
|
|
760
|
+
button:disabled > wui-image,
|
|
761
|
+
button:disabled > wui-transaction-visual,
|
|
762
|
+
button:disabled > wui-logo {
|
|
763
|
+
filter: grayscale(1);
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
@media (hover: hover) and (pointer: fine) {
|
|
767
|
+
button:hover:enabled {
|
|
768
|
+
background-color: var(--wui-color-gray-glass-005);
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
button:active:enabled {
|
|
772
|
+
background-color: var(--wui-color-gray-glass-010);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
button:disabled > wui-icon-box {
|
|
777
|
+
opacity: 0.5;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
input {
|
|
781
|
+
border: none;
|
|
782
|
+
outline: none;
|
|
783
|
+
appearance: none;
|
|
784
|
+
}
|
|
785
|
+
`,az=k.i`
|
|
786
|
+
.wui-color-inherit {
|
|
787
|
+
color: var(--wui-color-inherit);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
.wui-color-accent-100 {
|
|
791
|
+
color: var(--wui-color-accent-100);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
.wui-color-error-100 {
|
|
795
|
+
color: var(--wui-color-error-100);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
.wui-color-blue-100 {
|
|
799
|
+
color: var(--wui-color-blue-100);
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
.wui-color-blue-90 {
|
|
803
|
+
color: var(--wui-color-blue-90);
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
.wui-color-error-125 {
|
|
807
|
+
color: var(--wui-color-error-125);
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
.wui-color-success-100 {
|
|
811
|
+
color: var(--wui-color-success-100);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
.wui-color-success-125 {
|
|
815
|
+
color: var(--wui-color-success-125);
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
.wui-color-inverse-100 {
|
|
819
|
+
color: var(--wui-color-inverse-100);
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
.wui-color-inverse-000 {
|
|
823
|
+
color: var(--wui-color-inverse-000);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
.wui-color-fg-100 {
|
|
827
|
+
color: var(--wui-color-fg-100);
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
.wui-color-fg-200 {
|
|
831
|
+
color: var(--wui-color-fg-200);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
.wui-color-fg-300 {
|
|
835
|
+
color: var(--wui-color-fg-300);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
.wui-color-fg-325 {
|
|
839
|
+
color: var(--wui-color-fg-325);
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
.wui-color-fg-350 {
|
|
843
|
+
color: var(--wui-color-fg-350);
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
.wui-bg-color-inherit {
|
|
847
|
+
background-color: var(--wui-color-inherit);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
.wui-bg-color-blue-100 {
|
|
851
|
+
background-color: var(--wui-color-accent-100);
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
.wui-bg-color-error-100 {
|
|
855
|
+
background-color: var(--wui-color-error-100);
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
.wui-bg-color-error-125 {
|
|
859
|
+
background-color: var(--wui-color-error-125);
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
.wui-bg-color-success-100 {
|
|
863
|
+
background-color: var(--wui-color-success-100);
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
.wui-bg-color-success-125 {
|
|
867
|
+
background-color: var(--wui-color-success-100);
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
.wui-bg-color-inverse-100 {
|
|
871
|
+
background-color: var(--wui-color-inverse-100);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
.wui-bg-color-inverse-000 {
|
|
875
|
+
background-color: var(--wui-color-inverse-000);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
.wui-bg-color-fg-100 {
|
|
879
|
+
background-color: var(--wui-color-fg-100);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
.wui-bg-color-fg-200 {
|
|
883
|
+
background-color: var(--wui-color-fg-200);
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
.wui-bg-color-fg-300 {
|
|
887
|
+
background-color: var(--wui-color-fg-300);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
.wui-color-fg-325 {
|
|
891
|
+
background-color: var(--wui-color-fg-325);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
.wui-color-fg-350 {
|
|
895
|
+
background-color: var(--wui-color-fg-350);
|
|
896
|
+
}
|
|
897
|
+
`,Ma={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};function ea(s){return{formatters:void 0,fees:void 0,serializers:void 0,...s}}const _h=ea({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"}),Ch=ea({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"}),cz=ea({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"});ea({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});ea({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 lz={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"]},Om={getMethodsByChainNamespace(s){return lz[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 _h.caipNetworkId:h.chains.push(_h.deprecatedCaipNetworkId);break;case Ch.caipNetworkId:h.chains.push(Ch.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 ay.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 xm{constructor({provider:e,caipNetworks:t,namespace:i}){this.id=se.CONNECTOR_ID.WALLET_CONNECT,this.name=sc.ConnectorNamesMap[se.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=sc.ConnectorImageIds[se.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=R.state.universalProviderConfigOverride,i=Om.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 mn.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:hz})}}const hz=["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 uz{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:se.CONNECTOR_ID.AUTH,type:"AUTH",name:se.CONNECTOR_NAMES.AUTH,provider:e,imageId:sc.ConnectorImageIds[se.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){ie.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:R.state.defaultAccountTypes[t.chainNamespace]});this.emit("switchNetwork",o)}}getWalletConnectConnector(){const e=this.connectors.find(t=>t instanceof xm);if(!e)throw new Error("WalletConnectConnector not found");return e}}class dz extends uz{setUniversalProvider(e){this.addConnector(new xm({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=>le.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var n,o,a,c,l;if(!(e.caipNetwork&&Vt.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(ie.state.balanceLoading&&e.chainId===((c=I.state.activeCaipNetwork)==null?void 0:c.id))return{balance:ie.state.balance||"0.00",symbol:ie.state.balanceSymbol||""};const r=(await ie.fetchTokenBalance()).find(h=>{var d,p;return h.chainId===`${(d=e.caipNetwork)==null?void 0:d.chainNamespace}:${e.chainId}`&&h.symbol===((p=e.caipNetwork)==null?void 0:p.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=I.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===se.CHAIN.SOLANA?n=(await t.request({method:"solana_signMessage",params:{message:Ey.encode(new TextEncoder().encode(i)),pubkey:r}},(a=I.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:n=await t.request({method:"personal_sign",params:[i,r]},(c=I.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===se.CHAIN.EVM)try{await((r=i.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:wn.toHex(t.id)}]}))}catch(h){if(h.code===Ma.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||h.code===Ma.ERROR_INVALID_CHAIN_ID||h.code===Ma.ERROR_CODE_DEFAULT||((o=(n=h==null?void 0:h.data)==null?void 0:n.originalError)==null?void 0:o.code)===Ma.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=i.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:wn.toHex(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 pz{constructor(e){var t;this.hasSwitchedToPreferredAccountTypeOnConnect=!1,this.chainNamespaces=[],this.reportedAlertErrors={},this.getCaipNetwork=i=>{var r,n;if(i){const o=(r=I.getNetworkData(i))==null?void 0:r.caipNetwork;return o||((n=I.getRequestedCaipNetworks(i).filter(a=>a.chainNamespace===i))==null?void 0:n[0])}return I.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const i=this.getCaipNetwork();if(i)return i.id},this.getCaipNetworks=i=>I.getRequestedCaipNetworks(i),this.getActiveChainNamespace=()=>I.state.activeChain,this.setRequestedCaipNetworks=(i,r)=>{I.setRequestedCaipNetworks(i,r)},this.getApprovedCaipNetworkIds=()=>I.getAllApprovedCaipNetworkIds(),this.getCaipAddress=i=>I.state.activeChain===i||!i?I.state.activeCaipAddress:I.getAccountProp("caipAddress",i),this.setClientId=i=>{ne.setClientId(i)},this.getProvider=i=>et.getProvider(i),this.getProviderType=i=>et.getProviderId(i),this.getPreferredAccountType=()=>ie.state.preferredAccountType,this.setCaipAddress=(i,r)=>{ie.setCaipAddress(i,r)},this.setBalance=(i,r,n)=>{ie.setBalance(i,r,n)},this.setProfileName=(i,r)=>{ie.setProfileName(i,r)},this.setProfileImage=(i,r)=>{ie.setProfileImage(i,r)},this.setUser=(i,r)=>{ie.setUser(i,r),R.state.enableEmbedded&&ot.close()},this.resetAccount=i=>{ie.resetAccount(i)},this.setCaipNetwork=i=>{I.setActiveCaipNetwork(i)},this.setCaipNetworkOfNamespace=(i,r)=>{I.setChainNetworkData(r,{caipNetwork:i})},this.setAllAccounts=(i,r)=>{ie.setAllAccounts(i,r),R.setHasMultipleAddresses((i==null?void 0:i.length)>1)},this.setStatus=(i,r)=>{ie.setStatus(i,r),ce.isConnected()?X.setConnectionStatus("connected"):X.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=i=>I.getAccountProp("address",i),this.setConnectors=i=>{const r=[...ce.getConnectors(),...i];ce.setConnectors(r)},this.fetchIdentity=i=>ne.fetchIdentity(i),this.getReownName=i=>ay.getNamesForAddress(i),this.getConnectors=()=>ce.getConnectors(),this.getConnectorImage=i=>Kh.getConnectorImage(i),this.setConnectedWalletInfo=(i,r)=>{const n=et.getProviderId(r),o=i?{...i,type:n}:void 0;ie.setConnectedWalletInfo(o,r)},this.getIsConnectedState=()=>!!I.state.activeCaipAddress,this.addAddressLabel=(i,r,n)=>{ie.addAddressLabel(i,r,n)},this.removeAddressLabel=(i,r)=>{ie.removeAddressLabel(i,r)},this.getAddress=i=>I.state.activeChain===i||!i?ie.state.address:I.getAccountProp("address",i),this.setApprovedCaipNetworksData=i=>I.setApprovedCaipNetworksData(i),this.resetNetwork=i=>{I.resetNetwork(i)},this.addConnector=i=>{ce.addConnector(i)},this.resetWcConnection=()=>{Fe.resetWcConnection()},this.setAddressExplorerUrl=(i,r)=>{ie.setAddressExplorerUrl(i,r)},this.setSmartAccountDeployed=(i,r)=>{ie.setSmartAccountDeployed(i,r)},this.setSmartAccountEnabledNetworks=(i,r)=>{I.setSmartAccountEnabledNetworks(i,r)},this.setPreferredAccountType=(i,r)=>{ie.setPreferredAccountType(i,r)},this.setEIP6963Enabled=i=>{R.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(),gi.set({initialized:!0})}sendInitializeEvent(e){var i;const{...t}=e;delete t.adapters,qe.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&&Ft.setThemeMode(e.themeMode),e.themeVariables&&Ft.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");I.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&I.setActiveCaipNetwork(t)}initializeConnectionController(e){Fe.setWcBasic(e.basic??!1)}initializeConnectorController(){ce.initialize(this.chainNamespaces)}initializeOptionsController(e){var r;R.setDebug(e.debug!==!1),R.setEnableWalletConnect(e.enableWalletConnect!==!1),R.setEnableWalletGuide(e.enableWalletGuide!==!1),R.setEnableWallets(e.enableWallets!==!1),R.setEIP6963Enabled(e.enableEIP6963!==!1),R.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),R.setEnableAuthLogger(e.enableAuthLogger!==!1),R.setCustomRpcUrls(e.customRpcUrls),R.setSdkVersion(e.sdkVersion),R.setProjectId(e.projectId),R.setEnableEmbedded(e.enableEmbedded),R.setAllWallets(e.allWallets),R.setIncludeWalletIds(e.includeWalletIds),R.setExcludeWalletIds(e.excludeWalletIds),R.setFeaturedWalletIds(e.featuredWalletIds),R.setTokens(e.tokens),R.setTermsConditionsUrl(e.termsConditionsUrl),R.setPrivacyPolicyUrl(e.privacyPolicyUrl),R.setCustomWallets(e.customWallets),R.setFeatures(e.features),R.setAllowUnsupportedChain(e.allowUnsupportedChain),R.setDefaultAccountTypes(e.defaultAccountTypes),R.setUniversalProviderConfigOverride(e.universalProviderConfigOverride);const t=this.getDefaultMetaData();if(!e.metadata&&t&&(e.metadata=t),R.setMetadata(e.metadata),R.setDisableAppend(e.disableAppend),R.setEnableEmbedded(e.enableEmbedded),R.setSIWX(e.siwx),!e.projectId){yo.open($a.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((r=e.adapters)==null?void 0:r.find(n=>n.namespace===se.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");R.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=hn.getUnsupportedNetwork(`${t}:${e}`);I.setActiveCaipNetwork(i)}}getDefaultNetwork(){return hn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return hn.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return hn.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?hn.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var n;const e=I.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),X.setConnectedNamespaces([...I.state.chains.keys()]),this.chainNamespaces.forEach(o=>{ce.setConnectorId(_i.CONNECTOR_TYPE_WALLET_CONNECT,o)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:t,type:i,provider:r,chain:n,caipNetwork:o})=>{var f,g,w,v,b,y,A;const a=I.state.activeChain,c=n||a,l=this.getAdapter(c);if(n&&n!==a&&!o){const _=(f=this.caipNetworks)==null?void 0:f.find(C=>C.chainNamespace===n);_&&this.setCaipNetwork(_)}if(!l)throw new Error("Adapter not found");const h=this.getCaipNetwork(c),d=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:((v=(w=(g=o==null?void 0:o.rpcUrls)==null?void 0:g.default)==null?void 0:w.http)==null?void 0:v[0])||((A=(y=(b=h==null?void 0:h.rpcUrls)==null?void 0:b.default)==null?void 0:y.http)==null?void 0:A[0])});if(!d)return;X.addConnectedNamespace(c),this.syncProvider({...d,chainNamespace:c}),await this.syncAccount({...d,chainNamespace:c});const{accounts:p}=await l.getAccounts({namespace:c,id:e});this.setAllAccounts(p,c)},reconnectExternal:async({id:e,info:t,type:i,provider:r})=>{var a;const n=I.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})),X.addConnectedNamespace(n))},disconnect:async e=>{const t=e||I.state.activeChain,i=this.getAdapter(t),r=et.getProvider(t),n=et.getProviderId(t);await(i==null?void 0:i.disconnect({provider:r,providerType:n})),X.removeConnectedNamespace(t),et.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(I.state.activeChain),i=await(t==null?void 0:t.signMessage({message:e,address:ie.state.address,provider:et.getProvider(I.state.activeChain)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{if(e.chainNamespace===se.CHAIN.EVM){const t=this.getAdapter(I.state.activeChain),i=et.getProvider(I.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===se.CHAIN.EVM){const t=this.getAdapter(I.state.activeChain),i=et.getProvider(I.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(I.state.activeChain),t=await(e==null?void 0:e.getProfile({address:ie.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(I.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(I.state.activeChain),i=this.getCaipNetwork(),r=this.getCaipAddress(),n=et.getProvider(I.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(I.state.activeChain);return(i==null?void 0:i.parseUnits({value:e,decimals:t}))??0n},formatUnits:(e,t)=>{const i=this.getAdapter(I.state.activeChain);return(i==null?void 0:i.formatUnits({value:e,decimals:t}))??"0"},getCapabilities:async e=>{const t=this.getAdapter(I.state.activeChain);return await(t==null?void 0:t.getCapabilities(e))},grantPermissions:async e=>{const t=this.getAdapter(I.state.activeChain);return await(t==null?void 0:t.grantPermissions(e))},revokePermissions:async e=>{const t=this.getAdapter(I.state.activeChain);return t!=null&&t.revokePermissions?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>{const t=this.getAdapter(I.state.activeChain);return await(t==null?void 0:t.walletGetAssets(e))??{}}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Fe.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){var t,i,r,n,o;if(et.getProviderId(I.state.activeChain)===_i.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=et.getProvider(t),n=et.getProviderId(t);if(e.chainNamespace===I.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===_i.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}=Ii.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 dz({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=X.getConnectionStatus();i==="connected"?this.setStatus("connecting",e):i==="disconnected"?(X.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=I.state.activeChain===e,c=I.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=ie.state.address,n=I.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=I.state.activeChain===e;o&&n?this.syncAccount({address:r,chainId:n,chainNamespace:e}):o&&((a=I.state.activeCaipNetwork)!=null&&a.id)?this.syncAccount({address:r,chainId:(c=I.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=ce.getConnectorId(e);switch(this.setStatus("connecting",e),t){case se.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case se.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=ce.getConnectorId(e),r=this.getCaipNetwork(e),n=ce.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([le.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,d;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=(d=I.state.activeCaipNetwork)==null?void 0:d.id,o=r.find(p=>{const{chainId:f}=Ii.parseCaipAddress(p);return f===(n==null?void 0:n.toString())})||r[0];if(o){const p=Ii.validateCaipAddress(o),{chainId:f,address:g}=Ii.parseCaipAddress(p);if(et.setProviderId(t,_i.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&I.state.activeCaipNetwork&&(i==null?void 0:i.namespace)!==se.CHAIN.EVM){const w=i==null?void 0:i.getWalletConnectProvider({caipNetworks:this.caipNetworks,provider:this.universalProvider,activeCaipNetwork:I.state.activeCaipNetwork});et.setProvider(t,w)}else et.setProvider(t,this.universalProvider);ce.setConnectorId(se.CONNECTOR_ID.WALLET_CONNECT,t),X.addConnectedNamespace(t),this.syncWalletConnectAccounts(t),await this.syncAccount({address:g,chainId:f,chainNamespace:t})}else this.setStatus("disconnected",t);await I.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}=Ii.parseCaipAddress(c);return l}).filter((c,l,h)=>h.indexOf(c)===l);t&&this.setAllAccounts(t.map(c=>le.createAccount(e,c,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:i,chainNamespace:r}){et.setProviderId(r,e),et.setProvider(r,t),ce.setConnectorId(i,r)}async syncAccount(e){var d,p,f,g,w,v;const t=e.chainNamespace===I.state.activeChain,i=I.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:n,chainNamespace:o}=e,{chainId:a}=X.getActiveNetworkProps(),c=n||a,l=((d=I.state.activeCaipNetwork)==null?void 0:d.name)===se.UNSUPPORTED_NETWORK_NAME,h=I.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!h)&&c){let b=(p=this.caipNetworks)==null?void 0:p.find(_=>_.id.toString()===c.toString()),y=(f=this.caipNetworks)==null?void 0:f.find(_=>_.chainNamespace===o);if(!h&&!b&&!y){const _=this.getApprovedCaipNetworkIds()||[],C=_.find(P=>{var x;return((x=Ii.parseCaipNetworkId(P))==null?void 0:x.chainId)===c.toString()}),T=_.find(P=>{var x;return((x=Ii.parseCaipNetworkId(P))==null?void 0:x.chainNamespace)===o});b=(g=this.caipNetworks)==null?void 0:g.find(P=>P.caipNetworkId===C),y=(w=this.caipNetworks)==null?void 0:w.find(P=>P.caipNetworkId===T||"deprecatedCaipNetworkId"in P&&P.deprecatedCaipNetworkId===T)}const A=b||y;(A==null?void 0:A.chainNamespace)===I.state.activeChain?R.state.enableNetworkSwitch&&!R.state.allowUnsupportedChain&&((v=I.state.activeCaipNetwork)==null?void 0:v.name)===se.UNSUPPORTED_NETWORK_NAME?I.showUnsupportedChainUI():this.setCaipNetwork(A):t||i&&this.setCaipNetworkOfNamespace(i,o),this.syncConnectedWalletInfo(o),Pm.isLowerCaseMatch(r,ie.state.address)||this.syncAccountInfo(r,A==null?void 0:A.id,o),t?await this.syncBalance({address:r,chainId:A==null?void 0:A.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=ce.getConnectorId(e),i=et.getProviderId(e);if(i===_i.CONNECTOR_TYPE_ANNOUNCED||i===_i.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===_i.CONNECTOR_TYPE_WALLET_CONNECT){const n=et.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===se.CONNECTOR_ID.COINBASE){const n=this.getConnectors().find(o=>o.id===se.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(n)},e)}else this.setConnectedWalletInfo({name:t},e)}async syncBalance(e){!ry.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,d,p;const e=ez.createLogger((f,...g)=>{f&&this.handleAlertError(f),console.error(...g)}),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?(d=this.options)==null?void 0:d.metadata.icons:[""]},logger:e};R.setManualWCControl(!!((p=this.options)!=null&&p.manualWCControl)),this.universalProvider=this.options.universalProvider??await cu.init(t),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{Fe.setUri(e)}),this.universalProvider.on("connect",Fe.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),Fe.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(Om.isSessionEventData(e)){const{name:t,data:i}=e.params.event;t==="accountsChanged"&&Array.isArray(i)&&le.isCaipAddress(i[0])&&this.syncAccount(Ii.parseCaipAddress(i[0]))}}))}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&le.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){qe.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($a.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[i,r]=t??[],{message:n,alertErrorKey:o}=r??{};if(i&&n&&!this.reportedAlertErrors[i]){const a=$a.ALERT_ERRORS[o];a&&(yo.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&&Fe.setUri(e.uri),await ot.open(e)}async close(){await this.injectModalUi(),ot.close()}setLoading(e,t){ot.setLoading(e,t)}async disconnect(e){await Fe.disconnect(e)}getError(){return""}getChainId(){var e;return(e=I.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){yo.open($a.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await I.switchActiveNetwork(t)}getWalletProvider(){return I.state.activeChain?et.state.providers[I.state.activeChain]:null}getWalletProviderType(){return et.getProviderId(I.state.activeChain)}subscribeProviders(e){return et.subscribeProviders(e)}getThemeMode(){return Ft.state.themeMode}getThemeVariables(){return Ft.state.themeVariables}setThemeMode(e){Ft.setThemeMode(e),Mm(Ft.state.themeMode)}setTermsConditionsUrl(e){R.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){R.setPrivacyPolicyUrl(e)}setThemeVariables(e){Ft.setThemeVariables(e),rz(Ft.state.themeVariables)}subscribeTheme(e){return Ft.subscribe(e)}getWalletInfo(){return ie.state.connectedWalletInfo}getAccount(e){const t=ce.getAuthConnector(e),i=I.getAccountData(e);if(i)return{allAccounts:i.allAccounts,caipAddress:i.caipAddress,address:le.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?I.subscribeChainProp("accountState",i,t):I.subscribe(i),ce.subscribe(i)}subscribeNetwork(e){return I.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t==null?void 0:t.id,caipNetworkId:t==null?void 0:t.caipNetworkId})})}subscribeWalletInfo(e){return ie.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){ie.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){I.subscribeKey("activeCaipNetwork",e)}getState(){return gi.state}subscribeState(e){return gi.subscribe(e)}showErrorMessage(e){vt.showError(e)}showSuccessMessage(e){vt.showSuccess(e)}getEvent(){return{...qe.state}}subscribeEvents(e){return qe.subscribe(e)}replace(e){Me.replace(e)}redirect(e){Me.push(e)}popTransactionStack(e){Me.popTransactionStack(e)}isOpen(){return ot.state.open}isTransactionStackEmpty(){return Me.state.transactionStack.length===0}isTransactionShouldReplaceView(){var e;return(e=Me.state.transactionStack[Me.state.transactionStack.length-1])==null?void 0:e.replace}static getInstance(){return this.instance}updateFeatures(e){R.setFeatures(e)}updateOptions(e){const i={...R.state||{},...e};R.setOptions(i)}setConnectMethodsOrder(e){R.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){R.setWalletFeaturesOrder(e)}setCollapseWallets(e){R.setCollapseWallets(e)}setSocialsOrder(e){R.setSocialsOrder(e)}getConnectMethodsOrder(){return rc.getConnectOrderMethod(R.state.features,ce.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);I.removeAdapter(e),ce.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),I.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);I.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");I.removeNetwork(e,t),this.caipNetworks=[...r]}}let af=!1;class gz extends pz{async open(e){ce.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&Fe.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!af&&le.isClient()){if(await Promise.resolve().then(()=>require("./basic-DUWaF2I0.js")),await Promise.resolve().then(()=>require("./w3m-modal-xmdf4r6V.js")),!document.querySelector("w3m-modal")){const t=document.createElement("w3m-modal");!R.state.disableAppend&&!R.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",t)}af=!0}}}const fz="1.7.2";function wz(s){return new gz({...s,basic:!0,sdkVersion:`html-core-${fz}`})}function yz(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),d=h.charCodeAt(0);if(e[d]!==255)throw new TypeError(h+" is ambiguous");e[d]=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,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,h++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let y=l[p],A=0;for(let _=g-1;(y!==0||A<d)&&_!==-1;_--,A++)y+=256*w[_]>>>0,w[_]=y%t>>>0,y=y/t>>>0;if(y!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(h);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,d=0,p=0;for(;l[h]===i;)d++,h++;const f=(l.length-h)*r+1>>>0,g=new Uint8Array(f);for(;h<l.length;){const y=l.charCodeAt(h);if(y>255)return;let A=e[y];if(A===255)return;let _=0;for(let C=f-1;(A!==0||_<p)&&C!==-1;C--,_++)A+=t*g[C]>>>0,g[C]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=_,h++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 mz="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const _l=yz(mz);class fn extends Error{constructor(){super(),Object.setPrototypeOf(this,fn.prototype)}}class cf extends Error{constructor(e){super(`WalletConnect Adapter - Method ${e} is not supported by the wallet`),this.name="WalletConnectFeatureNotSupportedError"}}function bz(s){let e=[s];return s===gt.Mainnet||s===gt.Deprecated_Mainnet?(e=[gt.Mainnet,gt.Deprecated_Mainnet],s===gt.Deprecated_Mainnet&&console.warn(nc.mainnet)):(s===gt.Deprecated_Devnet||s===gt.Devnet)&&(e=[gt.Devnet,gt.Deprecated_Devnet],console.warn(nc.devnet)),e}const nc={mainnet:`You are using a deprecated chain ID for Solana Mainnet, please use ${gt.Mainnet} instead.`,devnet:`You are using a deprecated chain ID for Solana Devnet, please use ${gt.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 lf(s,e){var i;const t=(i=s.namespaces.solana)==null?void 0:i.accounts.map(r=>`solana:${r.split(":")[1]}`);if(e===gt.Mainnet)return t!=null&&t.find(r=>r===gt.Mainnet)?gt.Mainnet:(console.warn(nc.wallet),gt.Deprecated_Mainnet);if(e===gt.Devnet)return t!=null&&t.find(r=>r===gt.Devnet)?gt.Devnet:(console.warn(nc.wallet),gt.Deprecated_Devnet);throw Error("WalletConnect Solana Adapter: Unable to get a default chain from the session.")}function vz(s){return{optionalNamespaces:{solana:{chains:bz(s),methods:[Is.signTransaction,Is.signMessage],events:[]}}}}class lu extends Error{constructor(){super("QR Code Modal was closed by user"),Object.setPrototypeOf(this,lu.prototype),this.name="QRCodeModalError"}}class Iz{constructor(e){Nt(this,"_UniversalProvider");Nt(this,"_session");Nt(this,"_modal");Nt(this,"_projectId");Nt(this,"_network");Nt(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=lf(this._session,this._network);return this._network=h,this._UniversalProvider.setDefaultChain(h),{publicKey:this.publicKey}}await this.initModal();const e=vz(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 lu)});try{const h=await Promise.race([(o=this._UniversalProvider)==null?void 0:o.connect(e),new Promise((p,f)=>{i.addEventListener("abort",()=>{f(i.reason)})})]);if((a=this._modal)==null||a.close(),this._session=h,!h)throw new cc;const d=lf(h,this._network);return this._network=d,(c=this._UniversalProvider)==null||c.setDefaultChain(d),{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 fn}get client(){if(this._UniversalProvider)return this._UniversalProvider;throw new fn}get session(){if(!this._session)throw new fn;return this._session}get publicKey(){var e,t,i;if((e=this._UniversalProvider)!=null&&e.session&&this._session){const{address:r}=v0(((i=(t=this._session)==null?void 0:t.namespaces.solana)==null?void 0:i.accounts[0])??"");return new N.PublicKey(r)}throw new fn}async signTransaction(e){this.checkIfWalletSupportsMethod(Is.signTransaction);const t=di(e),i=t?{}:e,{signature:r,transaction:n}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:Is.signTransaction,params:{...i,transaction:this.serialize(e)}}});return n?this.deserialize(n,t):(e.addSignature(this.publicKey,N.dist.Buffer.from(_l.decode(r))),e)}async signMessage(e){this.checkIfWalletSupportsMethod(Is.signMessage);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:Is.signMessage,params:{pubkey:this.publicKey.toString(),message:_l.encode(e)}}});return _l.decode(t)}async signAndSendTransaction(e){this.checkIfWalletSupportsMethod(Is.signAndSendTransaction);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:Is.signAndSendTransaction,params:{transaction:this.serialize(e)}}});return t}async signAllTransactions(e){try{this.checkIfWalletSupportsMethod(Is.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:Is.signAllTransactions,params:{transactions:t}}});return e.map((r,n)=>di(r)?this.deserialize(i[n]??"",!0):this.deserialize(i[n]??""))}catch(t){if(t instanceof cf){const i=e.map(n=>this.signTransaction(n));return await Promise.all(i)}throw t}}async initClient(e){const t=await zO.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=wz({projectId:this._projectId,universalProvider:this._UniversalProvider,networks:[_h,Ch,cz],manualWCControl:!0})}}serialize(e){return N.dist.Buffer.from(e.serialize({verifySignatures:!1})).toString("base64")}deserialize(e,t=!1){return t?N.VersionedTransaction.deserialize(N.dist.Buffer.from(e,"base64")):N.Transaction.from(N.dist.Buffer.from(e,"base64"))}checkIfWalletSupportsMethod(e){var t;if(!((t=this.session.namespaces.solana)!=null&&t.methods.includes(e)))throw new cf(e)}}const Ez="WalletConnect";class Az extends $h{constructor(t){super();Nt(this,"name",Ez);Nt(this,"url","https://walletconnect.org");Nt(this,"icon","data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjE4NSIgdmlld0JveD0iMCAwIDMwMCAxODUiIHdpZHRoPSIzMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTYxLjQzODU0MjkgMzYuMjU2MjYxMmM0OC45MTEyMjQxLTQ3Ljg4ODE2NjMgMTI4LjIxMTk4NzEtNDcuODg4MTY2MyAxNzcuMTIzMjA5MSAwbDUuODg2NTQ1IDUuNzYzNDE3NGMyLjQ0NTU2MSAyLjM5NDQwODEgMi40NDU1NjEgNi4yNzY1MTEyIDAgOC42NzA5MjA0bC0yMC4xMzY2OTUgMTkuNzE1NTAzYy0xLjIyMjc4MSAxLjE5NzIwNTEtMy4yMDUzIDEuMTk3MjA1MS00LjQyODA4MSAwbC04LjEwMDU4NC03LjkzMTE0NzljLTM0LjEyMTY5Mi0zMy40MDc5ODE3LTg5LjQ0Mzg4Ni0zMy40MDc5ODE3LTEyMy41NjU1Nzg4IDBsLTguNjc1MDU2MiA4LjQ5MzYwNTFjLTEuMjIyNzgxNiAxLjE5NzIwNDEtMy4yMDUzMDEgMS4xOTcyMDQxLTQuNDI4MDgwNiAwbC0yMC4xMzY2OTQ5LTE5LjcxNTUwMzFjLTIuNDQ1NTYxMi0yLjM5NDQwOTItMi40NDU1NjEyLTYuMjc2NTEyMiAwLTguNjcwOTIwNHptMjE4Ljc2Nzc5NjEgNDAuNzczNzQ0OSAxNy45MjE2OTcgMTcuNTQ2ODk3YzIuNDQ1NTQ5IDIuMzk0Mzk2OSAyLjQ0NTU2MyA2LjI3NjQ3NjkuMDAwMDMxIDguNjcwODg5OWwtODAuODEwMTcxIDc5LjEyMTEzNGMtMi40NDU1NDQgMi4zOTQ0MjYtNi40MTA1ODIgMi4zOTQ0NTMtOC44NTYxNi4wMDAwNjItLjAwMDAxLS4wMDAwMS0uMDAwMDIyLS4wMDAwMjItLjAwMDAzMi0uMDAwMDMybC01Ny4zNTQxNDMtNTYuMTU0NTcyYy0uNjExMzktLjU5ODYwMi0xLjYwMjY1LS41OTg2MDItMi4yMTQwNCAwLS4wMDAwMDQuMDAwMDA0LS4wMDAwMDcuMDAwMDA4LS4wMDAwMTEuMDAwMDExbC01Ny4zNTI5MjEyIDU2LjE1NDUzMWMtMi40NDU1MzY4IDIuMzk0NDMyLTYuNDEwNTc1NSAyLjM5NDQ3Mi04Ljg1NjE2MTIuMDAwMDg3LS4wMDAwMTQzLS4wMDAwMTQtLjAwMDAyOTYtLjAwMDAyOC0uMDAwMDQ0OS0uMDAwMDQ0bC04MC44MTI0MTk0My03OS4xMjIxODVjLTIuNDQ1NTYwMjEtMi4zOTQ0MDgtMi40NDU1NjAyMS02LjI3NjUxMTUgMC04LjY3MDkxOTdsMTcuOTIxNzI5NjMtMTcuNTQ2ODY3M2MyLjQ0NTU2MDItMi4zOTQ0MDgyIDYuNDEwNTk4OS0yLjM5NDQwODIgOC44NTYxNjAyIDBsNTcuMzU0OTc3NSA1Ni4xNTUzNTdjLjYxMTM5MDguNTk4NjAyIDEuNjAyNjQ5LjU5ODYwMiAyLjIxNDAzOTggMCAuMDAwMDA5Mi0uMDAwMDA5LjAwMDAxNzQtLjAwMDAxNy4wMDAwMjY1LS4wMDAwMjRsNTcuMzUyMTAzMS01Ni4xNTUzMzNjMi40NDU1MDUtMi4zOTQ0NjMzIDYuNDEwNTQ0LTIuMzk0NTUzMSA4Ljg1NjE2MS0uMDAwMi4wMDAwMzQuMDAwMDMzNi4wMDAwNjguMDAwMDY3My4wMDAxMDEuMDAwMTAxbDU3LjM1NDkwMiA1Ni4xNTU0MzJjLjYxMTM5LjU5ODYwMSAxLjYwMjY1LjU5ODYwMSAyLjIxNDA0IDBsNTcuMzUzOTc1LTU2LjE1NDMyNDljMi40NDU1NjEtMi4zOTQ0MDkyIDYuNDEwNTk5LTIuMzk0NDA5MiA4Ljg1NjE2IDB6IiBmaWxsPSIjM2I5OWZjIi8+PC9zdmc+");Nt(this,"supportedTransactionVersions",new Set(["legacy",0]));Nt(this,"_publicKey");Nt(this,"_connecting");Nt(this,"_wallet");Nt(this,"_config");Nt(this,"_readyState");Nt(this,"_onDisconnect");this._publicKey=null,this._connecting=!1,this._config=t,this._wallet=null,this._readyState=typeof window>"u"?pe.Unsupported:pe.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!==pe.Loadable)throw new Li;this._connecting=!0,this._wallet=new Iz({network:this._config.network===No.Mainnet?Ba.Mainnet:Ba.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 Gb:(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 ko(i==null?void 0:i.message,i))}}this.emit("disconnect")}async signTransaction(t){try{const i=this._wallet;if(!i)throw new Ke;try{return await i.signTransaction(t)}catch(r){throw new rt(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 Ke;try{return await i.signMessage(t)}catch(r){throw new jo(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 Ke;try{return await i.signAndSendTransaction(t)}catch(r){throw new rt(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 Ke;try{return await i.signAllTransactions(t)}catch(r){throw new rt(r==null?void 0:r.message,r)}}catch(i){throw this.emit("error",i),i}}}const Nz={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"},_z=[Nz],Cz=s=>_z.find(e=>e.name.toLocaleLowerCase().includes(s.name.toLocaleLowerCase()))||s,Sz=(s,e,t)=>e[s]||t[s],hf=(s,e)=>Sz(s,Cz(e),e);class hi extends tt.Wallet{constructor(e,t){super(),this.adapter=e,this.connection=t}getAdapter(){return this.adapter}getName(){return hf("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 tt.CHAIN_ID_SOLANA}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 hf("icon",this.adapter)}getWalletState(){const e=this.adapter.readyState;if(!(e in tt.WalletState))throw new Error(`Unknown wallet state ${e}`);return tt.WalletState[e]}getFeatures(){const e=[tt.BaseFeatures.SendTransaction,tt.BaseFeatures.SignAndSendTransaction];return this.adapter.signTransaction&&this.adapter.signAllTransactions&&e.push(tt.BaseFeatures.SignTransaction),this.adapter.signMessage&&e.push(tt.BaseFeatures.SignMessage),e}supportsChain(e){return e===tt.CHAIN_ID_SOLANA}}function Tz(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),d=h.charCodeAt(0);if(e[d]!==255)throw new TypeError(h+" is ambiguous");e[d]=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,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,h++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let y=l[p],A=0;for(let _=g-1;(y!==0||A<d)&&_!==-1;_--,A++)y+=256*w[_]>>>0,w[_]=y%t>>>0,y=y/t>>>0;if(y!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(h);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let h=0,d=0,p=0;for(;l[h]===i;)d++,h++;const f=(l.length-h)*r+1>>>0,g=new Uint8Array(f);for(;h<l.length;){const y=l.charCodeAt(h);if(y>255)return;let A=e[y];if(A===255)return;let _=0;for(let C=f-1;(A!==0||_<p)&&C!==-1;C--,_++)A+=t*g[C]>>>0,g[C]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=_,h++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 Pz="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const $z=Tz(Pz);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)},lt=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},Ot,es,ar,cr,er,go,oc,_e,ac,Sh,qa,Th,Ao,Ph,uf,df,pf,gf;class Mz extends yf{get name(){return Z(this,_e,"f").name}get url(){return"https://github.com/solana-labs/wallet-standard"}get icon(){return Z(this,_e,"f").icon}get readyState(){return Z(this,ac,"f")}get publicKey(){return Z(this,ar,"f")}get connecting(){return Z(this,cr,"f")}get supportedTransactionVersions(){return Z(this,oc,"f")}get wallet(){return Z(this,_e,"f")}get standard(){return!0}constructor({wallet:e}){super(),Ot.add(this),es.set(this,void 0),ar.set(this,void 0),cr.set(this,void 0),er.set(this,void 0),go.set(this,void 0),oc.set(this,void 0),_e.set(this,void 0),ac.set(this,typeof window>"u"||typeof document>"u"?pe.Unsupported:pe.Installed),Ph.set(this,t=>{if("accounts"in t){const i=Z(this,_e,"f").accounts[0];Z(this,es,"f")&&!Z(this,er,"f")&&i!==Z(this,es,"f")&&(i?Z(this,Ot,"m",qa).call(this,i):(this.emit("error",new wf),Z(this,Ot,"m",Th).call(this)))}"features"in t&&Z(this,Ot,"m",Ao).call(this)}),lt(this,_e,e,"f"),lt(this,es,null,"f"),lt(this,ar,null,"f"),lt(this,cr,!1,"f"),lt(this,er,!1,"f"),lt(this,go,Z(this,_e,"f").features[bf].on("change",Z(this,Ph,"f")),"f"),Z(this,Ot,"m",Ao).call(this)}destroy(){lt(this,es,null,"f"),lt(this,ar,null,"f"),lt(this,cr,!1,"f"),lt(this,er,!1,"f");const e=Z(this,go,"f");e&&(lt(this,go,null,"f"),e())}async autoConnect(){return Z(this,Ot,"m",Sh).call(this,{silent:!0})}async connect(){return Z(this,Ot,"m",Sh).call(this)}async disconnect(){if($u in Z(this,_e,"f").features)try{lt(this,er,!0,"f"),await Z(this,_e,"f").features[$u].disconnect()}catch(e){this.emit("error",new ko(e==null?void 0:e.message,e))}finally{lt(this,er,!1,"f")}Z(this,Ot,"m",Th).call(this)}async sendTransaction(e,t,i={}){try{const r=Z(this,es,"f");if(!r)throw new Ke;let n;if(Pi in Z(this,_e,"f").features)if(r.features.includes(Pi))n=Pi;else if(Mt in Z(this,_e,"f").features&&r.features.includes(Mt))n=Mt;else throw new As;else if(Mt in Z(this,_e,"f").features){if(!r.features.includes(Mt))throw new As;n=Mt}else throw new un;const o=pv(t.rpcEndpoint);if(!r.chains.includes(o))throw new rr;try{const{signers:a,...c}=i;let l;if(di(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===Pi){const[h]=await Z(this,_e,"f").features[Pi].signAndSendTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:Dc(c.preflightCommitment||t.commitment),skipPreflight:c.skipPreflight,maxRetries:c.maxRetries,minContextSlot:c.minContextSlot}});return $z.encode(h.signature)}else{const[h]=await Z(this,_e,"f").features[Mt].signTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:Dc(c.preflightCommitment||t.commitment),minContextSlot:c.minContextSlot}});return await t.sendRawTransaction(h.signedTransaction,{...c,preflightCommitment:Dc(c.preflightCommitment||t.commitment)})}}catch(a){throw a instanceof Dt?a:new rr(a==null?void 0:a.message,a)}}catch(r){throw this.emit("error",r),r}}}es=new WeakMap,ar=new WeakMap,cr=new WeakMap,er=new WeakMap,go=new WeakMap,oc=new WeakMap,_e=new WeakMap,ac=new WeakMap,Ph=new WeakMap,Ot=new WeakSet,Sh=async function(e){try{if(this.connected||this.connecting)return;if(Z(this,ac,"f")!==pe.Installed)throw new Li;if(lt(this,cr,!0,"f"),!Z(this,_e,"f").accounts.length)try{await Z(this,_e,"f").features[mf].connect(e)}catch(i){throw new cc(i==null?void 0:i.message,i)}const t=Z(this,_e,"f").accounts[0];if(!t)throw new As;Z(this,Ot,"m",qa).call(this,t)}catch(t){throw this.emit("error",t),t}finally{lt(this,cr,!1,"f")}},qa=function(e){let t;try{t=new N.PublicKey(e.address)}catch(i){throw new wr(i==null?void 0:i.message,i)}lt(this,es,e,"f"),lt(this,ar,t,"f"),Z(this,Ot,"m",Ao).call(this),this.emit("connect",t)},Th=function(){lt(this,es,null,"f"),lt(this,ar,null,"f"),Z(this,Ot,"m",Ao).call(this),this.emit("disconnect")},Ao=function(){var t,i;const e=Pi in Z(this,_e,"f").features?Z(this,_e,"f").features[Pi].supportedTransactionVersions:Z(this,_e,"f").features[Mt].supportedTransactionVersions;lt(this,oc,Wb.arraysEqual(e,["legacy"])?null:new Set(e),"f"),Mt in Z(this,_e,"f").features&&((t=Z(this,es,"f"))!=null&&t.features.includes(Mt))?(this.signTransaction=Z(this,Ot,"m",uf),this.signAllTransactions=Z(this,Ot,"m",df)):(delete this.signTransaction,delete this.signAllTransactions),Ln in Z(this,_e,"f").features&&((i=Z(this,es,"f"))!=null&&i.features.includes(Ln))?this.signMessage=Z(this,Ot,"m",pf):delete this.signMessage,Oc in Z(this,_e,"f").features?this.signIn=Z(this,Ot,"m",gf):delete this.signIn},uf=async function(e){try{const t=Z(this,es,"f");if(!t)throw new Ke;if(!(Mt in Z(this,_e,"f").features))throw new un;if(!t.features.includes(Mt))throw new As;try{const r=(await Z(this,_e,"f").features[Mt].signTransaction({account:t,transaction:di(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return di(e)?N.VersionedTransaction.deserialize(r):N.Transaction.from(r)}catch(i){throw i instanceof Dt?i:new rt(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},df=async function(e){try{const t=Z(this,es,"f");if(!t)throw new Ke;if(!(Mt in Z(this,_e,"f").features))throw new un;if(!t.features.includes(Mt))throw new As;try{const i=await Z(this,_e,"f").features[Mt].signTransaction(...e.map(r=>({account:t,transaction:di(r)?r.serialize():new Uint8Array(r.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((r,n)=>{const o=i[n].signedTransaction;return di(r)?N.VersionedTransaction.deserialize(o):N.Transaction.from(o)})}catch(i){throw new rt(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},pf=async function(e){try{const t=Z(this,es,"f");if(!t)throw new Ke;if(!(Ln in Z(this,_e,"f").features))throw new un;if(!t.features.includes(Ln))throw new As;try{return(await Z(this,_e,"f").features[Ln].signMessage({account:t,message:e}))[0].signature}catch(i){throw new jo(i==null?void 0:i.message,i)}}catch(t){throw this.emit("error",t),t}},gf=async function(e={}){try{if(!(Oc in Z(this,_e,"f").features))throw new un;let t;try{[t]=await Z(this,_e,"f").features[Oc].signIn(e)}catch(i){throw new Pu(i==null?void 0:i.message,i)}if(!t)throw new Pu;return Z(this,Ot,"m",qa).call(this,t.account),t}catch(t){throw this.emit("error",t),t}};function Oz(s){return Vb.getWallets().get().filter(Yb).map(e=>new hi(new Mz({wallet:e}),s))}function xz(s){return s.includes("rpcpool.com")?"triton":s.includes("helius-rpc.com")?"helius":s.includes("rpc.ankr.com")?"ankr":"unknown"}async function Dz(s,e,t,i){const r=i.transaction.transaction,n=o=>o.programId.toString()!=="ComputeBudget111111111111111111111111111111";if(Oa.isVersionedTransaction(r)){const o=(await Promise.all(r.message.addressTableLookups.map(c=>s.getAddressLookupTable(c.accountKey)))).map(c=>c.value).filter(c=>c!==null),a=N.TransactionMessage.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 ff(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 ff(s,r)),i.transaction.signers&&r.partialSign(...i.transaction.signers);return r}async function ff(s,e,t){var A,_;let i=2e5,r=0;const n=N.ComputeBudgetProgram.setComputeUnitLimit({units:3e5});let o;if(Oa.isVersionedTransaction(e)){const C=(await Promise.all(e.message.addressTableLookups.map(P=>s.getAddressLookupTable(P.accountKey)))).map(P=>P.value).filter(P=>P!==null),T=N.TransactionMessage.decompile(e.message,{addressLookupTableAccounts:C});T.instructions=[...T.instructions,n],o=new N.VersionedTransaction(T.compileToV0Message(C)),o.signatures=[...e.signatures]}else{const C=new N.Transaction;C.recentBlockhash=e.recentBlockhash,C.feePayer=e.feePayer,C.instructions=[...e.instructions,n],C.signatures=[...e.signatures],o=C}e:for(;;){if(Oa.isVersionedTransaction(o)&&!o.message.recentBlockhash){const{blockhash:T}=await s.getLatestBlockhash(t);o.message.recentBlockhash=T}const C=await(Oa.isVersionedTransaction(o)?s.simulateTransaction(o,{commitment:t,replaceRecentBlockhash:!0}):s.simulateTransaction(o));if(C.value.err){if(kz(C.value)){if(r<5){r++,await tt.sleep(1e3);continue e}}else if(r<3){r++,await tt.sleep(1e3);continue e}throw new Error(`Simulation failed: ${JSON.stringify(C.value.err)}
|
|
898
|
+
Logs:
|
|
899
|
+
${(C.value.logs||[]).join(`
|
|
900
|
+
`)}`)}else{C.value.unitsConsumed&&(i=C.value.unitsConsumed);break}}const a=Math.floor(i*1.2),c=[];c.push(N.ComputeBudgetProgram.setComputeUnitLimit({units:a}));const l=((_=(A=tt.config.transactionSettings)==null?void 0:A.Solana)==null?void 0:_.priorityFee)||{},{percentile:h=.9,percentileMultiple:d=1,min:p=1e5,max:f=1e8}=l,g=async C=>{if(C==="triton")try{return{fee:await Tu.determinePriorityFeeTritonOne(s,e,h,d,p,f),methodUsed:"triton"}}catch(T){console.warn("Failed to determine priority fee using Triton RPC:",T)}try{return{fee:await Tu.determinePriorityFee(s,e,h,d,p,f),methodUsed:"default"}}catch(T){return console.warn("Failed to determine priority fee using Triton RPC:",T),{fee:p,methodUsed:"minimum"}}},w=xz(s.rpcEndpoint),{fee:v,methodUsed:b}=await g(w),y=v/1e6/N.LAMPORTS_PER_SOL*a;return console.table({"RPC Provider":w,"Method used":b,"Percentile used":h,"Multiple used":d,"Compute budget":a,"Priority fee":v,"Max fee in SOL":y}),c.push(N.ComputeBudgetProgram.setComputeUnitPrice({microLamports:v})),c}function kz(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 tt.isEmptyObject(e)?!1:(console.table(e),!0)}const jz=s=>s.getName().toLowerCase().replaceAll("wallet","").trim();function Rz(s){if(s==="Solana"){const e=tt.config.isMainnet?"mainnet-beta":"devnet",t=new N.Connection(tt.config.rpcs.Solana||N.clusterApiUrl(e));return{...Oz(t).reduce((i,r)=>(i[jz(r)]=r,i),{}),bitget:new hi(new Jb,t),clover:new hi(new Xb,t),coin98:new hi(new iv,t),solong:new hi(new lv,t),torus:new hi(new uv,t),nightly:new hi(new Mu,t),...tt.config.ui.walletConnectProjectId?{walletConnect:new hi(new Az({network:tt.config.isMainnet?No.Mainnet:No.Devnet,options:{projectId:tt.config.ui.walletConnectProjectId,customStoragePrefix:"wh-connect-solana-adapter"}}),t)}:{}}}else if(s==="Fogo"){if(!tt.config.rpcs.Fogo)throw new Error("Fogo RPC not found");const e=new N.Connection(tt.config.rpcs.Fogo);return{nightly:new hi(new Mu,e)}}throw new Error(`Unsupported chain: ${s}`)}async function Uz(s,e,t){if(!e)throw new Error("Wallet not found");const i=tt.config.rpcs[s.chain];if(!i)throw new Error(`${s.chain} RPC not found`);const r=(t==null?void 0:t.commitment)??"finalized",n=new N.Connection(i),{blockhash:o,lastValidBlockHeight:a}=await n.getLatestBlockhash(r),c=await Dz(n,o,a,s);let l=null,h=null,d=1,p="";const g=(await e.signTransaction(c)).serialize(),w={skipPreflight:!0,maxRetries:0,preFlightCommitment:r};p=await n.sendRawTransaction(g,w),l=n.confirmTransaction({signature:p,blockhash:o,lastValidBlockHeight:a},r);try{for(;!h&&(h=await Promise.race([l,new Promise(b=>setTimeout(()=>{b(null)},5e3))]),!h);){console.log(`Tx not confirmed after ${5e3*d++}ms, resending`);try{await n.sendRawTransaction(g,w)}catch(b){console.error("Failed to resend transaction:",b)}}}catch(v){if(v instanceof Error&&v.name==="TransactionExpiredBlockheightExceededError")for(let A=0;A<5;++A){try{if(await n.getTransaction(p,{commitment:"confirmed",maxSupportedTransactionVersion:0}))return p}catch{}await tt.sleep(2e3)}throw v}if(h.value.err){let v=`Transaction failed: ${h.value.err}`;if(typeof h.value.err=="object")try{v=`Transaction failed: ${JSON.stringify(h.value.err,(b,y)=>typeof y=="bigint"?y.toString():y)}`}catch{v="Transaction failed: Unknown error"}throw new Error(`Transaction failed: ${v}`)}return p}const Lz=Object.freeze(Object.defineProperty({__proto__:null,fetchOptions:Rz,signAndSendTransaction:Uz},Symbol.toStringTag,{value:"Module"}));exports.AccountController=ie;exports.AlertController=yo;exports.ApiController=he;exports.AssetController=Es;exports.AssetUtil=Kh;exports.ChainController=I;exports.ConnectionController=Fe;exports.ConnectorController=ce;exports.ConnectorUtil=Io;exports.ConstantsUtil=se;exports.ConstantsUtil$1=Vt;exports.ConstantsUtil$2=$m;exports.CoreHelperUtil=le;exports.EventsController=qe;exports.Hash=Tf;exports.Hash$1=wy;exports.ModalController=ot;exports.OptionsController=R;exports.RouterController=Me;exports.SIWXUtil=mn;exports.SnackController=vt;exports.StorageUtil=X;exports.ThemeController=Ft;exports.WalletUtil=rc;exports.abytes=Lo;exports.abytes$1=Ko;exports.aexists=Pl;exports.aexists$1=eh;exports.ahash=Hv;exports.ahash$1=Lx;exports.aoutput=Sf;exports.aoutput$1=fy;exports.colorStyles=az;exports.concatBytes=s0;exports.concatBytes$1=Jx;exports.createView=Zv;exports.createView$1=Kx;exports.elementStyles=oz;exports.initializeTheming=iz;exports.randomBytes=i0;exports.randomBytes$1=Zx;exports.resetStyles=nz;exports.rotr=Xv;exports.rotr$1=Gx;exports.solana=Lz;exports.toBytes=Mh;exports.toBytes$1=Gh;exports.wrapConstructor=Pf;exports.wrapConstructor$1=yy;
|