@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,11 @@
|
|
|
1
|
+
"use strict";const u=require("./index.es-D6S74vhi.js"),q=require("./web3-COTIsLs8.js");function Si(i,{strict:e=!0}={}){return!i||typeof i!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(i):i.startsWith("0x")}function Nr(i){return Si(i,{strict:!1})?Math.ceil((i.length-2)/2):i.length}const Oo="2.23.2";let pi={getDocsUrl:({docsBaseUrl:i,docsPath:e="",docsSlug:t})=>e?`${i??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${Oo}`};class St extends Error{constructor(e,t={}){var a;const s=(()=>{var c;return t.cause instanceof St?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),r=t.cause instanceof St&&t.cause.docsPath||t.docsPath,n=(a=pi.getDocsUrl)==null?void 0:a.call(pi,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...s?[`Details: ${s}`]:[],...pi.version?[`Version: ${pi.version}`]:[]].join(`
|
|
2
|
+
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Oo}walk(e){return Ao(this,e)}}function Ao(i,e){return e!=null&&e(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?Ao(i.cause,e):e?null:i}class xo extends St{constructor({size:e,targetSize:t,type:s}){super(`${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function oi(i,{dir:e,size:t=32}={}){return typeof i=="string"?hc(i,{dir:e,size:t}):lc(i,{dir:e,size:t})}function hc(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new xo({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function lc(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new xo({size:i.length,targetSize:t,type:"bytes"});const s=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";s[n?r:t-r-1]=i[n?r:i.length-r-1]}return s}class uc extends St{constructor({max:e,min:t,signed:s,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${s?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class pc extends St{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ai(i,{size:e}){if(Nr(i)>e)throw new pc({givenSize:Nr(i),maxSize:e})}function Bs(i,e={}){const{signed:t}=e;e.size&&ai(i,{size:e.size});const s=BigInt(i);if(!t)return s;const r=(i.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return s<=n?s:s-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function dc(i,e={}){return Number(Bs(i,e))}const gc=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function zs(i,e={}){return typeof i=="number"||typeof i=="bigint"?Co(i,e):typeof i=="string"?mc(i,e):typeof i=="boolean"?fc(i,e):Ro(i,e)}function fc(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?(ai(t,{size:e.size}),oi(t,{size:e.size})):t}function Ro(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=gc[i[r]];const s=`0x${t}`;return typeof e.size=="number"?(ai(s,{size:e.size}),oi(s,{dir:"right",size:e.size})):s}function Co(i,e={}){const{signed:t,size:s}=e,r=BigInt(i);let n;s?t?n=(1n<<BigInt(s)*8n-1n)-1n:n=2n**(BigInt(s)*8n)-1n:typeof i=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof i=="bigint"?"n":"";throw new uc({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:s,value:`${i}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(s*8))+BigInt(r):r).toString(16)}`;return s?oi(a,{size:s}):a}const yc=new TextEncoder;function mc(i,e={}){const t=yc.encode(i);return Ro(t,e)}const wc=new TextEncoder;function bc(i,e={}){return typeof i=="number"||typeof i=="bigint"?Ec(i,e):typeof i=="boolean"?vc(i,e):Si(i)?No(i,e):To(i,e)}function vc(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?(ai(t,{size:e.size}),oi(t,{size:e.size})):t}const tt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Tr(i){if(i>=tt.zero&&i<=tt.nine)return i-tt.zero;if(i>=tt.A&&i<=tt.F)return i-(tt.A-10);if(i>=tt.a&&i<=tt.f)return i-(tt.a-10)}function No(i,e={}){let t=i;e.size&&(ai(t,{size:e.size}),t=oi(t,{dir:"right",size:e.size}));let s=t.slice(2);s.length%2&&(s=`0${s}`);const r=s.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=Tr(s.charCodeAt(a++)),h=Tr(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new St(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function Ec(i,e){const t=Co(i,e);return No(t)}function To(i,e={}){const t=wc.encode(i);return typeof e.size=="number"?(ai(t,{size:e.size}),oi(t,{dir:"right",size:e.size})):t}function is(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Ic(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ni(i,...e){if(!Ic(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function _c(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");is(i.outputLen),is(i.blockLen)}function Hs(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function jo(i,e){Ni(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Li=BigInt(2**32-1),jr=BigInt(32);function Pc(i,e=!1){return e?{h:Number(i&Li),l:Number(i>>jr&Li)}:{h:Number(i>>jr&Li)|0,l:Number(i&Li)|0}}function $c(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=Pc(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Sc=(i,e,t)=>i<<t|e>>>32-t,Oc=(i,e,t)=>e<<t|i>>>32-t,Ac=(i,e,t)=>e<<t-32|i>>>64-t,xc=(i,e,t)=>i<<t-32|e>>>64-t,Nt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Rc(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Cc(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Nc(i,e){return i<<32-e|i>>>e}const qr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Tc(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function kr(i){for(let e=0;e<i.length;e++)i[e]=Tc(i[e])}function jc(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function br(i){return typeof i=="string"&&(i=jc(i)),Ni(i),i}function qc(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Ni(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}class qo{clone(){return this._cloneInto()}}function ko(i){const e=s=>i().update(br(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function kc(i=32){if(Nt&&typeof Nt.getRandomValues=="function")return Nt.getRandomValues(new Uint8Array(i));if(Nt&&typeof Nt.randomBytes=="function")return Nt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Do=[],Fo=[],Uo=[],Dc=BigInt(0),di=BigInt(1),Fc=BigInt(2),Uc=BigInt(7),Mc=BigInt(256),Lc=BigInt(113);for(let i=0,e=di,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Do.push(2*(5*s+t)),Fo.push((i+1)*(i+2)/2%64);let r=Dc;for(let n=0;n<7;n++)e=(e<<di^(e>>Uc)*Lc)%Mc,e&Fc&&(r^=di<<(di<<BigInt(n))-di);Uo.push(r)}const[Bc,zc]=$c(Uo,!0),Dr=(i,e,t)=>t>32?Ac(i,e,t):Sc(i,e,t),Fr=(i,e,t)=>t>32?xc(i,e,t):Oc(i,e,t);function Hc(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],p=Dr(h,l,1)^t[a],d=Fr(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=p,i[o+g+1]^=d}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Fo[o],c=Dr(r,n,a),h=Fr(r,n,a),l=Do[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=Bc[s],i[1]^=zc[s]}t.fill(0)}class vr extends qo{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,is(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Rc(this.state)}keccak(){qr||kr(this.state32),Hc(this.state32,this.rounds),qr||kr(this.state32),this.posOut=0,this.pos=0}update(e){Hs(this);const{blockLen:t,state:s}=this;e=br(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)s[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:s,blockLen:r}=this;e[s]^=t,t&128&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Hs(this,!1),Ni(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return is(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(jo(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new vr(t,s,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Vc=(i,e,t)=>ko(()=>new vr(e,i,t)),Mo=Vc(1,136,256/8);function Lo(i,e){const t=e||"hex",s=Mo(Si(i,{strict:!1})?bc(i):i);return t==="bytes"?s:zs(s)}class Kc extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const s=this.keys().next().value;s&&this.delete(s)}return this}}const bs=new Kc(8192);function Gc(i,e){if(bs.has(`${i}.${e}`))return bs.get(`${i}.${e}`);const t=i.substring(2).toLowerCase(),s=Lo(To(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)s[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(s[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return bs.set(`${i}.${e}`,n),n}function Wc(i){const e=Lo(`0x${i.substring(4)}`).substring(26);return Gc(`0x${e}`)}async function Jc({hash:i,signature:e}){const t=Si(i)?i:zs(i),{secp256k1:s}=await Promise.resolve().then(()=>require("./secp256k1-DYWDlveU.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:p,yParity:d}=e,g=Number(d??p),f=Ur(g);return new s.Signature(Bs(h),Bs(l)).addRecoveryBit(f)}const o=Si(e)?e:zs(e),a=dc(`0x${o.slice(130)}`),c=Ur(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Ur(i){if(i===0||i===1)return i;if(i===27)return 0;if(i===28)return 1;throw new Error("Invalid yParityOrV value")}async function Qc({hash:i,signature:e}){return Wc(await Jc({hash:i,signature:e}))}function Yc(i){if(i.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<i.length;h++){const l=i.charAt(h),p=l.charCodeAt(0);if(e[p]!==255)throw new TypeError(l+" is ambiguous");e[p]=h}const t=i.length,s=i.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let l=0,p=0,d=0;const g=h.length;for(;d!==g&&h[d]===0;)d++,l++;const f=(g-d)*n+1>>>0,w=new Uint8Array(f);for(;d!==g;){let m=h[d],v=0;for(let P=f-1;(m!==0||v<p)&&P!==-1;P--,v++)m+=256*w[P]>>>0,w[P]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");p=v,d++}let y=f-p;for(;y!==f&&w[y]===0;)y++;let b=s.repeat(l);for(;y<f;++y)b+=i.charAt(w[y]);return b}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,p=0,d=0;for(;h[l]===s;)p++,l++;const g=(h.length-l)*r+1>>>0,f=new Uint8Array(g);for(;l<h.length;){const m=h.charCodeAt(l);if(m>255)return;let v=e[m];if(v===255)return;let P=0;for(let R=g-1;(v!==0||P<d)&&R!==-1;R--,P++)v+=t*f[R]>>>0,f[R]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");d=P,l++}let w=g-d;for(;w!==g&&f[w]===0;)w++;const y=new Uint8Array(p+(g-w));let b=p;for(;w!==g;)y[b++]=f[w++];return y}function c(h){const l=a(h);if(l)return l;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Zc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Bo=Yc(Zc),Xc=":";function Zt(i){const[e,t]=i.split(Xc);return{namespace:e,reference:t}}function Mr(i,e=[]){const t=[];return Object.keys(i).forEach(s=>{if(e.length&&!e.includes(s))return;const r=i[s];t.push(...r.accounts)}),t}function zo(i,e){return i.includes(":")?[i]:e.chains||[]}var eh=Object.defineProperty,th=Object.defineProperties,ih=Object.getOwnPropertyDescriptors,Lr=Object.getOwnPropertySymbols,sh=Object.prototype.hasOwnProperty,rh=Object.prototype.propertyIsEnumerable,Br=(i,e,t)=>e in i?eh(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,zr=(i,e)=>{for(var t in e||(e={}))sh.call(e,t)&&Br(i,t,e[t]);if(Lr)for(var t of Lr(e))rh.call(e,t)&&Br(i,t,e[t]);return i},nh=(i,e)=>th(i,ih(e));const oh="ReactNative",Ne={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},ah="js";function ss(){return typeof q.dist.process<"u"&&typeof q.dist.process.versions<"u"&&typeof q.dist.process.versions.node<"u"}function ft(){return!u.getDocument_1()&&!!u.getNavigator_1()&&navigator.product===oh}function ch(){return ft()&&typeof q.dist.global<"u"&&typeof(q.dist.global==null?void 0:q.dist.global.Platform)<"u"&&(q.dist.global==null?void 0:q.dist.global.Platform.OS)==="android"}function hh(){return ft()&&typeof q.dist.global<"u"&&typeof(q.dist.global==null?void 0:q.dist.global.Platform)<"u"&&(q.dist.global==null?void 0:q.dist.global.Platform.OS)==="ios"}function ci(){return!ss()&&!!u.getNavigator_1()&&!!u.getDocument_1()}function Ti(){return ft()?Ne.reactNative:ss()?Ne.node:ci()?Ne.browser:Ne.unknown}function Hr(){var i;try{return ft()&&typeof q.dist.global<"u"&&typeof(q.dist.global==null?void 0:q.dist.global.Application)<"u"?(i=q.dist.global.Application)==null?void 0:i.applicationId:void 0}catch{return}}function lh(i,e){const t=new URLSearchParams(i);for(const s of Object.keys(e).sort())if(e.hasOwnProperty(s)){const r=e[s];r!==void 0&&t.set(s,r)}return t.toString()}function uh(i){var e,t;const s=Ho();try{return i!=null&&i.url&&s.url&&new URL(i.url).host!==new URL(s.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${i.url} differs from the actual page url:${s.url}. This is probably unintended and can lead to issues.`),i.url=s.url),(e=i==null?void 0:i.icons)!=null&&e.length&&i.icons.length>0&&(i.icons=i.icons.filter(r=>r!=="")),nh(zr(zr({},s),i),{url:(i==null?void 0:i.url)||s.url,name:(i==null?void 0:i.name)||s.name,description:(i==null?void 0:i.description)||s.description,icons:(t=i==null?void 0:i.icons)!=null&&t.length&&i.icons.length>0?i.icons:s.icons})}catch(r){return console.warn("Error populating app metadata",r),i||s}}function Ho(){return u.getWindowMetadata_1()||{name:"",description:"",url:"",icons:[""]}}function ph(){if(Ti()===Ne.reactNative&&typeof q.dist.global<"u"&&typeof(q.dist.global==null?void 0:q.dist.global.Platform)<"u"){const{OS:t,Version:s}=q.dist.global.Platform;return[t,s].join("-")}const i=u.detect();if(i===null)return"unknown";const e=i.os?i.os.replace(" ","").toLowerCase():"unknown";return i.type==="browser"?[e,i.name,i.version].join("-"):[e,i.version].join("-")}function dh(){var i;const e=Ti();return e===Ne.browser?[e,((i=u.getLocation_1())==null?void 0:i.host)||"unknown"].join(":"):e}function Vo(i,e,t){const s=ph(),r=dh();return[[i,e].join("-"),[ah,t].join("-"),s,r].join("/")}function gh({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Vo(i,e,s),p={auth:r,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=lh(h[1]||"",p);return h[0]+"?"+d}function Pt(i,e){return i.filter(t=>e.includes(t)).length===i.length}function Vs(i){return Object.fromEntries(i.entries())}function Ks(i){return new Map(Object.entries(i))}function bt(i=u.cjs.FIVE_MINUTES,e){const t=u.cjs.toMiliseconds(i||u.cjs.FIVE_MINUTES);let s,r,n,o;return{resolve:a=>{n&&s&&(clearTimeout(n),s(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const h=new Error(e);o=Promise.reject(h),c(h)},t),s=a,r=c})}}function pt(i,e,t){return new Promise(async(s,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await i;s(o)}catch(o){r(o)}clearTimeout(n)})}function Ko(i,e){if(typeof e=="string"&&e.startsWith(`${i}:`))return e;if(i.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(i.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${i}`)}function fh(i){return Ko("topic",i)}function yh(i){return Ko("id",i)}function Go(i){const[e,t]=i.split(":"),s={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")s.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))s.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return s}function ce(i,e){return u.cjs.fromMiliseconds(Date.now()+u.cjs.toMiliseconds(i))}function lt(i){return Date.now()>=u.cjs.toMiliseconds(i)}function J(i,e){return`${i}${e?`:${e}`:""}`}function Qe(i=[],e=[]){return[...new Set([...i,...e])]}async function mh({id:i,topic:e,wcDeepLink:t}){var s;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=wh(n,i,e),a=Ti();if(a===Ne.browser){if(!((s=u.getDocument_1())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}bh(o)}else a===Ne.reactNative&&typeof(q.dist.global==null?void 0:q.dist.global.Linking)<"u"&&await q.dist.global.Linking.openURL(o)}catch(r){console.error(r)}}function wh(i,e,t){const s=`requestId=${e}&sessionTopic=${t}`;i.endsWith("/")&&(i=i.slice(0,-1));let r=`${i}`;if(i.startsWith("https://t.me")){const n=i.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${_h(s,!0)}`}else r=`${r}/wc?${s}`;return r}function bh(i){let e="_self";Ih()?e="_top":(Eh()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function vh(i,e){let t="";try{if(ci()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function Vr(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function Kr(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function Er(){return typeof q.dist.process<"u"&&q.dist.process.env.IS_VITEST==="true"}function Eh(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Ih(){try{return window.self!==window.top}catch{return!1}}function _h(i,e=!1){const t=q.dist.Buffer.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Wo(i){return q.dist.Buffer.from(i,"base64").toString("utf-8")}function Ph(i){return new Promise(e=>setTimeout(e,i))}function Oi(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function $h(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ji(i,...e){if(!$h(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Ir(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Oi(i.outputLen),Oi(i.blockLen)}function Xt(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Jo(i,e){ji(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Bi=BigInt(2**32-1),Gr=BigInt(32);function Sh(i,e=!1){return e?{h:Number(i&Bi),l:Number(i>>Gr&Bi)}:{h:Number(i>>Gr&Bi)|0,l:Number(i&Bi)|0}}function Oh(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=Sh(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Ah=(i,e,t)=>i<<t|e>>>32-t,xh=(i,e,t)=>e<<t|i>>>32-t,Rh=(i,e,t)=>e<<t-32|i>>>64-t,Ch=(i,e,t)=>i<<t-32|e>>>64-t,Tt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Nh(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function vs(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Ve(i,e){return i<<32-e|i>>>e}const Wr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Th(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Jr(i){for(let e=0;e<i.length;e++)i[e]=Th(i[e])}function jh(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function ei(i){return typeof i=="string"&&(i=jh(i)),ji(i),i}function qh(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];ji(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}let _r=class{clone(){return this._cloneInto()}};function Qo(i){const e=s=>i().update(ei(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function hi(i=32){if(Tt&&typeof Tt.getRandomValues=="function")return Tt.getRandomValues(new Uint8Array(i));if(Tt&&typeof Tt.randomBytes=="function")return Tt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Yo=[],Zo=[],Xo=[],kh=BigInt(0),gi=BigInt(1),Dh=BigInt(2),Fh=BigInt(7),Uh=BigInt(256),Mh=BigInt(113);for(let i=0,e=gi,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Yo.push(2*(5*s+t)),Zo.push((i+1)*(i+2)/2%64);let r=kh;for(let n=0;n<7;n++)e=(e<<gi^(e>>Fh)*Mh)%Uh,e&Dh&&(r^=gi<<(gi<<BigInt(n))-gi);Xo.push(r)}const[Lh,Bh]=Oh(Xo,!0),Qr=(i,e,t)=>t>32?Rh(i,e,t):Ah(i,e,t),Yr=(i,e,t)=>t>32?Ch(i,e,t):xh(i,e,t);function zh(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],p=Qr(h,l,1)^t[a],d=Yr(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=p,i[o+g+1]^=d}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Zo[o],c=Qr(r,n,a),h=Yr(r,n,a),l=Yo[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=Lh[s],i[1]^=Bh[s]}t.fill(0)}let Hh=class ea extends _r{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Oi(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Nh(this.state)}keccak(){Wr||Jr(this.state32),zh(this.state32,this.rounds),Wr||Jr(this.state32),this.posOut=0,this.pos=0}update(e){Xt(this);const{blockLen:t,state:s}=this;e=ei(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)s[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:s,blockLen:r}=this;e[s]^=t,t&128&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Xt(this,!1),ji(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Oi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Jo(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new ea(t,s,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Vh=(i,e,t)=>Qo(()=>new Hh(e,i,t)),Kh=Vh(1,136,256/8),Gh="https://rpc.walletconnect.org/v1";function ta(i){const e=`Ethereum Signed Message:
|
|
3
|
+
${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+q.dist.Buffer.from(Kh(t)).toString("hex")}async function Wh(i,e,t,s,r,n){switch(t.t){case"eip191":return await Jh(i,e,t.s);case"eip1271":return await Qh(i,e,t.s,s,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function Jh(i,e,t){return(await Qc({hash:ta(e),signature:t})).toLowerCase()===i.toLowerCase()}async function Qh(i,e,t,s,r,n){const o=Zt(s);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${s}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",h="0000000000000000000000000000000000000000000000000000000000000041",l=t.substring(2),p=ta(e).substring(2),d=a+p+c+h+l,g=await fetch(`${n||Gh}/?chainId=${s}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:Yh(),jsonrpc:"2.0",method:"eth_call",params:[{to:i,data:d},"latest"]})}),{result:f}=await g.json();return f?f.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Yh(){return Date.now()+Math.floor(Math.random()*1e3)}function Zh(i){const e=atob(i),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);const s=t[0];if(s===0)throw new Error("No signatures found");const r=1+s*64;if(t.length<r)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const n=q.dist.Buffer.from(i,"base64").slice(1,65);return Bo.encode(n)}var Xh=Object.defineProperty,el=Object.defineProperties,tl=Object.getOwnPropertyDescriptors,Zr=Object.getOwnPropertySymbols,il=Object.prototype.hasOwnProperty,sl=Object.prototype.propertyIsEnumerable,Xr=(i,e,t)=>e in i?Xh(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,rl=(i,e)=>{for(var t in e||(e={}))il.call(e,t)&&Xr(i,t,e[t]);if(Zr)for(var t of Zr(e))sl.call(e,t)&&Xr(i,t,e[t]);return i},nl=(i,e)=>el(i,tl(e));const ol="did:pkh:",Pr=i=>i==null?void 0:i.split(":"),al=i=>{const e=i&&Pr(i);if(e)return i.includes(ol)?e[3]:e[1]},Gs=i=>{const e=i&&Pr(i);if(e)return e[2]+":"+e[3]},rs=i=>{const e=i&&Pr(i);if(e)return e.pop()};async function en(i){const{cacao:e,projectId:t}=i,{s,p:r}=e,n=ia(r,r.iss),o=rs(r.iss);return await Wh(o,n,s,Gs(r.iss),t)}const ia=(i,e)=>{const t=`${i.domain} wants you to sign in with your Ethereum account:`,s=rs(e);if(!i.aud&&!i.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=i.statement||void 0;const n=`URI: ${i.aud||i.uri}`,o=`Version: ${i.version}`,a=`Chain ID: ${al(e)}`,c=`Nonce: ${i.nonce}`,h=`Issued At: ${i.iat}`,l=i.exp?`Expiration Time: ${i.exp}`:void 0,p=i.nbf?`Not Before: ${i.nbf}`:void 0,d=i.requestId?`Request ID: ${i.requestId}`:void 0,g=i.resources?`Resources:${i.resources.map(w=>`
|
|
4
|
+
- ${w}`).join("")}`:void 0,f=Zi(i.resources);if(f){const w=Ai(f);r=yl(r,w)}return[t,s,"",r,"",n,o,a,c,h,l,p,d,g].filter(w=>w!=null).join(`
|
|
5
|
+
`)};function cl(i){return q.dist.Buffer.from(JSON.stringify(i)).toString("base64")}function hl(i){return JSON.parse(q.dist.Buffer.from(i,"base64").toString("utf-8"))}function Ot(i){if(!i)throw new Error("No recap provided, value is undefined");if(!i.att)throw new Error("No `att` property found");const e=Object.keys(i.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const s=i.att[t];if(Array.isArray(s))throw new Error(`Resource must be an object: ${t}`);if(typeof s!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(s).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(s).forEach(r=>{const n=s[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function ll(i,e,t,s={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[i]:ul(e,t,s)}}}function ul(i,e,t={}){e=e==null?void 0:e.sort((r,n)=>r.localeCompare(n));const s=e.map(r=>({[`${i}/${r}`]:[t]}));return Object.assign({},...s)}function sa(i){return Ot(i),`urn:recap:${cl(i).replace(/=/g,"")}`}function Ai(i){const e=hl(i.replace("urn:recap:",""));return Ot(e),e}function pl(i,e,t){const s=ll(i,e,t);return sa(s)}function dl(i){return i&&i.includes("urn:recap:")}function gl(i,e){const t=Ai(i),s=Ai(e),r=fl(t,s);return sa(r)}function fl(i,e){Ot(i),Ot(e);const t=Object.keys(i.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),s={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=i.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,h;s.att[r]=nl(rl({},s.att[r]),{[a]:((c=i.att[r])==null?void 0:c[a])||((h=e.att[r])==null?void 0:h[a])})})}),s}function yl(i="",e){Ot(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(i.includes(t))return i;const s=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(p=>({ability:p.split("/")[0],action:p.split("/")[1]}));c.sort((p,d)=>p.action.localeCompare(d.action));const h={};c.forEach(p=>{h[p.ability]||(h[p.ability]=[]),h[p.ability].push(p.action)});const l=Object.keys(h).map(p=>(r++,`(${r}) '${p}': '${h[p].join("', '")}' for '${a}'.`));s.push(l.join(", ").replace(".,","."))});const n=s.join(" "),o=`${t}${n}`;return`${i?i+" ":""}${o}`}function tn(i){var e;const t=Ai(i);Ot(t);const s=(e=t.att)==null?void 0:e.eip155;return s?Object.keys(s).map(r=>r.split("/")[1]):[]}function sn(i){const e=Ai(i);Ot(e);const t=[];return Object.values(e.att).forEach(s=>{Object.values(s).forEach(r=>{var n;(n=r==null?void 0:r[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function Zi(i){if(!i)return;const e=i==null?void 0:i[i.length-1];return dl(e)?e:void 0}function Es(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function ra(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ce(i,...e){if(!ra(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function rn(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function ml(i,e){Ce(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function nn(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const dt=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),wl=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),bl=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!bl)throw new Error("Non little-endian hardware is not supported");function vl(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function Ws(i){if(typeof i=="string")i=vl(i);else if(ra(i))i=Js(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function El(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function Il(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}const _l=(i,e)=>{function t(s,...r){if(Ce(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?Ce(h):Ce(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&Ce(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");Ce(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ce(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(Ce(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(h,l)}}}return Object.assign(t,i),t};function on(i,e,t=!0){if(e===void 0)return new Uint8Array(i);if(e.length!==i)throw new Error("invalid output length, expected "+i+", got: "+e.length);if(t&&!Pl(e))throw new Error("invalid output, must be aligned");return e}function an(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);i.setUint32(e+4,o,s),i.setUint32(e+0,a,s)}function Pl(i){return i.byteOffset%4===0}function Js(i){return Uint8Array.from(i)}function ti(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const na=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),$l=na("expand 16-byte k"),Sl=na("expand 32-byte k"),Ol=dt($l),Al=dt(Sl);function V(i,e){return i<<e|i>>>32-e}function Qs(i){return i.byteOffset%4===0}const zi=64,xl=16,oa=2**32-1,cn=new Uint32Array;function Rl(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(zi),l=dt(h),p=Qs(r)&&Qs(n),d=p?dt(r):cn,g=p?dt(n):cn;for(let f=0;f<c;o++){if(i(e,t,s,l,o,a),o>=oa)throw new Error("arx: counter overflow");const w=Math.min(zi,c-f);if(p&&w===zi){const y=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let b=0,m;b<xl;b++)m=y+b,g[m]=d[m]^l[b];f+=zi;continue}for(let y=0,b;y<w;y++)b=f+y,n[b]=r[b]^h[y];f+=w}}function Cl(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=El({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return Es(r),Es(o),nn(n),nn(t),(a,c,h,l,p=0)=>{Ce(a),Ce(c),Ce(h);const d=h.length;if(l===void 0&&(l=new Uint8Array(d)),Ce(l),Es(p),p<0||p>=oa)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const g=[];let f=a.length,w,y;if(f===32)g.push(w=Js(a)),y=Al;else if(f===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),y=Ol,g.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${f}`);Qs(c)||g.push(c=Js(c));const b=dt(w);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(y,b,dt(c.subarray(0,16)),b),c=c.subarray(16)}const m=16-r;if(m!==c.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const P=new Uint8Array(12);P.set(c,n?0:12-c.length),c=P,g.push(c)}const v=dt(c);return Rl(i,y,b,v,h,l,p,o),ti(...g),l}}const fe=(i,e)=>i[e++]&255|(i[e++]&255)<<8;class Nl{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=Ws(e),Ce(e,32);const t=fe(e,0),s=fe(e,2),r=fe(e,4),n=fe(e,6),o=fe(e,8),a=fe(e,10),c=fe(e,12),h=fe(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>10|r<<6)&7939,this.r[3]=(r>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=fe(e,16+2*l)}process(e,t,s=!1){const r=s?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],l=o[3],p=o[4],d=o[5],g=o[6],f=o[7],w=o[8],y=o[9],b=fe(e,t+0),m=fe(e,t+2),v=fe(e,t+4),P=fe(e,t+6),R=fe(e,t+8),$=fe(e,t+10),O=fe(e,t+12),N=fe(e,t+14);let E=n[0]+(b&8191),F=n[1]+((b>>>13|m<<3)&8191),j=n[2]+((m>>>10|v<<6)&8191),D=n[3]+((v>>>7|P<<9)&8191),M=n[4]+((P>>>4|R<<12)&8191),_=n[5]+(R>>>1&8191),x=n[6]+((R>>>14|$<<2)&8191),A=n[7]+(($>>>11|O<<5)&8191),T=n[8]+((O>>>8|N<<8)&8191),k=n[9]+(N>>>5|r),S=0,U=S+E*a+F*(5*y)+j*(5*w)+D*(5*f)+M*(5*g);S=U>>>13,U&=8191,U+=_*(5*d)+x*(5*p)+A*(5*l)+T*(5*h)+k*(5*c),S+=U>>>13,U&=8191;let L=S+E*c+F*a+j*(5*y)+D*(5*w)+M*(5*f);S=L>>>13,L&=8191,L+=_*(5*g)+x*(5*d)+A*(5*p)+T*(5*l)+k*(5*h),S+=L>>>13,L&=8191;let B=S+E*h+F*c+j*a+D*(5*y)+M*(5*w);S=B>>>13,B&=8191,B+=_*(5*f)+x*(5*g)+A*(5*d)+T*(5*p)+k*(5*l),S+=B>>>13,B&=8191;let X=S+E*l+F*h+j*c+D*a+M*(5*y);S=X>>>13,X&=8191,X+=_*(5*w)+x*(5*f)+A*(5*g)+T*(5*d)+k*(5*p),S+=X>>>13,X&=8191;let W=S+E*p+F*l+j*h+D*c+M*a;S=W>>>13,W&=8191,W+=_*(5*y)+x*(5*w)+A*(5*f)+T*(5*g)+k*(5*d),S+=W>>>13,W&=8191;let se=S+E*d+F*p+j*l+D*h+M*c;S=se>>>13,se&=8191,se+=_*a+x*(5*y)+A*(5*w)+T*(5*f)+k*(5*g),S+=se>>>13,se&=8191;let he=S+E*g+F*d+j*p+D*l+M*h;S=he>>>13,he&=8191,he+=_*c+x*a+A*(5*y)+T*(5*w)+k*(5*f),S+=he>>>13,he&=8191;let ve=S+E*f+F*g+j*d+D*p+M*l;S=ve>>>13,ve&=8191,ve+=_*h+x*c+A*a+T*(5*y)+k*(5*w),S+=ve>>>13,ve&=8191;let oe=S+E*w+F*f+j*g+D*d+M*p;S=oe>>>13,oe&=8191,oe+=_*l+x*h+A*c+T*a+k*(5*y),S+=oe>>>13,oe&=8191;let ae=S+E*y+F*w+j*f+D*g+M*d;S=ae>>>13,ae&=8191,ae+=_*p+x*l+A*h+T*c+k*a,S+=ae>>>13,ae&=8191,S=(S<<2)+S|0,S=S+U|0,U=S&8191,S=S>>>13,L+=S,n[0]=U,n[1]=L,n[2]=B,n[3]=X,n[4]=W,n[5]=se,n[6]=he,n[7]=ve,n[8]=oe,n[9]=ae}finalize(){const{h:e,pad:t}=this,s=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,s[0]=e[0]+5,r=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+r,r=s[a]>>>13,s[a]&=8191;s[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)s[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|s[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;ti(s)}update(e){rn(this);const{buffer:t,blockLen:s}=this;e=Ws(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o===s){for(;s<=r-n;n+=s)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){ti(this.h,this.r,this.buffer,this.pad)}digestInto(e){rn(this),ml(e,this),this.finished=!0;const{buffer:t,h:s}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=s[o]>>>0,e[n++]=s[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}}function Tl(i){const e=(s,r)=>i(r).update(Ws(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const jl=Tl(i=>new Nl(i));function ql(i,e,t,s,r,n=20){let o=i[0],a=i[1],c=i[2],h=i[3],l=e[0],p=e[1],d=e[2],g=e[3],f=e[4],w=e[5],y=e[6],b=e[7],m=r,v=t[0],P=t[1],R=t[2],$=o,O=a,N=c,E=h,F=l,j=p,D=d,M=g,_=f,x=w,A=y,T=b,k=m,S=v,U=P,L=R;for(let X=0;X<n;X+=2)$=$+F|0,k=V(k^$,16),_=_+k|0,F=V(F^_,12),$=$+F|0,k=V(k^$,8),_=_+k|0,F=V(F^_,7),O=O+j|0,S=V(S^O,16),x=x+S|0,j=V(j^x,12),O=O+j|0,S=V(S^O,8),x=x+S|0,j=V(j^x,7),N=N+D|0,U=V(U^N,16),A=A+U|0,D=V(D^A,12),N=N+D|0,U=V(U^N,8),A=A+U|0,D=V(D^A,7),E=E+M|0,L=V(L^E,16),T=T+L|0,M=V(M^T,12),E=E+M|0,L=V(L^E,8),T=T+L|0,M=V(M^T,7),$=$+j|0,L=V(L^$,16),A=A+L|0,j=V(j^A,12),$=$+j|0,L=V(L^$,8),A=A+L|0,j=V(j^A,7),O=O+D|0,k=V(k^O,16),T=T+k|0,D=V(D^T,12),O=O+D|0,k=V(k^O,8),T=T+k|0,D=V(D^T,7),N=N+M|0,S=V(S^N,16),_=_+S|0,M=V(M^_,12),N=N+M|0,S=V(S^N,8),_=_+S|0,M=V(M^_,7),E=E+F|0,U=V(U^E,16),x=x+U|0,F=V(F^x,12),E=E+F|0,U=V(U^E,8),x=x+U|0,F=V(F^x,7);let B=0;s[B++]=o+$|0,s[B++]=a+O|0,s[B++]=c+N|0,s[B++]=h+E|0,s[B++]=l+F|0,s[B++]=p+j|0,s[B++]=d+D|0,s[B++]=g+M|0,s[B++]=f+_|0,s[B++]=w+x|0,s[B++]=y+A|0,s[B++]=b+T|0,s[B++]=m+k|0,s[B++]=v+S|0,s[B++]=P+U|0,s[B++]=R+L|0}const kl=Cl(ql,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Dl=new Uint8Array(16),hn=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(Dl.subarray(t))},Fl=new Uint8Array(32);function ln(i,e,t,s,r){const n=i(e,t,Fl),o=jl.create(n);r&&hn(o,r),hn(o,s);const a=new Uint8Array(16),c=wl(a);an(c,0,BigInt(r?r.length:0),!0),an(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return ti(n,a),h}const Ul=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=on(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=ln(i,e,t,a,s);return n.set(c,o),ti(c),n},decrypt(r,n){n=on(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=ln(i,e,t,o,s);if(!Il(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),ti(c),n}}),aa=_l({blockSize:64,nonceLength:12,tagLength:16},Ul(kl));let ca=class extends _r{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ir(e);const s=ei(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(s.length>r?e.create().update(s).digest():s);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return Xt(this),this.iHash.update(e),this}digestInto(e){Xt(this),ji(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:s,finished:r,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const ls=(i,e,t)=>new ca(i,e).update(t).digest();ls.create=(i,e)=>new ca(i,e);function Ml(i,e,t){return Ir(i),t===void 0&&(t=new Uint8Array(i.outputLen)),ls(i,ei(t),ei(e))}const Is=new Uint8Array([0]),un=new Uint8Array;function Ll(i,e,t,s=32){if(Ir(i),Oi(s),s>255*i.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(s/i.outputLen);t===void 0&&(t=un);const n=new Uint8Array(r*i.outputLen),o=ls.create(i,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let h=0;h<r;h++)Is[0]=h+1,a.update(h===0?un:c).update(t).update(Is).digestInto(c),n.set(c,i.outputLen*h),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Is.fill(0),n.slice(0,s)}const Bl=(i,e,t,s,r)=>Ll(i,Ml(i,e,t),s,r);function zl(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=s?4:0,h=s?0:4;i.setUint32(e+c,o,s),i.setUint32(e+h,a,s)}function Hl(i,e,t){return i&e^~i&t}function Vl(i,e,t){return i&e^i&t^e&t}let Kl=class extends _r{constructor(e,t,s,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=vs(this.buffer)}update(e){Xt(this);const{view:t,buffer:s,blockLen:r}=this;e=ei(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=vs(e);for(;r<=n-o;o+=r)this.process(c,o);continue}s.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Xt(this),Jo(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(s,0),o=0);for(let p=o;p<r;p++)t[p]=0;zl(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=vs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<h;p++)a.setUint32(4*p,l[p],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,length:r,finished:n,destroyed:o,pos:a}=this;return e.length=r,e.pos=a,e.finished=n,e.destroyed=o,r%t&&e.buffer.set(s),e}};const Gl=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]),ct=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ht=new Uint32Array(64);class Wl extends Kl{constructor(){super(64,32,8,!1),this.A=ct[0]|0,this.B=ct[1]|0,this.C=ct[2]|0,this.D=ct[3]|0,this.E=ct[4]|0,this.F=ct[5]|0,this.G=ct[6]|0,this.H=ct[7]|0}get(){const{A:e,B:t,C:s,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,s,r,n,o,a,c]}set(e,t,s,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let p=0;p<16;p++,t+=4)ht[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){const d=ht[p-15],g=ht[p-2],f=Ve(d,7)^Ve(d,18)^d>>>3,w=Ve(g,17)^Ve(g,19)^g>>>10;ht[p]=w+ht[p-7]+f+ht[p-16]|0}let{A:s,B:r,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let p=0;p<64;p++){const d=Ve(a,6)^Ve(a,11)^Ve(a,25),g=l+d+Hl(a,c,h)+Gl[p]+ht[p]|0,f=(Ve(s,2)^Ve(s,13)^Ve(s,22))+Vl(s,r,n)|0;l=h,h=c,c=a,a=o+g|0,o=n,n=r,r=s,s=g+f|0}s=s+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(s,r,n,o,a,c,h,l)}roundClean(){ht.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const qi=Qo(()=>new Wl);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const us=BigInt(0),ps=BigInt(1),Jl=BigInt(2);function At(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ki(i){if(!At(i))throw new Error("Uint8Array expected")}function ii(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const Ql=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function si(i){ki(i);let e="";for(let t=0;t<i.length;t++)e+=Ql[i[t]];return e}function Jt(i){const e=i.toString(16);return e.length&1?"0"+e:e}function $r(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?us:BigInt("0x"+i)}const it={_0:48,_9:57,A:65,F:70,a:97,f:102};function pn(i){if(i>=it._0&&i<=it._9)return i-it._0;if(i>=it.A&&i<=it.F)return i-(it.A-10);if(i>=it.a&&i<=it.f)return i-(it.a-10)}function ri(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const s=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=pn(i.charCodeAt(n)),a=pn(i.charCodeAt(n+1));if(o===void 0||a===void 0){const c=i[n]+i[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}s[r]=o*16+a}return s}function $t(i){return $r(si(i))}function xi(i){return ki(i),$r(si(Uint8Array.from(i).reverse()))}function ni(i,e){return ri(i.toString(16).padStart(e*2,"0"))}function ds(i,e){return ni(i,e).reverse()}function Yl(i){return ri(Jt(i))}function Re(i,e,t){let s;if(typeof e=="string")try{s=ri(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(At(e))s=Uint8Array.from(e);else throw new Error(i+" must be hex string or Uint8Array");const r=s.length;if(typeof t=="number"&&r!==t)throw new Error(i+" of length "+t+" expected, got "+r);return s}function Ri(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];ki(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}function Zl(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}function Xl(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const _s=i=>typeof i=="bigint"&&us<=i;function gs(i,e,t){return _s(i)&&_s(e)&&_s(t)&&e<=i&&i<t}function ot(i,e,t,s){if(!gs(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function ha(i){let e;for(e=0;i>us;i>>=ps,e+=1);return e}function eu(i,e){return i>>BigInt(e)&ps}function tu(i,e,t){return i|(t?ps:us)<<BigInt(e)}const Sr=i=>(Jl<<BigInt(i-1))-ps,Ps=i=>new Uint8Array(i),dn=i=>Uint8Array.from(i);function la(i,e,t){if(typeof i!="number"||i<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let s=Ps(i),r=Ps(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=Ps())=>{r=a(dn([0]),l),s=a(),l.length!==0&&(r=a(dn([1]),l),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const p=[];for(;l<e;){s=a();const d=s.slice();p.push(d),l+=s.length}return Ri(...p)};return(l,p)=>{o(),c(l);let d;for(;!(d=p(h()));)c();return o(),d}}const iu={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||At(i),isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function li(i,e,t={}){const s=(r,n,o)=>{const a=iu[n];if(typeof a!="function")throw new Error("invalid validator function");const c=i[r];if(!(o&&c===void 0)&&!a(c,i))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))s(r,n,!1);for(const[r,n]of Object.entries(t))s(r,n,!0);return i}const su=()=>{throw new Error("not implemented")};function Ys(i){const e=new WeakMap;return(t,...s)=>{const r=e.get(t);if(r!==void 0)return r;const n=i(t,...s);return e.set(t,n),n}}var ru=Object.freeze({__proto__:null,isBytes:At,abytes:ki,abool:ii,bytesToHex:si,numberToHexUnpadded:Jt,hexToNumber:$r,hexToBytes:ri,bytesToNumberBE:$t,bytesToNumberLE:xi,numberToBytesBE:ni,numberToBytesLE:ds,numberToVarBytesBE:Yl,ensureBytes:Re,concatBytes:Ri,equalBytes:Zl,utf8ToBytes:Xl,inRange:gs,aInRange:ot,bitLen:ha,bitGet:eu,bitSet:tu,bitMask:Sr,createHmacDrbg:la,validateObject:li,notImplemented:su,memoized:Ys});const ge=BigInt(0),ie=BigInt(1),Et=BigInt(2),nu=BigInt(3),Zs=BigInt(4),gn=BigInt(5),fn=BigInt(8);function Se(i,e){const t=i%e;return t>=ge?t:e+t}function ua(i,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===ie)return ge;let s=ie;for(;e>ge;)e&ie&&(s=s*i%t),i=i*i%t,e>>=ie;return s}function Le(i,e,t){let s=i;for(;e-- >ge;)s*=s,s%=t;return s}function Xs(i,e){if(i===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let t=Se(i,e),s=e,r=ge,n=ie;for(;t!==ge;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==ie)throw new Error("invert: does not exist");return Se(r,e)}function ou(i){const e=(i-ie)/Et;let t,s,r;for(t=i-ie,s=0;t%Et===ge;t/=Et,s++);for(r=Et;r<i&&ua(r,e,i)!==i-ie;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+ie)/Zs;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(t+ie)/Et;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=s,h=o.pow(o.mul(o.ONE,r),t),l=o.pow(a,n),p=o.pow(a,t);for(;!o.eql(p,o.ONE);){if(o.eql(p,o.ZERO))return o.ZERO;let d=1;for(let f=o.sqr(p);d<c&&!o.eql(f,o.ONE);d++)f=o.sqr(f);const g=o.pow(h,ie<<BigInt(c-d-1));h=o.sqr(g),l=o.mul(l,g),p=o.mul(p,h),c=d}return l}}function au(i){if(i%Zs===nu){const e=(i+ie)/Zs;return function(t,s){const r=t.pow(s,e);if(!t.eql(t.sqr(r),s))throw new Error("Cannot find square root");return r}}if(i%fn===gn){const e=(i-gn)/fn;return function(t,s){const r=t.mul(s,Et),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,Et),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),s))throw new Error("Cannot find square root");return c}}return ou(i)}const cu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hu(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=cu.reduce((s,r)=>(s[r]="function",s),e);return li(i,t)}function lu(i,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return i.ONE;if(t===ie)return e;let s=i.ONE,r=e;for(;t>ge;)t&ie&&(s=i.mul(s,r)),r=i.sqr(r),t>>=ie;return s}function uu(i,e){const t=new Array(e.length),s=e.reduce((n,o,a)=>i.is0(o)?n:(t[a]=n,i.mul(n,o)),i.ONE),r=i.inv(s);return e.reduceRight((n,o,a)=>i.is0(o)?n:(t[a]=i.mul(n,t[a]),i.mul(n,o)),r),t}function pa(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function da(i,e,t=!1,s={}){if(i<=ge)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=pa(i,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:i,isLE:t,BITS:r,BYTES:n,MASK:Sr(r),ZERO:ge,ONE:ie,create:c=>Se(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ge<=c&&c<i},is0:c=>c===ge,isOdd:c=>(c&ie)===ie,neg:c=>Se(-c,i),eql:(c,h)=>c===h,sqr:c=>Se(c*c,i),add:(c,h)=>Se(c+h,i),sub:(c,h)=>Se(c-h,i),mul:(c,h)=>Se(c*h,i),pow:(c,h)=>lu(a,c,h),div:(c,h)=>Se(c*Xs(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>Xs(c,i),sqrt:s.sqrt||(c=>(o||(o=au(i)),o(a,c))),invertBatch:c=>uu(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?ds(c,n):ni(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?xi(c):$t(c)}});return Object.freeze(a)}function ga(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function fa(i){const e=ga(i);return e+Math.ceil(e/2)}function pu(i,e,t=!1){const s=i.length,r=ga(e),n=fa(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?xi(i):$t(i),a=Se(o,e-ie)+ie;return t?ds(a,r):ni(a,r)}const yn=BigInt(0),Hi=BigInt(1);function $s(i,e){const t=e.negate();return i?t:e}function ya(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function Ss(i,e){ya(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function du(i,e){if(!Array.isArray(i))throw new Error("array expected");i.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function gu(i,e){if(!Array.isArray(i))throw new Error("array of scalars expected");i.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}const Os=new WeakMap,ma=new WeakMap;function As(i){return ma.get(i)||1}function fu(i,e){return{constTimeNegate:$s,hasPrecomputes(t){return As(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>yn;)s&Hi&&(r=r.add(n)),n=n.double(),s>>=Hi;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=Ss(s,e),o=[];let a=t,c=a;for(let h=0;h<r;h++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,s,r){const{windows:n,windowSize:o}=Ss(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),l=2**t,p=BigInt(t);for(let d=0;d<n;d++){const g=d*o;let f=Number(r&h);r>>=p,f>o&&(f-=l,r+=Hi);const w=g,y=g+Math.abs(f)-1,b=d%2!==0,m=f<0;f===0?c=c.add($s(b,s[w])):a=a.add($s(m,s[y]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=Ss(t,e),c=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let p=0;p<o;p++){const d=p*a;if(r===yn)break;let g=Number(r&c);if(r>>=l,g>a&&(g-=h,r+=Hi),g===0)continue;let f=s[d+Math.abs(g)-1];g<0&&(f=f.negate()),n=n.add(f)}return n},getPrecomputes(t,s,r){let n=Os.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&Os.set(s,r(n))),n},wNAFCached(t,s,r){const n=As(t);return this.wNAF(n,this.getPrecomputes(n,t,r),s)},wNAFCachedUnsafe(t,s,r,n){const o=As(t);return o===1?this.unsafeLadder(t,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,r),s,n)},setWindowSize(t,s){ya(s,e),ma.set(t,s),Os.delete(t)}}}function yu(i,e,t,s){if(du(t,i),gu(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=ha(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r),h=Math.floor((e.BITS-1)/o)*o;let l=r;for(let p=h;p>=0;p-=o){c.fill(r);for(let g=0;g<s.length;g++){const f=s[g],w=Number(f>>BigInt(p)&BigInt(a));c[w]=c[w].add(t[g])}let d=r;for(let g=c.length-1,f=r;g>0;g--)f=f.add(c[g]),d=d.add(f);if(l=l.add(d),p!==0)for(let g=0;g<o;g++)l=l.double()}return l}function wa(i){return hu(i.Fp),li(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...pa(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const jt=BigInt(0),xs=BigInt(1);function mu(i){return li(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function wu(i){const e=mu(i),{P:t}=e,s=m=>Se(m,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),c=e.powPminus2||(m=>ua(m,t-BigInt(2),t));function h(m,v,P){const R=s(m*(v-P));return v=s(v-R),P=s(P+R),[v,P]}const l=(e.a-BigInt(2))/BigInt(4);function p(m,v){ot("u",m,jt,t),ot("scalar",v,jt,t);const P=v,R=m;let $=xs,O=jt,N=m,E=xs,F=jt,j;for(let M=BigInt(r-1);M>=jt;M--){const _=P>>M&xs;F^=_,j=h(F,$,N),$=j[0],N=j[1],j=h(F,O,E),O=j[0],E=j[1],F=_;const x=$+O,A=s(x*x),T=$-O,k=s(T*T),S=A-k,U=N+E,L=N-E,B=s(L*x),X=s(U*T),W=B+X,se=B-X;N=s(W*W),E=s(R*s(se*se)),$=s(A*k),O=s(S*(A+s(l*S)))}j=h(F,$,N),$=j[0],N=j[1],j=h(F,O,E),O=j[0],E=j[1];const D=c(O);return s($*D)}function d(m){return ds(s(m),n)}function g(m){const v=Re("u coordinate",m,n);return o===32&&(v[31]&=127),xi(v)}function f(m){const v=Re("scalar",m),P=v.length;if(P!==n&&P!==o){let R=""+n+" or "+o;throw new Error("invalid scalar, expected "+R+" bytes, got "+P)}return xi(a(v))}function w(m,v){const P=g(v),R=f(m),$=p(P,R);if($===jt)throw new Error("invalid private or public key received");return d($)}const y=d(e.Gu);function b(m){return w(m,y)}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(m,v)=>w(m,v),getPublicKey:m=>b(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:y}}const er=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const bu=BigInt(1),mn=BigInt(2),vu=BigInt(3),Eu=BigInt(5);BigInt(8);function Iu(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=er,o=i*i%n*i%n,a=Le(o,mn,n)*o%n,c=Le(a,bu,n)*i%n,h=Le(c,Eu,n)*c%n,l=Le(h,e,n)*h%n,p=Le(l,t,n)*l%n,d=Le(p,s,n)*p%n,g=Le(d,r,n)*d%n,f=Le(g,r,n)*d%n,w=Le(f,e,n)*h%n;return{pow_p_5_8:Le(w,mn,n)*i%n,b2:o}}function _u(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}const tr=wu({P:er,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=er,{pow_p_5_8:t,b2:s}=Iu(i);return Se(Le(t,vu,e)*s,e)},adjustScalarBytes:_u,randomBytes:hi});function wn(i){i.lowS!==void 0&&ii("lowS",i.lowS),i.prehash!==void 0&&ii("prehash",i.prehash)}function Pu(i){const e=wa(i);li(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:s,a:r}=e;if(t){if(!s.eql(r,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:$u,hexToBytes:Su}=ru;class Ou extends Error{constructor(e=""){super(e)}}const rt={Err:Ou,_tlv:{encode:(i,e)=>{const{Err:t}=rt;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const s=e.length/2,r=Jt(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?Jt(r.length/2|128):"";return Jt(i)+n+r+e},decode(i,e){const{Err:t}=rt;let s=0;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==i)throw new t("tlv.decode: wrong tlv");const r=e[s++],n=!!(r&128);let o=0;if(!n)o=r;else{const c=r&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const h=e.subarray(s,s+c);if(h.length!==c)throw new t("tlv.decode: length bytes not complete");if(h[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const l of h)o=o<<8|l;if(s+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(s,s+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(i){const{Err:e}=rt;if(i<nt)throw new e("integer: negative integers are not allowed");let t=Jt(i);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(i){const{Err:e}=rt;if(i[0]&128)throw new e("invalid signature integer: negative");if(i[0]===0&&!(i[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return $u(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=rt,r=typeof i=="string"?Su(i):i;ki(r);const{v:n,l:o}=s.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l}=s.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(h)}},hexFromSig(i){const{_tlv:e,_int:t}=rt,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},nt=BigInt(0),pe=BigInt(1);BigInt(2);const bn=BigInt(3);BigInt(4);function Au(i){const e=Pu(i),{Fp:t}=e,s=da(e.n,e.nBitLength),r=e.toBytes||((w,y,b)=>{const m=y.toAffine();return Ri(Uint8Array.from([4]),t.toBytes(m.x),t.toBytes(m.y))}),n=e.fromBytes||(w=>{const y=w.subarray(1),b=t.fromBytes(y.subarray(0,t.BYTES)),m=t.fromBytes(y.subarray(t.BYTES,2*t.BYTES));return{x:b,y:m}});function o(w){const{a:y,b}=e,m=t.sqr(w),v=t.mul(m,w);return t.add(t.add(v,t.mul(w,y)),b)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(w){return gs(w,pe,e.n)}function c(w){const{allowedPrivateKeyLengths:y,nByteLength:b,wrapPrivateKey:m,n:v}=e;if(y&&typeof w!="bigint"){if(At(w)&&(w=si(w)),typeof w!="string"||!y.includes(w.length))throw new Error("invalid private key");w=w.padStart(b*2,"0")}let P;try{P=typeof w=="bigint"?w:$t(Re("private key",w,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof w)}return m&&(P=Se(P,v)),ot("private key",P,pe,v),P}function h(w){if(!(w instanceof d))throw new Error("ProjectivePoint expected")}const l=Ys((w,y)=>{const{px:b,py:m,pz:v}=w;if(t.eql(v,t.ONE))return{x:b,y:m};const P=w.is0();y==null&&(y=P?t.ONE:t.inv(v));const R=t.mul(b,y),$=t.mul(m,y),O=t.mul(v,y);if(P)return{x:t.ZERO,y:t.ZERO};if(!t.eql(O,t.ONE))throw new Error("invZ was invalid");return{x:R,y:$}}),p=Ys(w=>{if(w.is0()){if(e.allowInfinityPoint&&!t.is0(w.py))return;throw new Error("bad point: ZERO")}const{x:y,y:b}=w.toAffine();if(!t.isValid(y)||!t.isValid(b))throw new Error("bad point: x or y not FE");const m=t.sqr(b),v=o(y);if(!t.eql(m,v))throw new Error("bad point: equation left != right");if(!w.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(y,b,m){if(this.px=y,this.py=b,this.pz=m,y==null||!t.isValid(y))throw new Error("x required");if(b==null||!t.isValid(b))throw new Error("y required");if(m==null||!t.isValid(m))throw new Error("z required");Object.freeze(this)}static fromAffine(y){const{x:b,y:m}=y||{};if(!y||!t.isValid(b)||!t.isValid(m))throw new Error("invalid affine point");if(y instanceof d)throw new Error("projective point not allowed");const v=P=>t.eql(P,t.ZERO);return v(b)&&v(m)?d.ZERO:new d(b,m,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){const b=t.invertBatch(y.map(m=>m.pz));return y.map((m,v)=>m.toAffine(b[v])).map(d.fromAffine)}static fromHex(y){const b=d.fromAffine(n(Re("pointHex",y)));return b.assertValidity(),b}static fromPrivateKey(y){return d.BASE.multiply(c(y))}static msm(y,b){return yu(d,s,y,b)}_setWindowSize(y){f.setWindowSize(this,y)}assertValidity(){p(this)}hasEvenY(){const{y}=this.toAffine();if(t.isOdd)return!t.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){h(y);const{px:b,py:m,pz:v}=this,{px:P,py:R,pz:$}=y,O=t.eql(t.mul(b,$),t.mul(P,v)),N=t.eql(t.mul(m,$),t.mul(R,v));return O&&N}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){const{a:y,b}=e,m=t.mul(b,bn),{px:v,py:P,pz:R}=this;let $=t.ZERO,O=t.ZERO,N=t.ZERO,E=t.mul(v,v),F=t.mul(P,P),j=t.mul(R,R),D=t.mul(v,P);return D=t.add(D,D),N=t.mul(v,R),N=t.add(N,N),$=t.mul(y,N),O=t.mul(m,j),O=t.add($,O),$=t.sub(F,O),O=t.add(F,O),O=t.mul($,O),$=t.mul(D,$),N=t.mul(m,N),j=t.mul(y,j),D=t.sub(E,j),D=t.mul(y,D),D=t.add(D,N),N=t.add(E,E),E=t.add(N,E),E=t.add(E,j),E=t.mul(E,D),O=t.add(O,E),j=t.mul(P,R),j=t.add(j,j),E=t.mul(j,D),$=t.sub($,E),N=t.mul(j,F),N=t.add(N,N),N=t.add(N,N),new d($,O,N)}add(y){h(y);const{px:b,py:m,pz:v}=this,{px:P,py:R,pz:$}=y;let O=t.ZERO,N=t.ZERO,E=t.ZERO;const F=e.a,j=t.mul(e.b,bn);let D=t.mul(b,P),M=t.mul(m,R),_=t.mul(v,$),x=t.add(b,m),A=t.add(P,R);x=t.mul(x,A),A=t.add(D,M),x=t.sub(x,A),A=t.add(b,v);let T=t.add(P,$);return A=t.mul(A,T),T=t.add(D,_),A=t.sub(A,T),T=t.add(m,v),O=t.add(R,$),T=t.mul(T,O),O=t.add(M,_),T=t.sub(T,O),E=t.mul(F,A),O=t.mul(j,_),E=t.add(O,E),O=t.sub(M,E),E=t.add(M,E),N=t.mul(O,E),M=t.add(D,D),M=t.add(M,D),_=t.mul(F,_),A=t.mul(j,A),M=t.add(M,_),_=t.sub(D,_),_=t.mul(F,_),A=t.add(A,_),D=t.mul(M,A),N=t.add(N,D),D=t.mul(T,A),O=t.mul(x,O),O=t.sub(O,D),D=t.mul(x,M),E=t.mul(T,E),E=t.add(E,D),new d(O,N,E)}subtract(y){return this.add(y.negate())}is0(){return this.equals(d.ZERO)}wNAF(y){return f.wNAFCached(this,y,d.normalizeZ)}multiplyUnsafe(y){const{endo:b,n:m}=e;ot("scalar",y,nt,m);const v=d.ZERO;if(y===nt)return v;if(this.is0()||y===pe)return this;if(!b||f.hasPrecomputes(this))return f.wNAFCachedUnsafe(this,y,d.normalizeZ);let{k1neg:P,k1:R,k2neg:$,k2:O}=b.splitScalar(y),N=v,E=v,F=this;for(;R>nt||O>nt;)R&pe&&(N=N.add(F)),O&pe&&(E=E.add(F)),F=F.double(),R>>=pe,O>>=pe;return P&&(N=N.negate()),$&&(E=E.negate()),E=new d(t.mul(E.px,b.beta),E.py,E.pz),N.add(E)}multiply(y){const{endo:b,n:m}=e;ot("scalar",y,pe,m);let v,P;if(b){const{k1neg:R,k1:$,k2neg:O,k2:N}=b.splitScalar(y);let{p:E,f:F}=this.wNAF($),{p:j,f:D}=this.wNAF(N);E=f.constTimeNegate(R,E),j=f.constTimeNegate(O,j),j=new d(t.mul(j.px,b.beta),j.py,j.pz),v=E.add(j),P=F.add(D)}else{const{p:R,f:$}=this.wNAF(y);v=R,P=$}return d.normalizeZ([v,P])[0]}multiplyAndAddUnsafe(y,b,m){const v=d.BASE,P=($,O)=>O===nt||O===pe||!$.equals(v)?$.multiplyUnsafe(O):$.multiply(O),R=P(this,b).add(P(y,m));return R.is0()?void 0:R}toAffine(y){return l(this,y)}isTorsionFree(){const{h:y,isTorsionFree:b}=e;if(y===pe)return!0;if(b)return b(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:y,clearCofactor:b}=e;return y===pe?this:b?b(d,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return ii("isCompressed",y),this.assertValidity(),r(d,this,y)}toHex(y=!0){return ii("isCompressed",y),si(this.toRawBytes(y))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);const g=e.nBitLength,f=fu(d,e.endo?Math.ceil(g/2):g);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function xu(i){const e=wa(i);return li(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Ru(i){const e=xu(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(_){return Se(_,s)}function a(_){return Xs(_,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:p}=Au({...e,toBytes(_,x,A){const T=x.toAffine(),k=t.toBytes(T.x),S=Ri;return ii("isCompressed",A),A?S(Uint8Array.from([x.hasEvenY()?2:3]),k):S(Uint8Array.from([4]),k,t.toBytes(T.y))},fromBytes(_){const x=_.length,A=_[0],T=_.subarray(1);if(x===r&&(A===2||A===3)){const k=$t(T);if(!gs(k,pe,t.ORDER))throw new Error("Point is not on curve");const S=l(k);let U;try{U=t.sqrt(S)}catch(B){const X=B instanceof Error?": "+B.message:"";throw new Error("Point is not on curve"+X)}const L=(U&pe)===pe;return(A&1)===1!==L&&(U=t.neg(U)),{x:k,y:U}}else if(x===n&&A===4){const k=t.fromBytes(T.subarray(0,t.BYTES)),S=t.fromBytes(T.subarray(t.BYTES,2*t.BYTES));return{x:k,y:S}}else{const k=r,S=n;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+S+", got "+x)}}}),d=_=>si(ni(_,e.nByteLength));function g(_){const x=s>>pe;return _>x}function f(_){return g(_)?o(-_):_}const w=(_,x,A)=>$t(_.slice(x,A));class y{constructor(x,A,T){this.r=x,this.s=A,this.recovery=T,this.assertValidity()}static fromCompact(x){const A=e.nByteLength;return x=Re("compactSignature",x,A*2),new y(w(x,0,A),w(x,A,2*A))}static fromDER(x){const{r:A,s:T}=rt.toSig(Re("DER",x));return new y(A,T)}assertValidity(){ot("r",this.r,pe,s),ot("s",this.s,pe,s)}addRecoveryBit(x){return new y(this.r,this.s,x)}recoverPublicKey(x){const{r:A,s:T,recovery:k}=this,S=$(Re("msgHash",x));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");const U=k===2||k===3?A+e.n:A;if(U>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=k&1?"03":"02",B=c.fromHex(L+d(U)),X=a(U),W=o(-S*X),se=o(T*X),he=c.BASE.multiplyAndAddUnsafe(B,W,se);if(!he)throw new Error("point at infinify");return he.assertValidity(),he}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return ri(this.toDERHex())}toDERHex(){return rt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ri(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const b={isValidPrivateKey(_){try{return h(_),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const _=fa(e.n);return pu(e.randomBytes(_),e.n)},precompute(_=8,x=c.BASE){return x._setWindowSize(_),x.multiply(BigInt(3)),x}};function m(_,x=!0){return c.fromPrivateKey(_).toRawBytes(x)}function v(_){const x=At(_),A=typeof _=="string",T=(x||A)&&_.length;return x?T===r||T===n:A?T===2*r||T===2*n:_ instanceof c}function P(_,x,A=!0){if(v(_))throw new Error("first arg must be private key");if(!v(x))throw new Error("second arg must be public key");return c.fromHex(x).multiply(h(_)).toRawBytes(A)}const R=e.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");const x=$t(_),A=_.length*8-e.nBitLength;return A>0?x>>BigInt(A):x},$=e.bits2int_modN||function(_){return o(R(_))},O=Sr(e.nBitLength);function N(_){return ot("num < 2^"+e.nBitLength,_,nt,O),ni(_,e.nByteLength)}function E(_,x,A=F){if(["recovered","canonical"].some(oe=>oe in A))throw new Error("sign() legacy options not supported");const{hash:T,randomBytes:k}=e;let{lowS:S,prehash:U,extraEntropy:L}=A;S==null&&(S=!0),_=Re("msgHash",_),wn(A),U&&(_=Re("prehashed msgHash",T(_)));const B=$(_),X=h(x),W=[N(X),N(B)];if(L!=null&&L!==!1){const oe=L===!0?k(t.BYTES):L;W.push(Re("extraEntropy",oe))}const se=Ri(...W),he=B;function ve(oe){const ae=R(oe);if(!p(ae))return;const yt=a(ae),Ze=c.BASE.multiply(ae).toAffine(),He=o(Ze.x);if(He===nt)return;const Xe=o(yt*o(he+He*X));if(Xe===nt)return;let et=(Ze.x===He?0:2)|Number(Ze.y&pe),Mi=Xe;return S&&g(Xe)&&(Mi=f(Xe),et^=1),new y(He,Mi,et)}return{seed:se,k2sig:ve}}const F={lowS:e.lowS,prehash:!1},j={lowS:e.lowS,prehash:!1};function D(_,x,A=F){const{seed:T,k2sig:k}=E(_,x,A),S=e;return la(S.hash.outputLen,S.nByteLength,S.hmac)(T,k)}c.BASE._setWindowSize(8);function M(_,x,A,T=j){var Xe;const k=_;x=Re("msgHash",x),A=Re("publicKey",A);const{lowS:S,prehash:U,format:L}=T;if(wn(T),"strict"in T)throw new Error("options.strict was renamed to lowS");if(L!==void 0&&L!=="compact"&&L!=="der")throw new Error("format must be compact or der");const B=typeof k=="string"||At(k),X=!B&&!L&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!B&&!X)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let W,se;try{if(X&&(W=new y(k.r,k.s)),B){try{L!=="compact"&&(W=y.fromDER(k))}catch(et){if(!(et instanceof rt.Err))throw et}!W&&L!=="der"&&(W=y.fromCompact(k))}se=c.fromHex(A)}catch{return!1}if(!W||S&&W.hasHighS())return!1;U&&(x=e.hash(x));const{r:he,s:ve}=W,oe=$(x),ae=a(ve),yt=o(oe*ae),Ze=o(he*ae),He=(Xe=c.BASE.multiplyAndAddUnsafe(se,yt,Ze))==null?void 0:Xe.toAffine();return He?o(He.x)===he:!1}return{CURVE:e,getPublicKey:m,getSharedSecret:P,sign:D,verify:M,ProjectivePoint:c,Signature:y,utils:b}}function Cu(i){return{hash:i,hmac:(e,...t)=>ls(i,e,qh(...t)),randomBytes:hi}}function Nu(i,e){const t=s=>Ru({...i,...Cu(s)});return{...t(e),create:t}}const ba=da(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Tu=ba.create(BigInt("-3")),ju=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),qu=Nu({a:Tu,b:ju,Fp:ba,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},qi),va="base10",_e="base16",Be="base64pad",ut="base64url",Di="utf8",Ea=0,at=1,Fi=2,ku=0,vn=1,_i=12,Or=32;function Du(){const i=tr.utils.randomPrivateKey(),e=tr.getPublicKey(i);return{privateKey:u.toString(i,_e),publicKey:u.toString(e,_e)}}function ir(){const i=hi(Or);return u.toString(i,_e)}function Fu(i,e){const t=tr.getSharedSecret(u.fromString(i,_e),u.fromString(e,_e)),s=Bl(qi,t,void 0,void 0,Or);return u.toString(s,_e)}function Xi(i){const e=qi(u.fromString(i,_e));return u.toString(e,_e)}function Je(i){const e=qi(u.fromString(i,Di));return u.toString(e,_e)}function Ia(i){return u.fromString(`${i}`,va)}function xt(i){return Number(u.toString(i,va))}function _a(i){return i.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Pa(i){const e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Uu(i){const e=Ia(typeof i.type<"u"?i.type:Ea);if(xt(e)===at&&typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof i.senderPublicKey<"u"?u.fromString(i.senderPublicKey,_e):void 0,s=typeof i.iv<"u"?u.fromString(i.iv,_e):hi(_i),r=u.fromString(i.symKey,_e),n=aa(r,s).encrypt(u.fromString(i.message,Di)),o=$a({type:e,sealed:n,iv:s,senderPublicKey:t});return i.encoding===ut?_a(o):o}function Mu(i){const e=u.fromString(i.symKey,_e),{sealed:t,iv:s}=Ci({encoded:i.encoded,encoding:i.encoding}),r=aa(e,s).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return u.toString(r,Di)}function Lu(i,e){const t=Ia(Fi),s=hi(_i),r=u.fromString(i,Di),n=$a({type:t,sealed:r,iv:s});return e===ut?_a(n):n}function Bu(i,e){const{sealed:t}=Ci({encoded:i,encoding:e});return u.toString(t,Di)}function $a(i){if(xt(i.type)===Fi)return u.toString(u.concat([i.type,i.sealed]),Be);if(xt(i.type)===at){if(typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return u.toString(u.concat([i.type,i.senderPublicKey,i.iv,i.sealed]),Be)}return u.toString(u.concat([i.type,i.iv,i.sealed]),Be)}function Ci(i){const e=(i.encoding||Be)===ut?Pa(i.encoded):i.encoded,t=u.fromString(e,Be),s=t.slice(ku,vn),r=vn;if(xt(s)===at){const c=r+Or,h=c+_i,l=t.slice(r,c),p=t.slice(c,h),d=t.slice(h);return{type:s,sealed:d,iv:p,senderPublicKey:l}}if(xt(s)===Fi){const c=t.slice(r),h=hi(_i);return{type:s,sealed:c,iv:h}}const n=r+_i,o=t.slice(r,n),a=t.slice(n);return{type:s,sealed:a,iv:o}}function zu(i,e){const t=Ci({encoded:i,encoding:e==null?void 0:e.encoding});return Sa({type:xt(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?u.toString(t.senderPublicKey,_e):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Sa(i){const e=(i==null?void 0:i.type)||Ea;if(e===at){if(typeof(i==null?void 0:i.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(i==null?void 0:i.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:i==null?void 0:i.senderPublicKey,receiverPublicKey:i==null?void 0:i.receiverPublicKey}}function En(i){return i.type===at&&typeof i.senderPublicKey=="string"&&typeof i.receiverPublicKey=="string"}function In(i){return i.type===Fi}function Hu(i){const e=q.dist.Buffer.from(i.x,"base64"),t=q.dist.Buffer.from(i.y,"base64");return u.concat([new Uint8Array([4]),e,t])}function Vu(i,e){const[t,s,r]=i.split("."),n=q.dist.Buffer.from(Pa(r),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${t}.${s}`,h=qi(c),l=Hu(e);if(!qu.verify(u.concat([o,a]),h,l))throw new Error("Invalid signature");return u.sn(i).payload}const Ku="irn";function ns(i){return(i==null?void 0:i.relay)||{protocol:Ku}}function Ei(i){const e=u.C[i];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${i}`);return e}function Gu(i,e="-"){const t={},s="relay"+e;return Object.keys(i).forEach(r=>{if(r.startsWith(s)){const n=r.replace(s,""),o=i[r];t[n]=o}}),t}function _n(i){if(!i.includes("wc:")){const h=Wo(i);h!=null&&h.includes("wc:")&&(i=h)}i=i.includes("wc://")?i.replace("wc://",""):i,i=i.includes("wc:")?i.replace("wc:",""):i;const e=i.indexOf(":"),t=i.indexOf("?")!==-1?i.indexOf("?"):void 0,s=i.substring(0,e),r=i.substring(e+1,t).split("@"),n=typeof t<"u"?i.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((h,l)=>{a[l]=h});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:s,topic:Wu(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:Gu(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Wu(i){return i.startsWith("//")?i.substring(2):i}function Ju(i,e="-"){const t="relay",s={};return Object.keys(i).forEach(r=>{const n=r,o=t+e+n;i[n]&&(s[o]=i[n])}),s}function Pn(i){const e=new URLSearchParams,t=Ju(i.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",i.symKey),i.expiryTimestamp&&e.set("expiryTimestamp",i.expiryTimestamp.toString()),i.methods&&e.set("methods",i.methods.join(","));const s=e.toString();return`${i.protocol}:${i.topic}@${i.version}?${s}`}function Vi(i,e,t){return`${i}?wc_ev=${t}&topic=${e}`}var Qu=Object.defineProperty,Yu=Object.defineProperties,Zu=Object.getOwnPropertyDescriptors,$n=Object.getOwnPropertySymbols,Xu=Object.prototype.hasOwnProperty,ep=Object.prototype.propertyIsEnumerable,Sn=(i,e,t)=>e in i?Qu(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,tp=(i,e)=>{for(var t in e||(e={}))Xu.call(e,t)&&Sn(i,t,e[t]);if($n)for(var t of $n(e))ep.call(e,t)&&Sn(i,t,e[t]);return i},ip=(i,e)=>Yu(i,Zu(e));function ui(i){const e=[];return i.forEach(t=>{const[s,r]=t.split(":");e.push(`${s}:${r}`)}),e}function sp(i){const e=[];return Object.values(i).forEach(t=>{e.push(...ui(t.accounts))}),e}function rp(i,e){const t=[];return Object.values(i).forEach(s=>{ui(s.accounts).includes(e)&&t.push(...s.methods)}),t}function np(i,e){const t=[];return Object.values(i).forEach(s=>{ui(s.accounts).includes(e)&&t.push(...s.events)}),t}function fs(i){return i.includes(":")}function Qt(i){return fs(i)?i.split(":")[0]:i}function On(i){var e,t,s;const r={};if(!gt(i))return r;for(const[n,o]of Object.entries(i)){const a=fs(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],l=Qt(n);r[l]=ip(tp({},r[l]),{chains:Qe(a,(e=r[l])==null?void 0:e.chains),methods:Qe(c,(t=r[l])==null?void 0:t.methods),events:Qe(h,(s=r[l])==null?void 0:s.events)})}return r}function op(i){const e={};return i==null||i.forEach(t=>{var s;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(s=e[r].chains)==null||s.push(`${r}:${n}`)}),e}function An(i,e){e=e.map(s=>s.replace("did:pkh:",""));const t=op(e);for(const[s,r]of Object.entries(t))r.methods?r.methods=Qe(r.methods,i):r.methods=i,r.events=["chainChanged","accountsChanged"];return t}function ap(i,e){var t,s,r,n,o,a;const c=On(i),h=On(e),l={},p=Object.keys(c).concat(Object.keys(h));for(const d of p)l[d]={chains:Qe((t=c[d])==null?void 0:t.chains,(s=h[d])==null?void 0:s.chains),methods:Qe((r=c[d])==null?void 0:r.methods,(n=h[d])==null?void 0:n.methods),events:Qe((o=c[d])==null?void 0:o.events,(a=h[d])==null?void 0:a.events)};return l}const cp={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}},hp={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function C(i,e){const{message:t,code:s}=hp[i];return{message:e?`${t} ${e}`:t,code:s}}function Q(i,e){const{message:t,code:s}=cp[i];return{message:e?`${t} ${e}`:t,code:s}}function ze(i,e){return!!Array.isArray(i)}function gt(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}function we(i){return typeof i>"u"}function ne(i,e){return e&&we(i)?!0:typeof i=="string"&&!!i.trim().length}function Ar(i,e){return e&&we(i)?!0:typeof i=="number"&&!isNaN(i)}function lp(i,e){const{requiredNamespaces:t}=e,s=Object.keys(i.namespaces),r=Object.keys(t);let n=!0;return Pt(r,s)?(s.forEach(o=>{const{accounts:a,methods:c,events:h}=i.namespaces[o],l=ui(a),p=t[o];(!Pt(zo(o,p),l)||!Pt(p.methods,c)||!Pt(p.events,h))&&(n=!1)}),n):!1}function os(i){return ne(i,!1)&&i.includes(":")?i.split(":").length===2:!1}function up(i){if(ne(i,!1)&&i.includes(":")){const e=i.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&os(t)}}return!1}function pp(i){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(ne(i,!1)){if(e(i))return!0;const t=Wo(i);return e(t)}}catch{}return!1}function dp(i){var e;return(e=i==null?void 0:i.proposer)==null?void 0:e.publicKey}function gp(i){return i==null?void 0:i.topic}function fp(i,e){let t=null;return ne(i==null?void 0:i.publicKey,!1)||(t=C("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function xn(i){let e=!0;return ze(i)?i.length&&(e=i.every(t=>ne(t,!1))):e=!1,e}function yp(i,e,t){let s=null;return ze(e)&&e.length?e.forEach(r=>{s||os(r)||(s=Q("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):os(i)||(s=Q("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),s}function mp(i,e,t){let s=null;return Object.entries(i).forEach(([r,n])=>{if(s)return;const o=yp(r,zo(r,n),`${e} ${t}`);o&&(s=o)}),s}function wp(i,e){let t=null;return ze(i)?i.forEach(s=>{t||up(s)||(t=Q("UNSUPPORTED_ACCOUNTS",`${e}, account ${s} should be a string and conform to "namespace:chainId:address" format`))}):t=Q("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function bp(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=wp(s==null?void 0:s.accounts,`${e} namespace`);r&&(t=r)}),t}function vp(i,e){let t=null;return xn(i==null?void 0:i.methods)?xn(i==null?void 0:i.events)||(t=Q("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Q("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function Oa(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=vp(s,`${e}, namespace`);r&&(t=r)}),t}function Ep(i,e,t){let s=null;if(i&>(i)){const r=Oa(i,e);r&&(s=r);const n=mp(i,e,t);n&&(s=n)}else s=C("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return s}function Rs(i,e){let t=null;if(i&>(i)){const s=Oa(i,e);s&&(t=s);const r=bp(i,e);r&&(t=r)}else t=C("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Aa(i){return ne(i.protocol,!0)}function Ip(i,e){let t=!1;return i?i&&ze(i)&&i.length&&i.forEach(s=>{t=Aa(s)}):t=!0,t}function _p(i){return typeof i=="number"}function $e(i){return typeof i<"u"&&typeof i!==null}function Pp(i){return!(!i||typeof i!="object"||!i.code||!Ar(i.code,!1)||!i.message||!ne(i.message,!1))}function $p(i){return!(we(i)||!ne(i.method,!1))}function Sp(i){return!(we(i)||we(i.result)&&we(i.error)||!Ar(i.id,!1)||!ne(i.jsonrpc,!1))}function Op(i){return!(we(i)||!ne(i.name,!1))}function Rn(i,e){return!(!os(e)||!sp(i).includes(e))}function Ap(i,e,t){return ne(t,!1)?rp(i,e).includes(t):!1}function xp(i,e,t){return ne(t,!1)?np(i,e).includes(t):!1}function Cn(i,e,t){let s=null;const r=Rp(i),n=Cp(e),o=Object.keys(r),a=Object.keys(n),c=Nn(Object.keys(i)),h=Nn(Object.keys(e)),l=c.filter(p=>!h.includes(p));return l.length&&(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
|
|
6
|
+
Required: ${l.toString()}
|
|
7
|
+
Received: ${Object.keys(e).toString()}`)),Pt(o,a)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces.
|
|
8
|
+
Required: ${o.toString()}
|
|
9
|
+
Approved: ${a.toString()}`)),Object.keys(e).forEach(p=>{if(!p.includes(":")||s)return;const d=ui(e[p].accounts);d.includes(p)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${p}
|
|
10
|
+
Required: ${p}
|
|
11
|
+
Approved: ${d.toString()}`))}),o.forEach(p=>{s||(Pt(r[p].methods,n[p].methods)?Pt(r[p].events,n[p].events)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${p}`)):s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${p}`))}),s}function Rp(i){const e={};return Object.keys(i).forEach(t=>{var s;t.includes(":")?e[t]=i[t]:(s=i[t].chains)==null||s.forEach(r=>{e[r]={methods:i[t].methods,events:i[t].events}})}),e}function Nn(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Cp(i){const e={};return Object.keys(i).forEach(t=>{if(t.includes(":"))e[t]=i[t];else{const s=ui(i[t].accounts);s==null||s.forEach(r=>{e[r]={accounts:i[t].accounts.filter(n=>n.includes(`${r}:`)),methods:i[t].methods,events:i[t].events}})}}),e}function Np(i,e){return Ar(i,!1)&&i<=e.max&&i>=e.min}function Tn(){const i=Ti();return new Promise(e=>{switch(i){case Ne.browser:e(Tp());break;case Ne.reactNative:e(jp());break;case Ne.node:e(qp());break;default:e(!0)}})}function Tp(){return ci()&&(navigator==null?void 0:navigator.onLine)}async function jp(){if(ft()&&typeof q.dist.global<"u"&&q.dist.global!=null&&q.dist.global.NetInfo){const i=await(q.dist.global==null?void 0:q.dist.global.NetInfo.fetch());return i==null?void 0:i.isConnected}return!0}function qp(){return!0}function kp(i){switch(Ti()){case Ne.browser:Dp(i);break;case Ne.reactNative:Fp(i);break}}function Dp(i){!ft()&&ci()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function Fp(i){var e;ft()&&typeof q.dist.global<"u"&&q.dist.global!=null&&q.dist.global.NetInfo&&((e=q.dist.global)==null||e.NetInfo.addEventListener(t=>i(t==null?void 0:t.isConnected)))}function Up(){var i;return ci()&&u.getDocument_1()?((i=u.getDocument_1())==null?void 0:i.visibilityState)==="visible":!0}const Cs={};class fi{static get(e){return Cs[e]}static set(e,t){Cs[e]=t}static delete(e){delete Cs[e]}}var Mp=Object.defineProperty,Lp=(i,e,t)=>e in i?Mp(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,jn=(i,e,t)=>Lp(i,typeof e!="symbol"?e+"":e,t);let Bp=class extends u.IEvents{constructor(e){super(),this.opts=e,jn(this,"protocol","wc"),jn(this,"version",2)}};var zp=Object.defineProperty,Hp=(i,e,t)=>e in i?zp(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Vp=(i,e,t)=>Hp(i,e+"",t);let Kp=class extends u.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,Vp(this,"records",new Map)}},Gp=class{constructor(e,t){this.logger=e,this.core=t}};class Wp extends u.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}let Jp=class extends u.IEvents{constructor(e){super()}},Qp=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},Yp=class extends u.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},Zp=class extends u.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},Xp=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},ed=class{constructor(e,t){this.projectId=e,this.logger=t}},td=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var id=Object.defineProperty,sd=(i,e,t)=>e in i?id(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qn=(i,e,t)=>sd(i,typeof e!="symbol"?e+"":e,t);let rd=class{constructor(e){this.opts=e,qn(this,"protocol","wc"),qn(this,"version",2)}},nd=class{constructor(e){this.client=e}};const xa="wc",Ra=2,sr="core",Ye=`${xa}@2:${sr}:`,od={logger:"error"},ad={database:":memory:"},cd="crypto",kn="client_ed25519_seed",hd=u.cjs.ONE_DAY,ld="keychain",ud="0.3",pd="messages",dd="0.3",Dn=u.cjs.SIX_HOURS,gd="publisher",Ca="irn",fd="error",Na="wss://relay.walletconnect.org",yd="relayer",de={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},md="_subscription",je={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},wd=.1,rr="2.21.1",te={link_mode:"link_mode",relay:"relay"},es={inbound:"inbound",outbound:"outbound"},bd="0.3",vd="WALLETCONNECT_CLIENT_ID",Fn="WALLETCONNECT_LINK_MODE_APPS",xe={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Ed="subscription",Id="0.3",_d="pairing",Pd="0.3",yi={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}}},It={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Fe={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},$d="history",Sd="0.3",Od="expirer",ke={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Ad="0.3",xd="verify-api",Rd="https://verify.walletconnect.com",Ta="https://verify.walletconnect.org",Pi=Ta,Cd=`${Pi}/v3`,Nd=[Rd,Ta],Td="echo",jd="https://echo.walletconnect.com",We={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"},st={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Ue={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},mt={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"},wt={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"},mi={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"},qd=.1,kd="event-client",Dd=86400,Fd="https://pulse.walletconnect.org/batch";function Ud(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var r=0;r<i.length;r++){var n=i.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=i.length,c=i.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function p(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var w=0,y=0,b=0,m=f.length;b!==m&&f[b]===0;)b++,w++;for(var v=(m-b)*l+1>>>0,P=new Uint8Array(v);b!==m;){for(var R=f[b],$=0,O=v-1;(R!==0||$<y)&&O!==-1;O--,$++)R+=256*P[O]>>>0,P[O]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");y=$,b++}for(var N=v-y;N!==v&&P[N]===0;)N++;for(var E=c.repeat(w);N<v;++N)E+=i.charAt(P[N]);return E}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var w=0;if(f[w]!==" "){for(var y=0,b=0;f[w]===c;)y++,w++;for(var m=(f.length-w)*h+1>>>0,v=new Uint8Array(m);f[w];){var P=t[f.charCodeAt(w)];if(P===255)return;for(var R=0,$=m-1;(P!==0||R<b)&&$!==-1;$--,R++)P+=a*v[$]>>>0,v[$]=P%256>>>0,P=P/256>>>0;if(P!==0)throw new Error("Non-zero carry");b=R,w++}if(f[w]!==" "){for(var O=m-b;O!==m&&v[O]===0;)O++;for(var N=new Uint8Array(y+(m-O)),E=y;O!==m;)N[E++]=v[O++];return N}}}function g(f){var w=d(f);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:d,decode:g}}var Md=Ud,Ld=Md;const ja=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},Bd=i=>new TextEncoder().encode(i),zd=i=>new TextDecoder().decode(i);class Hd{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Vd{constructor(e,t,s){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=s}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return qa(this,e)}}class Kd{constructor(e){this.decoders=e}or(e){return qa(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const qa=(i,e)=>new Kd({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Gd{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Hd(e,t,s),this.decoder=new Vd(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ys=({name:i,prefix:e,encode:t,decode:s})=>new Gd(i,e,t,s),Ui=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=Ld(t,e);return ys({prefix:i,name:e,encode:s,decode:n=>ja(r(n))})},Wd=(i,e,t,s)=>{const r={};for(let l=0;l<e.length;++l)r[e[l]]=l;let n=i.length;for(;i[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const p=r[i[l]];if(p===void 0)throw new SyntaxError(`Non-${s} character`);c=c<<t|p,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Jd=(i,e,t)=>{const s=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),s)for(;n.length*t&7;)n+="=";return n},be=({name:i,prefix:e,bitsPerChar:t,alphabet:s})=>ys({prefix:e,name:i,encode(r){return Jd(r,s,t)},decode(r){return Wd(r,s,t,i)}}),Qd=ys({prefix:"\0",name:"identity",encode:i=>zd(i),decode:i=>Bd(i)});var Yd=Object.freeze({__proto__:null,identity:Qd});const Zd=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Xd=Object.freeze({__proto__:null,base2:Zd});const eg=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var tg=Object.freeze({__proto__:null,base8:eg});const ig=Ui({prefix:"9",name:"base10",alphabet:"0123456789"});var sg=Object.freeze({__proto__:null,base10:ig});const rg=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ng=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var og=Object.freeze({__proto__:null,base16:rg,base16upper:ng});const ag=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),cg=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hg=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lg=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ug=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pg=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dg=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gg=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fg=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var yg=Object.freeze({__proto__:null,base32:ag,base32upper:cg,base32pad:hg,base32padupper:lg,base32hex:ug,base32hexupper:pg,base32hexpad:dg,base32hexpadupper:gg,base32z:fg});const mg=Ui({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wg=Ui({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var bg=Object.freeze({__proto__:null,base36:mg,base36upper:wg});const vg=Ui({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Eg=Ui({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ig=Object.freeze({__proto__:null,base58btc:vg,base58flickr:Eg});const _g=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Pg=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$g=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Sg=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Og=Object.freeze({__proto__:null,base64:_g,base64pad:Pg,base64url:$g,base64urlpad:Sg});const ka=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Ag=ka.reduce((i,e,t)=>(i[t]=e,i),[]),xg=ka.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function Rg(i){return i.reduce((e,t)=>(e+=Ag[t],e),"")}function Cg(i){const e=[];for(const t of i){const s=xg[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const Ng=ys({prefix:"🚀",name:"base256emoji",encode:Rg,decode:Cg});var Tg=Object.freeze({__proto__:null,base256emoji:Ng}),jg=Da,Un=128,qg=-128,kg=Math.pow(2,31);function Da(i,e,t){e=e||[],t=t||0;for(var s=t;i>=kg;)e[t++]=i&255|Un,i/=128;for(;i&qg;)e[t++]=i&255|Un,i>>>=7;return e[t]=i|0,Da.bytes=t-s+1,e}var Dg=nr,Fg=128,Mn=127;function nr(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw nr.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&Mn)<<r:(o&Mn)*Math.pow(2,r),r+=7}while(o>=Fg);return nr.bytes=n-s,t}var Ug=Math.pow(2,7),Mg=Math.pow(2,14),Lg=Math.pow(2,21),Bg=Math.pow(2,28),zg=Math.pow(2,35),Hg=Math.pow(2,42),Vg=Math.pow(2,49),Kg=Math.pow(2,56),Gg=Math.pow(2,63),Wg=function(i){return i<Ug?1:i<Mg?2:i<Lg?3:i<Bg?4:i<zg?5:i<Hg?6:i<Vg?7:i<Kg?8:i<Gg?9:10},Jg={encode:jg,decode:Dg,encodingLength:Wg},Fa=Jg;const Ln=(i,e,t=0)=>(Fa.encode(i,e,t),e),Bn=i=>Fa.encodingLength(i),or=(i,e)=>{const t=e.byteLength,s=Bn(i),r=s+Bn(t),n=new Uint8Array(r+t);return Ln(i,n,0),Ln(t,n,s),n.set(e,r),new Qg(i,t,e,n)};class Qg{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}}const Ua=({name:i,code:e,encode:t})=>new Yg(i,e,t);class Yg{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?or(this.code,t):t.then(s=>or(this.code,s))}else throw Error("Unknown type, must be binary type")}}const Ma=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Zg=Ua({name:"sha2-256",code:18,encode:Ma("SHA-256")}),Xg=Ua({name:"sha2-512",code:19,encode:Ma("SHA-512")});var ef=Object.freeze({__proto__:null,sha256:Zg,sha512:Xg});const La=0,tf="identity",Ba=ja,sf=i=>or(La,Ba(i)),rf={code:La,name:tf,encode:Ba,digest:sf};var nf=Object.freeze({__proto__:null,identity:rf});new TextEncoder,new TextDecoder;const zn={...Yd,...Xd,...tg,...sg,...og,...yg,...bg,...Ig,...Og,...Tg};({...ef,...nf});function of(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function za(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Hn=za("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Ns=za("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=of(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),af={utf8:Hn,"utf-8":Hn,hex:zn.base16,latin1:Ns,ascii:Ns,binary:Ns,...zn};function cf(i,e="utf8"){const t=af[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(i,"utf8"):t.decoder.decode(`${t.prefix}${i}`)}var hf=Object.defineProperty,lf=(i,e,t)=>e in i?hf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ke=(i,e,t)=>lf(i,typeof e!="symbol"?e+"":e,t);class uf{constructor(e,t){this.core=e,this.logger=t,Ke(this,"keychain",new Map),Ke(this,"name",ld),Ke(this,"version",ud),Ke(this,"initialized",!1),Ke(this,"storagePrefix",Ye),Ke(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),Ke(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),Ke(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),Ke(this,"get",s=>{this.isInitialized();const r=this.keychain.get(s);if(typeof r>"u"){const{message:n}=C("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(n)}return r}),Ke(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Vs(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ks(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var pf=Object.defineProperty,df=(i,e,t)=>e in i?pf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ye=(i,e,t)=>df(i,typeof e!="symbol"?e+"":e,t);class gf{constructor(e,t,s){this.core=e,this.logger=t,ye(this,"name",cd),ye(this,"keychain"),ye(this,"randomSessionIdentifier",ir()),ye(this,"initialized",!1),ye(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),ye(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),ye(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=u.Po(r);return u.Qe(n.publicKey)}),ye(this,"generateKeyPair",()=>{this.isInitialized();const r=Du();return this.setPrivateKey(r.publicKey,r.privateKey)}),ye(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=u.Po(n),a=this.randomSessionIdentifier,c=hd;return await u.Qo(a,r,c,o)}),ye(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Fu(a,n);return this.setSymKey(c,o)}),ye(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||Xi(r);return await this.keychain.set(o,r),o}),ye(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),ye(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),ye(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Sa(o),c=u.safeJsonStringify(n);if(In(a))return Lu(c,o==null?void 0:o.encoding);if(En(a)){const d=a.senderPublicKey,g=a.receiverPublicKey;r=await this.generateSharedKey(d,g)}const h=this.getSymKey(r),{type:l,senderPublicKey:p}=a;return Uu({type:l,symKey:h,message:c,senderPublicKey:p,encoding:o==null?void 0:o.encoding})}),ye(this,"decode",async(r,n,o)=>{this.isInitialized();const a=zu(n,o);if(In(a)){const c=Bu(n,o==null?void 0:o.encoding);return u.safeJsonParse(c)}if(En(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=Mu({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return u.safeJsonParse(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),ye(this,"getPayloadType",(r,n=Be)=>{const o=Ci({encoded:r,encoding:n});return xt(o.type)}),ye(this,"getPayloadSenderPublicKey",(r,n=Be)=>{const o=Ci({encoded:r,encoding:n});return o.senderPublicKey?u.toString(o.senderPublicKey,_e):void 0}),this.core=e,this.logger=u.E(t,this.name),this.keychain=s||new uf(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(kn)}catch{e=ir(),await this.keychain.set(kn,e)}return cf(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ff=Object.defineProperty,yf=Object.defineProperties,mf=Object.getOwnPropertyDescriptors,Vn=Object.getOwnPropertySymbols,wf=Object.prototype.hasOwnProperty,bf=Object.prototype.propertyIsEnumerable,ar=(i,e,t)=>e in i?ff(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vf=(i,e)=>{for(var t in e||(e={}))wf.call(e,t)&&ar(i,t,e[t]);if(Vn)for(var t of Vn(e))bf.call(e,t)&&ar(i,t,e[t]);return i},Ef=(i,e)=>yf(i,mf(e)),Oe=(i,e,t)=>ar(i,typeof e!="symbol"?e+"":e,t);class If extends Gp{constructor(e,t){super(e,t),this.logger=e,this.core=t,Oe(this,"messages",new Map),Oe(this,"messagesWithoutClientAck",new Map),Oe(this,"name",pd),Oe(this,"version",dd),Oe(this,"initialized",!1),Oe(this,"storagePrefix",Ye),Oe(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const s=await this.getRelayerMessages();typeof s<"u"&&(this.messages=s);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(s){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(s)}finally{this.initialized=!0}}}),Oe(this,"set",async(s,r,n)=>{this.isInitialized();const o=Je(r);let a=this.messages.get(s);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(s,a),n===es.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,Ef(vf({},c),{[o]:r}))}return await this.persist(),o}),Oe(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),Oe(this,"getWithoutAck",s=>{this.isInitialized();const r={};for(const n of s){const o=this.messagesWithoutClientAck.get(n)||{};r[n]=Object.values(o)}return r}),Oe(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=Je(r);return typeof n[o]<"u"}),Oe(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=Je(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),Oe(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=u.E(e,this.name),this.core=t}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Vs(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Vs(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ks(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Ks(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _f=Object.defineProperty,Pf=Object.defineProperties,$f=Object.getOwnPropertyDescriptors,Kn=Object.getOwnPropertySymbols,Sf=Object.prototype.hasOwnProperty,Of=Object.prototype.propertyIsEnumerable,cr=(i,e,t)=>e in i?_f(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ki=(i,e)=>{for(var t in e||(e={}))Sf.call(e,t)&&cr(i,t,e[t]);if(Kn)for(var t of Kn(e))Of.call(e,t)&&cr(i,t,e[t]);return i},Ts=(i,e)=>Pf(i,$f(e)),Me=(i,e,t)=>cr(i,typeof e!="symbol"?e+"":e,t);class Af extends Wp{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Me(this,"events",new u.eventsExports.EventEmitter),Me(this,"name",gd),Me(this,"queue",new Map),Me(this,"publishTimeout",u.cjs.toMiliseconds(u.cjs.ONE_MINUTE)),Me(this,"initialPublishTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),Me(this,"needsTransportRestart",!1),Me(this,"publish",async(s,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:s,message:r,opts:n}});const a=(n==null?void 0:n.ttl)||Dn,c=ns(n),h=(n==null?void 0:n.prompt)||!1,l=(n==null?void 0:n.tag)||0,p=(n==null?void 0:n.id)||u.getBigIntRpcId().toString(),d={topic:s,message:r,opts:{ttl:a,relay:c,prompt:h,tag:l,id:p,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},g=`Failed to publish payload, please try again. id:${p} tag:${l}`;try{const f=new Promise(async w=>{const y=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(de.publish,y),w(d))};this.relayer.events.on(de.publish,y);const b=pt(new Promise((m,v)=>{this.rpcPublish({topic:s,message:r,ttl:a,prompt:h,tag:l,id:p,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(m).catch(P=>{this.logger.warn(P,P==null?void 0:P.message),v(P)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${l}`);try{await b,this.events.removeListener(de.publish,y)}catch(m){this.queue.set(p,Ts(Ki({},d),{attempt:1})),this.logger.warn(m,m==null?void 0:m.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:s,message:r,opts:n}}),await pt(f,this.publishTimeout,g)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(p)}}),Me(this,"on",(s,r)=>{this.events.on(s,r)}),Me(this,"once",(s,r)=>{this.events.once(s,r)}),Me(this,"off",(s,r)=>{this.events.off(s,r)}),Me(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=u.E(t,this.name),this.registerEventListeners()}get context(){return u.y(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=Dn,prompt:h,tag:l,id:p,attestation:d,tvf:g}=e,f={method:Ei(ns().protocol).publish,params:Ki({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:d},g),id:p};we((t=f.params)==null?void 0:t.prompt)&&((s=f.params)==null||delete s.prompt),we((r=f.params)==null?void 0:r.tag)&&((n=f.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const w=await this.relayer.request(f);return this.relayer.events.emit(de.publish,e),this.logger.debug("Successfully Published Payload"),w}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,Ts(Ki({},e),{attempt:s}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${s}`),await this.rpcPublish(Ts(Ki({},e),{topic:r,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(u.r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(de.connection_stalled);return}this.checkQueue()}),this.relayer.on(de.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var xf=Object.defineProperty,Rf=(i,e,t)=>e in i?xf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qt=(i,e,t)=>Rf(i,typeof e!="symbol"?e+"":e,t);class Cf{constructor(){qt(this,"map",new Map),qt(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),qt(this,"get",e=>this.map.get(e)||[]),qt(this,"exists",(e,t)=>this.get(e).includes(t)),qt(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const r=s.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),qt(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Nf=Object.defineProperty,Tf=Object.defineProperties,jf=Object.getOwnPropertyDescriptors,Gn=Object.getOwnPropertySymbols,qf=Object.prototype.hasOwnProperty,kf=Object.prototype.propertyIsEnumerable,hr=(i,e,t)=>e in i?Nf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,wi=(i,e)=>{for(var t in e||(e={}))qf.call(e,t)&&hr(i,t,e[t]);if(Gn)for(var t of Gn(e))kf.call(e,t)&&hr(i,t,e[t]);return i},js=(i,e)=>Tf(i,jf(e)),Y=(i,e,t)=>hr(i,typeof e!="symbol"?e+"":e,t);class Df extends Yp{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Y(this,"subscriptions",new Map),Y(this,"topicMap",new Cf),Y(this,"events",new u.eventsExports.EventEmitter),Y(this,"name",Ed),Y(this,"version",Id),Y(this,"pending",new Map),Y(this,"cached",[]),Y(this,"initialized",!1),Y(this,"storagePrefix",Ye),Y(this,"subscribeTimeout",u.cjs.toMiliseconds(u.cjs.ONE_MINUTE)),Y(this,"initialSubscribeTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),Y(this,"clientId"),Y(this,"batchSubscribeTopicsLimit",500),Y(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Y(this,"subscribe",async(s,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:s,opts:r}});try{const n=ns(r),o={topic:s,relay:n,transportType:r==null?void 0:r.transportType};this.pending.set(s,o);const a=await this.rpcSubscribe(s,n,r);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:s,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),Y(this,"unsubscribe",async(s,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(s,r.id,r):await this.unsubscribeByTopic(s,r)}),Y(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),Y(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),Y(this,"on",(s,r)=>{this.events.on(s,r)}),Y(this,"once",(s,r)=>{this.events.once(s,r)}),Y(this,"off",(s,r)=>{this.events.off(s,r)}),Y(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),Y(this,"start",async()=>{await this.onConnect()}),Y(this,"stop",async()=>{await this.onDisconnect()}),Y(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Y(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const s=[];this.pending.forEach(r=>{s.push(r)}),await this.batchSubscribe(s)}),Y(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(u.r.pulse,async()=>{await this.checkPending()}),this.events.on(xe.created,async s=>{const r=xe.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(xe.deleted,async s=>{const r=xe.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=u.E(t,this.name),this.clientId=""}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const r=ns(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Q("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,s){var r;(!s||(s==null?void 0:s.transportType)===te.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Ei(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=s==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((s==null?void 0:s.transportType)===te.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},u.cjs.toMiliseconds(u.cjs.ONE_SECOND)),a;const c=new Promise(async l=>{const p=d=>{d.topic===e&&(this.events.removeListener(xe.created,p),l(d.id))};this.events.on(xe.created,p);try{const d=await pt(new Promise((g,f)=>{this.relayer.request(n).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),f(w)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(xe.created,p),l(d)}catch{}}),h=await pt(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(de.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Ei(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await pt(new Promise(r=>{this.relayer.request(s).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Ei(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let r;try{r=await await pt(new Promise((n,o)=>{this.relayer.request(s).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:Ei(s.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,js(wi({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,wi({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,wi({},t)),this.topicMap.set(t.topic,e),this.events.emit(xe.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:s}=C("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(xe.deleted,js(wi({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(xe.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let s=0;s<t;s++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(xe.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=C("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async t=>js(wi({},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 Ph(u.cjs.toMiliseconds(u.cjs.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Je(e+await this.getClientId())}}var Ff=Object.defineProperty,Wn=Object.getOwnPropertySymbols,Uf=Object.prototype.hasOwnProperty,Mf=Object.prototype.propertyIsEnumerable,lr=(i,e,t)=>e in i?Ff(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Jn=(i,e)=>{for(var t in e||(e={}))Uf.call(e,t)&&lr(i,t,e[t]);if(Wn)for(var t of Wn(e))Mf.call(e,t)&&lr(i,t,e[t]);return i},K=(i,e,t)=>lr(i,typeof e!="symbol"?e+"":e,t);class Lf extends Jp{constructor(e){super(e),K(this,"protocol","wc"),K(this,"version",2),K(this,"core"),K(this,"logger"),K(this,"events",new u.eventsExports.EventEmitter),K(this,"provider"),K(this,"messages"),K(this,"subscriber"),K(this,"publisher"),K(this,"name",yd),K(this,"transportExplicitlyClosed",!1),K(this,"initialized",!1),K(this,"connectionAttemptInProgress",!1),K(this,"relayUrl"),K(this,"projectId"),K(this,"packageName"),K(this,"bundleId"),K(this,"hasExperiencedNetworkDisruption",!1),K(this,"pingTimeout"),K(this,"heartBeatTimeout",u.cjs.toMiliseconds(u.cjs.THIRTY_SECONDS+u.cjs.FIVE_SECONDS)),K(this,"reconnectTimeout"),K(this,"connectPromise"),K(this,"reconnectInProgress",!1),K(this,"requestsInFlight",[]),K(this,"connectTimeout",u.cjs.toMiliseconds(u.cjs.ONE_SECOND*15)),K(this,"request",async t=>{var s,r;this.logger.debug("Publishing Request Payload");const n=t.id||u.getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(s=t.params)==null?void 0:s.topic},"relayer.request - publishing...");const o=`${n}:${((r=t.params)==null?void 0:r.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),K(this,"resetPingTimeout",()=>{ss()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,s,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(s=(t=this.provider)==null?void 0:t.connection)==null?void 0:s.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),K(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),K(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(de.connect)}),K(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),K(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(de.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),K(this,"registerProviderListeners",()=>{this.provider.on(je.payload,this.onPayloadHandler),this.provider.on(je.connect,this.onConnectHandler),this.provider.on(je.disconnect,this.onDisconnectHandler),this.provider.on(je.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?u.E(e.logger,this.name):u.Ot(u.k({level:e.logger||fd})),this.messages=new If(this.logger,e.core),this.subscriber=new Df(this,this.logger),this.publisher=new Af(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Na,this.projectId=e.projectId,ch()?this.packageName=Hr():hh()&&(this.bundleId=Hr()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return u.y(this.logger)}get connected(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===1||!1}get connecting(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:te.relay},es.outbound)}async subscribe(e,t){var s,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((s=t==null?void 0:t.internal)==null?void 0:s.throwOnFailedPublish)>"u"?!0:(r=t==null?void 0:t.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const h=l=>{l.topic===e&&(this.subscriber.off(xe.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(xe.created,h)}),new Promise(async(l,p)=>{a=await this.subscriber.subscribe(e,Jn({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&p(d)})||a,l()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await pt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,s)=>{await this.connect(e).then(t).catch(s).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Tn())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((s,r)=>s.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const s of t)try{await this.onMessageEvent(s)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+(r==null?void 0:r.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:s}=e;if(!t.sessionExists){const r=ce(u.cjs.FIVE_MINUTES),n={topic:s,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,n)}this.events.emit(de.message,e),await this.recordMessageEvent(e,es.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(s,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(je.disconnect,n),await pt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off(je.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(je.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(je.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,s()})}catch(s){await this.subscriber.stop();const r=s;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(s=>setTimeout(s,u.cjs.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,s,r,n;if(ss())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(s=this.provider)==null?void 0:s.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new u.o(new u.f(gh({sdkVersion:rr,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:s,message:r}=e;await this.messages.set(s,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||s.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,s);return r&&this.logger.warn(`Ignoring duplicate message: ${s}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),u.isJsonRpcRequest(e)){if(!e.method.endsWith(md))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:te.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Jn({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else u.isJsonRpcResponse(e)&&this.events.emit(de.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,es.inbound),this.events.emit(de.message,e))}async acknowledgePayload(e){const t=u.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(je.payload,this.onPayloadHandler),this.provider.off(je.connect,this.onConnectHandler),this.provider.off(je.disconnect,this.onDisconnectHandler),this.provider.off(je.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Tn();kp(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(s=>this.logger.error(s,s==null?void 0:s.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(u.r.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Up())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t==null?void 0:t.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(de.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},u.cjs.toMiliseconds(wd)))))}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function Bf(){}function Qn(i){if(!i||typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(i)==="[object Object]":!1}function Yn(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Zn(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const zf="[object RegExp]",Hf="[object String]",Vf="[object Number]",Kf="[object Boolean]",Xn="[object Arguments]",Gf="[object Symbol]",Wf="[object Date]",Jf="[object Map]",Qf="[object Set]",Yf="[object Array]",Zf="[object Function]",Xf="[object ArrayBuffer]",qs="[object Object]",ey="[object Error]",ty="[object DataView]",iy="[object Uint8Array]",sy="[object Uint8ClampedArray]",ry="[object Uint16Array]",ny="[object Uint32Array]",oy="[object BigUint64Array]",ay="[object Int8Array]",cy="[object Int16Array]",hy="[object Int32Array]",ly="[object BigInt64Array]",uy="[object Float32Array]",py="[object Float64Array]";function dy(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function gy(i,e,t){return Ii(i,e,void 0,void 0,void 0,void 0,t)}function Ii(i,e,t,s,r,n,o){const a=o(i,e,t,s,r,n);if(a!==void 0)return a;if(typeof i==typeof e)switch(typeof i){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return i===e;case"number":return i===e||Object.is(i,e);case"function":return i===e;case"object":return $i(i,e,n,o)}return $i(i,e,n,o)}function $i(i,e,t,s){if(Object.is(i,e))return!0;let r=Zn(i),n=Zn(e);if(r===Xn&&(r=qs),n===Xn&&(n=qs),r!==n)return!1;switch(r){case Hf:return i.toString()===e.toString();case Vf:{const c=i.valueOf(),h=e.valueOf();return dy(c,h)}case Kf:case Wf:case Gf:return Object.is(i.valueOf(),e.valueOf());case zf:return i.source===e.source&&i.flags===e.flags;case Zf:return i===e}t=t??new Map;const o=t.get(i),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(i,e),t.set(e,i);try{switch(r){case Jf:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!Ii(h,e.get(c),c,i,e,t,s))return!1;return!0}case Qf:{if(i.size!==e.size)return!1;const c=Array.from(i.values()),h=Array.from(e.values());for(let l=0;l<c.length;l++){const p=c[l],d=h.findIndex(g=>Ii(p,g,void 0,i,e,t,s));if(d===-1)return!1;h.splice(d,1)}return!0}case Yf:case iy:case sy:case ry:case ny:case oy:case ay:case cy:case hy:case ly:case uy:case py:{if(typeof q.dist.Buffer<"u"&&q.dist.Buffer.isBuffer(i)!==q.dist.Buffer.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!Ii(i[c],e[c],c,i,e,t,s))return!1;return!0}case Xf:return i.byteLength!==e.byteLength?!1:$i(new Uint8Array(i),new Uint8Array(e),t,s);case ty:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:$i(new Uint8Array(i),new Uint8Array(e),t,s);case ey:return i.name===e.name&&i.message===e.message;case qs:{if(!($i(i.constructor,e.constructor,t,s)||Qn(i)&&Qn(e)))return!1;const c=[...Object.keys(i),...Yn(i)],h=[...Object.keys(e),...Yn(e)];if(c.length!==h.length)return!1;for(let l=0;l<c.length;l++){const p=c[l],d=i[p];if(!Object.hasOwn(e,p))return!1;const g=e[p];if(!Ii(d,g,p,i,e,t,s))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function fy(i,e){return gy(i,e,Bf)}var yy=Object.defineProperty,eo=Object.getOwnPropertySymbols,my=Object.prototype.hasOwnProperty,wy=Object.prototype.propertyIsEnumerable,ur=(i,e,t)=>e in i?yy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,to=(i,e)=>{for(var t in e||(e={}))my.call(e,t)&&ur(i,t,e[t]);if(eo)for(var t of eo(e))wy.call(e,t)&&ur(i,t,e[t]);return i},Pe=(i,e,t)=>ur(i,typeof e!="symbol"?e+"":e,t);class Rt extends Qp{constructor(e,t,s,r=Ye,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,Pe(this,"map",new Map),Pe(this,"version",bd),Pe(this,"cached",[]),Pe(this,"initialized",!1),Pe(this,"getKey"),Pe(this,"storagePrefix",Ye),Pe(this,"recentlyDeleted",[]),Pe(this,"recentlyDeletedLimit",200),Pe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!we(o)?this.map.set(this.getKey(o),o):dp(o)?this.map.set(o.id,o):gp(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Pe(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Pe(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Pe(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>fy(a[c],o[c]))):this.values)),Pe(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=to(to({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Pe(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=u.E(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=C("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:s}=C("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=C("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var by=Object.defineProperty,vy=(i,e,t)=>e in i?by(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,z=(i,e,t)=>vy(i,typeof e!="symbol"?e+"":e,t);class Ey{constructor(e,t){this.core=e,this.logger=t,z(this,"name",_d),z(this,"version",Pd),z(this,"events",new u.Nt),z(this,"pairings"),z(this,"initialized",!1),z(this,"storagePrefix",Ye),z(this,"ignoredPayloadTypes",[at]),z(this,"registeredMethods",[]),z(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),z(this,"register",({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]}),z(this,"create",async s=>{this.isInitialized();const r=ir(),n=await this.core.crypto.setSymKey(r),o=ce(u.cjs.FIVE_MINUTES),a={protocol:Ca},c={topic:n,expiry:o,relay:a,active:!1,methods:s==null?void 0:s.methods},h=Pn({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:s==null?void 0:s.methods});return this.events.emit(It.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:s==null?void 0:s.transportType}),{topic:n,uri:h}}),z(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s==null?void 0:s.uri,trace:[We.pairing_started]}});this.isValidPair(s,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=_n(s.uri);r.props.properties.topic=n,r.addTrace(We.pairing_uri_validation_success),r.addTrace(We.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(We.existing_pairing),l.active)throw r.setError(st.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(We.pairing_not_expired)}const p=c||ce(u.cjs.FIVE_MINUTES),d={topic:n,relay:a,expiry:p,active:!1,methods:h};this.core.expirer.set(n,p),await this.pairings.set(n,d),r.addTrace(We.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(It.create,d),r.addTrace(We.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(We.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(st.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(g){throw r.setError(st.subscribe_pairing_topic_failure),g}return r.addTrace(We.subscribe_pairing_topic_success),d}),z(this,"activate",async({topic:s})=>{this.isInitialized();const r=ce(u.cjs.FIVE_MINUTES);this.core.expirer.set(s,r),await this.pairings.update(s,{active:!0,expiry:r})}),z(this,"ping",async s=>{this.isInitialized(),await this.isValidPing(s),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=s;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=bt();this.events.once(J("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),z(this,"updateExpiry",async({topic:s,expiry:r})=>{this.isInitialized(),await this.pairings.update(s,{expiry:r})}),z(this,"updateMetadata",async({topic:s,metadata:r})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:r})}),z(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),z(this,"disconnect",async s=>{this.isInitialized(),await this.isValidDisconnect(s);const{topic:r}=s;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Q("USER_DISCONNECTED")),await this.deletePairing(r))}),z(this,"formatUriFromPairing",s=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=s,c=this.core.crypto.keychain.get(r);return Pn({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),z(this,"sendRequest",async(s,r,n)=>{const o=u.formatJsonRpcRequest(r,n),a=await this.core.crypto.encode(s,o),c=yi[r].req;return this.core.history.set(s,o),this.core.relayer.publish(s,a,c),o.id}),z(this,"sendResult",async(s,r,n)=>{const o=u.formatJsonRpcResult(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=yi[c].res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),z(this,"sendError",async(s,r,n)=>{const o=u.formatJsonRpcError(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=yi[c]?yi[c].res:yi.unregistered_method.res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),z(this,"deletePairing",async(s,r)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,Q("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),r?Promise.resolve():this.core.expirer.del(s)])}),z(this,"cleanup",async()=>{const s=this.pairings.getAll().filter(r=>lt(r.expiry));await Promise.all(s.map(r=>this.deletePairing(r.topic)))}),z(this,"onRelayEventRequest",async s=>{const{topic:r,payload:n}=s;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,n);default:return await this.onUnknownRpcMethodRequest(r,n)}}),z(this,"onRelayEventResponse",async s=>{const{topic:r,payload:n}=s,o=(await this.core.history.get(r,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,n);default:return this.onUnknownRpcMethodResponse(o)}}),z(this,"onPairingPingRequest",async(s,r)=>{const{id:n}=r;try{this.isValidPing({topic:s}),await this.sendResult(n,s,!0),this.events.emit(It.ping,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),z(this,"onPairingPingResponse",(s,r)=>{const{id:n}=r;setTimeout(()=>{u.isJsonRpcResult(r)?this.events.emit(J("pairing_ping",n),{}):u.isJsonRpcError(r)&&this.events.emit(J("pairing_ping",n),{error:r.error})},500)}),z(this,"onPairingDeleteRequest",async(s,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(It.delete,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),z(this,"onUnknownRpcMethodRequest",async(s,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Q("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,s,a),this.logger.error(a)}catch(a){await this.sendError(n,s,a),this.logger.error(a)}}),z(this,"onUnknownRpcMethodResponse",s=>{this.registeredMethods.includes(s)||this.logger.error(Q("WC_METHOD_UNSUPPORTED",s))}),z(this,"isValidPair",(s,r)=>{var n;if(!$e(s)){const{message:a}=C("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(st.malformed_pairing_uri),new Error(a)}if(!pp(s.uri)){const{message:a}=C("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(st.malformed_pairing_uri),new Error(a)}const o=_n(s==null?void 0:s.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=C("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(st.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=C("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(st.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&u.cjs.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(st.pairing_expired);const{message:a}=C("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),z(this,"isValidPing",async s=>{if(!$e(s)){const{message:n}=C("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),z(this,"isValidDisconnect",async s=>{if(!$e(s)){const{message:n}=C("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),z(this,"isValidPairingTopic",async s=>{if(!ne(s,!1)){const{message:r}=C("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(r)}if(!this.pairings.keys.includes(s)){const{message:r}=C("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(r)}if(lt(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:r}=C("EXPIRED",`pairing topic: ${s}`);throw new Error(r)}}),this.core=e,this.logger=u.E(t,this.name),this.pairings=new Rt(this.core,this.logger,this.name,this.storagePrefix)}get context(){return u.y(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(de.message,async e=>{const{topic:t,message:s,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==te.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);u.isJsonRpcRequest(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):u.isJsonRpcResponse(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,s)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(ke.expired,async e=>{const{topic:t}=Go(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(It.expire,{topic:t}))})}}var Iy=Object.defineProperty,_y=(i,e,t)=>e in i?Iy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,me=(i,e,t)=>_y(i,typeof e!="symbol"?e+"":e,t);class Py extends Kp{constructor(e,t){super(e,t),this.core=e,this.logger=t,me(this,"records",new Map),me(this,"events",new u.eventsExports.EventEmitter),me(this,"name",$d),me(this,"version",Sd),me(this,"cached",[]),me(this,"initialized",!1),me(this,"storagePrefix",Ye),me(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.records.set(s.id,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),me(this,"set",(s,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:s,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:s,request:{method:r.method,params:r.params||null},chainId:n,expiry:ce(u.cjs.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Fe.created,o)}),me(this,"resolve",async s=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:s}),!this.records.has(s.id))return;const r=await this.getRecord(s.id);typeof r.response>"u"&&(r.response=u.isJsonRpcError(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(Fe.updated,r))}),me(this,"get",async(s,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:s,id:r}),await this.getRecord(r))),me(this,"delete",(s,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===s){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(Fe.deleted,n)}}),this.persist()}),me(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),me(this,"on",(s,r)=>{this.events.on(s,r)}),me(this,"once",(s,r)=>{this.events.once(s,r)}),me(this,"off",(s,r)=>{this.events.off(s,r)}),me(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:u.formatJsonRpcRequest(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:s}=C("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Fe.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=C("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Fe.created,e=>{const t=Fe.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Fe.updated,e=>{const t=Fe.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Fe.deleted,e=>{const t=Fe.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(u.r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{u.cjs.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Fe.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $y=Object.defineProperty,Sy=(i,e,t)=>e in i?$y(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ee=(i,e,t)=>Sy(i,typeof e!="symbol"?e+"":e,t);class Oy extends Zp{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ee(this,"expirations",new Map),Ee(this,"events",new u.eventsExports.EventEmitter),Ee(this,"name",Od),Ee(this,"version",Ad),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",Ye),Ee(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.expirations.set(s.target,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ee(this,"has",s=>{try{const r=this.formatTarget(s);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ee(this,"set",(s,r)=>{this.isInitialized();const n=this.formatTarget(s),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(ke.created,{target:n,expiration:o})}),Ee(this,"get",s=>{this.isInitialized();const r=this.formatTarget(s);return this.getExpiration(r)}),Ee(this,"del",s=>{if(this.isInitialized(),this.has(s)){const r=this.formatTarget(s),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(ke.deleted,{target:r,expiration:n})}}),Ee(this,"on",(s,r)=>{this.events.on(s,r)}),Ee(this,"once",(s,r)=>{this.events.once(s,r)}),Ee(this,"off",(s,r)=>{this.events.off(s,r)}),Ee(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=u.E(t,this.name)}get context(){return u.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return fh(e);if(typeof e=="number")return yh(e);const{message:t}=C("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(ke.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=C("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:s}=C("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(s),new Error(s)}return t}checkExpiry(e,t){const{expiry:s}=t;u.cjs.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(ke.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(u.r.pulse,()=>this.checkExpirations()),this.events.on(ke.created,e=>{const t=ke.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(ke.expired,e=>{const t=ke.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(ke.deleted,e=>{const t=ke.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ay=Object.defineProperty,xy=(i,e,t)=>e in i?Ay(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,re=(i,e,t)=>xy(i,typeof e!="symbol"?e+"":e,t);class Ry extends Xp{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,re(this,"name",xd),re(this,"abortController"),re(this,"isDevEnv"),re(this,"verifyUrlV3",Cd),re(this,"storagePrefix",Ye),re(this,"version",Ra),re(this,"publicKey"),re(this,"fetchPromise"),re(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&u.cjs.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),re(this,"register",async r=>{if(!ci()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const h=u.getDocument_1(),l=this.startAbortTimer(u.cjs.ONE_SECOND*5),p=await new Promise((d,g)=>{const f=()=>{window.removeEventListener("message",y),h.body.removeChild(w),g("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const w=h.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",f,{signal:this.abortController.signal});const y=b=>{if(b.data&&typeof b.data=="string")try{const m=JSON.parse(b.data);if(m.type==="verify_attestation"){if(u.sn(m.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(w),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",y),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};h.body.appendChild(w),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",p),p}catch(h){this.logger.warn(h)}return""}),re(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(u.sn(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),re(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(u.cjs.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),re(this,"getVerifyUrl",r=>{let n=r||Pi;return Nd.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Pi}`),n=Pi),n}),re(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(u.cjs.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),re(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),re(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),re(this,"isValidJwtAttestation",async r=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(r,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),re(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),re(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),re(this,"validateAttestation",(r,n)=>{const o=Vu(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=Er(),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 Cy=Object.defineProperty,Ny=(i,e,t)=>e in i?Cy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,io=(i,e,t)=>Ny(i,typeof e!="symbol"?e+"":e,t);class Ty extends ed{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,io(this,"context",Td),io(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${jd}/${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 jy=Object.defineProperty,so=Object.getOwnPropertySymbols,qy=Object.prototype.hasOwnProperty,ky=Object.prototype.propertyIsEnumerable,pr=(i,e,t)=>e in i?jy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bi=(i,e)=>{for(var t in e||(e={}))qy.call(e,t)&&pr(i,t,e[t]);if(so)for(var t of so(e))ky.call(e,t)&&pr(i,t,e[t]);return i},le=(i,e,t)=>pr(i,typeof e!="symbol"?e+"":e,t);class Dy extends td{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,le(this,"context",kd),le(this,"storagePrefix",Ye),le(this,"storageVersion",qd),le(this,"events",new Map),le(this,"shouldPersist",!1),le(this,"init",async()=>{if(!Er())try{const r={eventId:Kr(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Vo(this.core.relayer.protocol,this.core.relayer.version,rr)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),le(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,h=Kr(),l=this.core.projectId||"",p=Date.now(),d=bi({eventId:h,timestamp:p,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(h));return this.telemetryEnabled&&(this.events.set(h,d),this.shouldPersist=!0),d}),le(this,"getEvent",r=>{const{eventId:n,topic:o}=r;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return bi(bi({},a),this.setMethods(a.eventId))}),le(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),le(this,"setEventListeners",()=>{this.core.heartbeat.on(u.r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{u.cjs.fromMiliseconds(Date.now())-u.cjs.fromMiliseconds(r.timestamp)>Dd&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),le(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),le(this,"addTrace",(r,n)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(n),this.events.set(r,o),this.shouldPersist=!0)}),le(this,"setError",(r,n)=>{const o=this.events.get(r);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),le(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),le(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(n=>{this.events.set(n.eventId,bi(bi({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),le(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[n,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const n of r)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),le(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Fd}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${rr}${n}`,{method:"POST",body:JSON.stringify(r)})}),le(this,"getAppDomain",()=>Ho().url),this.logger=u.E(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var Fy=Object.defineProperty,ro=Object.getOwnPropertySymbols,Uy=Object.prototype.hasOwnProperty,My=Object.prototype.propertyIsEnumerable,dr=(i,e,t)=>e in i?Fy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,no=(i,e)=>{for(var t in e||(e={}))Uy.call(e,t)&&dr(i,t,e[t]);if(ro)for(var t of ro(e))My.call(e,t)&&dr(i,t,e[t]);return i},ee=(i,e,t)=>dr(i,typeof e!="symbol"?e+"":e,t);let Ly=class Ha extends Bp{constructor(e){var t;super(e),ee(this,"protocol",xa),ee(this,"version",Ra),ee(this,"name",sr),ee(this,"relayUrl"),ee(this,"projectId"),ee(this,"customStoragePrefix"),ee(this,"events",new u.eventsExports.EventEmitter),ee(this,"logger"),ee(this,"heartbeat"),ee(this,"relayer"),ee(this,"crypto"),ee(this,"storage"),ee(this,"history"),ee(this,"expirer"),ee(this,"pairing"),ee(this,"verify"),ee(this,"echoClient"),ee(this,"linkModeSupportedApps"),ee(this,"eventClient"),ee(this,"initialized",!1),ee(this,"logChunkController"),ee(this,"on",(a,c)=>this.events.on(a,c)),ee(this,"once",(a,c)=>this.events.once(a,c)),ee(this,"off",(a,c)=>this.events.off(a,c)),ee(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ee(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:te.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(s)try{return this.customStoragePrefix=s.customStoragePrefix,this.logger=s.logger,this.heartbeat=s.heartbeat,this.crypto=s.crypto,this.history=s.history,this.expirer=s.expirer,this.storage=s.storage,this.relayer=s.relayer,this.pairing=s.pairing,this.verify=s.verify,this.echoClient=s.echoClient,this.linkModeSupportedApps=s.linkModeSupportedApps,this.eventClient=s.eventClient,this.initialized=s.initialized,this.logChunkController=s.logChunkController,s}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Na,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=u.k({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:od.logger,name:sr}),{logger:n,chunkLoggerController:o}=u.A({opts:r,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=u.E(n,this.name),this.heartbeat=new u.i,this.crypto=new gf(this,this.logger,e==null?void 0:e.keychain),this.history=new Py(this,this.logger),this.expirer=new Oy(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new u.h(no(no({},ad),e==null?void 0:e.storageOptions)),this.relayer=new Lf({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Ey(this,this.logger),this.verify=new Ry(this,this.logger,this.storage),this.echoClient=new Ty(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Dy(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Ha(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(vd,s),t}get context(){return u.y(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Fn,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(Fn)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,s=`${t}_count`;return globalThis[s]=(globalThis[s]||0)+1,globalThis[s]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[s]} times.`),globalThis[t]}catch(t){console.warn("Failed to get global WalletConnect core",t);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${((t=e.opts)==null?void 0:t.customStoragePrefix)||""}`;globalThis[s]=e}catch(s){console.warn("Failed to set global WalletConnect core",s)}}isGlobalCoreDisabled(){try{return typeof q.dist.process<"u"&&q.dist.process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const By=Ly,Va="wc",Ka=2,Ga="client",xr=`${Va}@${Ka}:${Ga}:`,ks={name:Ga,logger:"error"},oo="WALLETCONNECT_DEEPLINK_CHOICE",zy="proposal",ao="Proposal expired",Hy="session",kt=u.cjs.SEVEN_DAYS,Vy="engine",ue={wc_sessionPropose:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1104},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1106},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:u.cjs.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1112},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1114},res:{ttl:u.cjs.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:u.cjs.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:u.cjs.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:u.cjs.FIVE_MINUTES,prompt:!1,tag:1119}}},Ds={min:u.cjs.FIVE_MINUTES,max:u.cjs.SEVEN_DAYS},Ge={idle:"IDLE",active:"ACTIVE"},co={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Ky="request",Gy=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Wy="wc",Jy="auth",Qy="authKeys",Yy="pairingTopics",Zy="requests",ms=`${Wy}@${1.5}:${Jy}:`,ts=`${ms}:PUB_KEY`;var Xy=Object.defineProperty,em=Object.defineProperties,tm=Object.getOwnPropertyDescriptors,ho=Object.getOwnPropertySymbols,im=Object.prototype.hasOwnProperty,sm=Object.prototype.propertyIsEnumerable,gr=(i,e,t)=>e in i?Xy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Z=(i,e)=>{for(var t in e||(e={}))im.call(e,t)&&gr(i,t,e[t]);if(ho)for(var t of ho(e))sm.call(e,t)&&gr(i,t,e[t]);return i},Ie=(i,e)=>em(i,tm(e)),I=(i,e,t)=>gr(i,typeof e!="symbol"?e+"":e,t);class rm extends nd{constructor(e){super(e),I(this,"name",Vy),I(this,"events",new u.Nt),I(this,"initialized",!1),I(this,"requestQueue",{state:Ge.idle,queue:[]}),I(this,"sessionRequestQueue",{state:Ge.idle,queue:[]}),I(this,"requestQueueDelay",u.cjs.ONE_SECOND),I(this,"expectedPairingMethodMap",new Map),I(this,"recentlyDeletedMap",new Map),I(this,"recentlyDeletedLimit",200),I(this,"relayMessageCache",[]),I(this,"pendingSessions",new Map),I(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(ue)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},u.cjs.toMiliseconds(this.requestQueueDelay)))}),I(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=Ie(Z({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=ap(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h}=s;let l=r,p,d=!1;try{if(l){const $=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=$.active}}catch($){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),$}if(!l||!d){const{topic:$,uri:O}=await this.client.core.pairing.create();l=$,p=O}if(!l){const{message:$}=C("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error($)}const g=await this.client.core.crypto.generateKeyPair(),f=ue.wc_sessionPropose.req.ttl||u.cjs.FIVE_MINUTES,w=ce(f),y=Ie(Z(Z({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:Ca}],proposer:{publicKey:g,metadata:this.client.metadata},expiryTimestamp:w,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:u.payloadId()}),b=J("session_connect",y.id),{reject:m,resolve:v,done:P}=bt(f,ao),R=({id:$})=>{$===y.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(y.id),this.events.emit(b,{error:{message:ao,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(b,({error:$,session:O})=>{this.client.events.off("proposal_expire",R),$?m($):O&&v(O)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:y,throwOnFailedPublish:!0,clientRpcId:y.id}),await this.setProposal(y.id,y),{uri:p,approval:P}}),I(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(s){throw this.client.logger.error("pair() failed"),s}}),I(this,"approve",async t=>{var s,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(s=t==null?void 0:t.id)==null?void 0:s.toString(),trace:[Ue.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(E){throw o.setError(mt.no_internet_connection),E}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(E){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(mt.proposal_not_found),E}try{await this.isValidApprove(t)}catch(E){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(mt.session_approve_namespace_validation_failure),E}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:p,sessionConfig:d}=t,g=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:w,requiredNamespaces:y,optionalNamespaces:b}=g;let m=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:f});m||(m=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Ue.session_approve_started,properties:{topic:f,trace:[Ue.session_approve_started,Ue.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),P=w.publicKey,R=await this.client.core.crypto.generateSharedKey(v,P),$=Z(Z(Z({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:v,metadata:this.client.metadata},expiry:ce(kt)},l&&{sessionProperties:l}),p&&{scopedProperties:p}),d&&{sessionConfig:d}),O=te.relay;m.addTrace(Ue.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:O})}catch(E){throw m.setError(mt.subscribe_session_topic_failure),E}m.addTrace(Ue.subscribe_session_topic_success);const N=Ie(Z({},$),{topic:R,requiredNamespaces:y,optionalNamespaces:b,pairingTopic:f,acknowledged:!1,self:$.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:v,transportType:te.relay});await this.client.session.set(R,N),m.addTrace(Ue.store_session);try{m.addTrace(Ue.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:$,throwOnFailedPublish:!0}).catch(E=>{throw m==null||m.setError(mt.session_settle_publish_failure),E}),m.addTrace(Ue.session_settle_publish_success),m.addTrace(Ue.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:v},throwOnFailedPublish:!0}).catch(E=>{throw m==null||m.setError(mt.session_approve_publish_failure),E}),m.addTrace(Ue.session_approve_publish_success)}catch(E){throw this.client.logger.error(E),this.client.session.delete(R,Q("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),E}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:w.metadata}),await this.client.proposal.delete(a,Q("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(R,ce(kt)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}}),I(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:s,reason:r}=t;let n;try{n=this.client.proposal.get(s).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${s}) failed`),o}n&&(await this.sendError({id:s,topic:n,error:r,rpcOpts:ue.wc_sessionPropose.reject}),await this.client.proposal.delete(s,Q("USER_DISCONNECTED")))}),I(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(p){throw this.client.logger.error("update() -> isValidUpdate() failed"),p}const{topic:s,namespaces:r}=t,{done:n,resolve:o,reject:a}=bt(),c=u.payloadId(),h=u.getBigIntRpcId().toString(),l=this.client.session.get(s).namespaces;return this.events.once(J("session_update",c),({error:p})=>{p?a(p):o()}),await this.client.session.update(s,{namespaces:r}),await this.sendRequest({topic:s,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(p=>{this.client.logger.error(p),this.client.session.update(s,{namespaces:l}),a(p)}),{acknowledged:n}}),I(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:s}=t,r=u.payloadId(),{done:n,resolve:o,reject:a}=bt();return this.events.once(J("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,ce(kt)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),I(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:s,request:r,topic:n,expiry:o=ue.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===te.relay&&await this.confirmOnlineStateOrThrow();const c=u.payloadId(),h=u.getBigIntRpcId().toString(),{done:l,resolve:p,reject:d}=bt(o,"Request expired. Please try again.");this.events.once(J("session_request",c),({error:b,result:m})=>{b?d(b):p(m)});const g="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:{request:Ie(Z({},r),{expiryTimestamp:ce(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const w={request:Ie(Z({},r),{expiryTimestamp:ce(o)}),chainId:s},y=this.shouldSetTVF(g,w);return await Promise.all([new Promise(async b=>{await this.sendRequest(Z({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:w,expiry:o,throwOnFailedPublish:!0},y&&{tvf:this.getTVFParams(c,w)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),b()}),new Promise(async b=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const v=await vh(this.client.core.storage,oo);await mh({id:c,topic:n,wcDeepLink:v})}b()}),l()]).then(b=>b[2])}),I(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:s,response:r}=t,{id:n}=r,o=this.client.session.get(s);o.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);u.isJsonRpcResult(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):u.isJsonRpcError(r)&&await this.sendError({id:n,topic:s,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),I(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:s}=t;if(this.client.session.keys.includes(s)){const r=u.payloadId(),n=u.getBigIntRpcId().toString(),{done:o,resolve:a,reject:c}=bt();this.events.once(J("session_ping",r),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:s,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(s)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:s}))}),I(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:s,event:r,chainId:n}=t,o=u.getBigIntRpcId().toString(),a=u.payloadId();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),I(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:s}=t;if(this.client.session.keys.includes(s))await this.sendRequest({topic:s,method:"wc_sessionDelete",params:Q("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:s,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(s))await this.client.core.pairing.disconnect({topic:s});else{const{message:r}=C("MISMATCHED_TOPIC",`Session or pairing topic not found: ${s}`);throw new Error(r)}}),I(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(s=>lp(s,t)))),I(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),I(this,"authenticate",async(t,s)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=s&&this.client.core.linkModeSupportedApps.includes(s)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?te.link_mode:te.relay;o===te.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:p,type:d,exp:g,nbf:f,methods:w=[],expiry:y}=t,b=[...t.resources||[]],{topic:m,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:v}});const P=await this.client.core.crypto.generateKeyPair(),R=Xi(P);if(await Promise.all([this.client.auth.authKeys.set(ts,{responseTopic:R,publicKey:P}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:m})]),await this.client.core.relayer.subscribe(R,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),w.length>0){const{namespace:S}=Zt(a[0]);let U=pl(S,"request",w);Zi(b)&&(U=gl(U,b.pop())),b.push(U)}const $=y&&y>ue.wc_sessionAuthenticate.req.ttl?y:ue.wc_sessionAuthenticate.req.ttl,O={authPayload:{type:d??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:p,iat:new Date().toISOString(),exp:g,nbf:f,resources:b},requester:{publicKey:P,metadata:this.client.metadata},expiryTimestamp:ce($)},N={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},E={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:P,metadata:this.client.metadata},expiryTimestamp:ce(ue.wc_sessionPropose.req.ttl),id:u.payloadId()},{done:F,resolve:j,reject:D}=bt($,"Request expired"),M=u.payloadId(),_=J("session_connect",E.id),x=J("session_request",M),A=async({error:S,session:U})=>{this.events.off(x,T),S?D(S):U&&j({session:U})},T=async S=>{var U,L,B;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),S.error){const ae=Q("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return S.error.code===ae.code?void 0:(this.events.off(_,A),D(S.error.message))}await this.deleteProposal(E.id),this.events.off(_,A);const{cacaos:X,responder:W}=S.result,se=[],he=[];for(const ae of X){await en({cacao:ae,projectId:this.client.core.projectId})||(this.client.logger.error(ae,"Signature verification failed"),D(Q("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:yt}=ae,Ze=Zi(yt.resources),He=[Gs(yt.iss)],Xe=rs(yt.iss);if(Ze){const et=tn(Ze),Mi=sn(Ze);se.push(...et),He.push(...Mi)}for(const et of He)he.push(`${et}:${Xe}`)}const ve=await this.client.core.crypto.generateSharedKey(P,W.publicKey);let oe;se.length>0&&(oe={topic:ve,acknowledged:!0,self:{publicKey:P,metadata:this.client.metadata},peer:W,controller:W.publicKey,expiry:ce(kt),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:An([...new Set(se)],[...new Set(he)]),transportType:o},await this.client.core.relayer.subscribe(ve,{transportType:o}),await this.client.session.set(ve,oe),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:W.metadata}),oe=this.client.session.get(ve)),(U=this.client.metadata.redirect)!=null&&U.linkMode&&(L=W.metadata.redirect)!=null&&L.linkMode&&(B=W.metadata.redirect)!=null&&B.universal&&s&&(this.client.core.addLinkModeSupportedApp(W.metadata.redirect.universal),this.client.session.update(ve,{transportType:te.link_mode})),j({auths:X,session:oe})};this.events.once(_,A),this.events.once(x,T);let k;try{if(n){const S=u.formatJsonRpcRequest("wc_sessionAuthenticate",O,M);this.client.core.history.set(m,S);const U=await this.client.core.crypto.encode("",S,{type:Fi,encoding:ut});k=Vi(s,m,U)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:O,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:M}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:E,expiry:ue.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(S){throw this.events.off(_,A),this.events.off(x,T),S}return await this.setProposal(E.id,E),await this.setAuthRequest(M,{request:Ie(Z({},O),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:k??v,response:F}}),I(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[wt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw n.setError(mi.no_internet_connection),y}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(mi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||te.relay;a===te.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=Xi(c),p={type:at,receiverPublicKey:c,senderPublicKey:h},d=[],g=[];for(const y of r){if(!await en({cacao:y,projectId:this.client.core.projectId})){n.setError(mi.invalid_cacao);const R=Q("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:R,encodeOpts:p}),new Error(R.message)}n.addTrace(wt.cacaos_verified);const{p:b}=y,m=Zi(b.resources),v=[Gs(b.iss)],P=rs(b.iss);if(m){const R=tn(m),$=sn(m);d.push(...R),v.push(...$)}for(const R of v)g.push(`${R}:${P}`)}const f=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(wt.create_authenticated_session_topic);let w;if((d==null?void 0:d.length)>0){w={topic:f,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ce(kt),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:An([...new Set(d)],[...new Set(g)]),transportType:a},n.addTrace(wt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(y){throw n.setError(mi.subscribe_authenticated_session_topic_failure),y}n.addTrace(wt.subscribe_authenticated_session_topic_success),await this.client.session.set(f,w),n.addTrace(wt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(wt.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:s,result:{cacaos:r,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:p,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw n.setError(mi.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(s,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:w}}),I(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:s,reason:r}=t,n=this.getPendingAuthRequest(s);if(!n)throw new Error(`Could not find pending auth request with id ${s}`);n.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Xi(o),h={type:at,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:s,topic:c,error:r,encodeOpts:h,rpcOpts:ue.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(s,{message:"rejected",code:0}),await this.client.proposal.delete(s,Q("USER_DISCONNECTED"))}),I(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return ia(s,r)}),I(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),I(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const s=this.client.core.pairing.pairings.get(t.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===t.peer.metadata.url&&n.topic&&n.topic!==s.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(s){this.client.logger.error(s)}}),I(this,"deleteSession",async t=>{var s;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Q("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(oo).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,Q("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=Ge.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),I(this,"deleteProposal",async(t,s)=>{if(s)try{const r=this.client.proposal.get(t),n=this.client.core.eventClient.getEvent({topic:r.pairingTopic});n==null||n.setError(mt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Q("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),I(this,"deletePendingSessionRequest",async(t,s,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,s),r?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==t),r&&(this.sessionRequestQueue.state=Ge.idle,this.client.events.emit("session_request_expire",{id:t}))}),I(this,"deletePendingAuthRequest",async(t,s,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,s),r?Promise.resolve():this.client.core.expirer.del(t)])}),I(this,"setExpiry",async(t,s)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,s),await this.client.session.update(t,{expiry:s}))}),I(this,"setProposal",async(t,s)=>{this.client.core.expirer.set(t,ce(ue.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),I(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=te.relay}=s;this.client.core.expirer.set(t,r.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:t,pairingTopic:n,verifyContext:r.verifyContext,transportType:o})}),I(this,"setPendingSessionRequest",async t=>{const{id:s,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ce(ue.wc_sessionRequest.req.ttl);this.client.core.expirer.set(s,a),await this.client.pendingRequest.set(s,{id:s,topic:r,params:n,verifyContext:o})}),I(this,"sendRequest",async t=>{const{topic:s,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:p}=t,d=u.formatJsonRpcRequest(r,n,c);let g;const f=!!l;try{const b=f?ut:Be;g=await this.client.core.crypto.encode(s,d,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),b}let w;if(Gy.includes(r)){const b=Je(JSON.stringify(d)),m=Je(g);w=await this.client.core.verify.register({id:m,decryptedId:b})}const y=ue[r].req;if(y.attestation=w,o&&(y.ttl=o),a&&(y.id=a),this.client.core.history.set(s,d),f){const b=Vi(l,s,g);await q.dist.global.Linking.openURL(b,this.client.name)}else{const b=ue[r].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=Ie(Z({},p),{correlationId:d.id}),h?(b.internal=Ie(Z({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,g,b)):this.client.core.relayer.publish(s,g,b).catch(m=>this.client.logger.error(m))}return d.id}),I(this,"sendResult",async t=>{const{id:s,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=u.formatJsonRpcResult(s,n);let l;const p=c&&typeof(q.dist.global==null?void 0:q.dist.global.Linking)<"u";try{const f=p?ut:Be;l=await this.client.core.crypto.encode(r,h,Ie(Z({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),f}let d,g;try{d=await this.client.core.history.get(r,s);const f=d.request;try{this.shouldSetTVF(f.method,f.params)&&(g=this.getTVFParams(s,f.params,n))}catch(w){this.client.logger.warn("sendResult() -> getTVFParams() failed",w)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),f}if(p){const f=Vi(c,r,l);await q.dist.global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,w=ue[f].res;w.tvf=Ie(Z({},g),{correlationId:s}),o?(w.internal=Ie(Z({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,w)):this.client.core.relayer.publish(r,l,w).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(h)}),I(this,"sendError",async t=>{const{id:s,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=u.formatJsonRpcError(s,n);let l;const p=c&&typeof(q.dist.global==null?void 0:q.dist.global.Linking)<"u";try{const g=p?ut:Be;l=await this.client.core.crypto.encode(r,h,Ie(Z({},o||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),g}let d;try{d=await this.client.core.history.get(r,s)}catch(g){throw this.client.logger.error(`sendError() -> history.get(${r}, ${s}) failed`),g}if(p){const g=Vi(c,r,l);await q.dist.global.Linking.openURL(g,this.client.name)}else{const g=d.request.method,f=a||ue[g].res;this.client.core.relayer.publish(r,l,f)}await this.client.core.history.resolve(h)}),I(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;lt(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=>{lt(r.expiryTimestamp)&&s.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...s.map(r=>this.deleteProposal(r))])}),I(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),I(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),I(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Ge.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=Ge.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=Ge.idle}),I(this,"processRequest",async t=>{const{topic:s,payload:r,attestation:n,transportType:o,encryptedId:a}=t,c=r.method;if(!this.shouldIgnorePairingRequest({topic:s,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:s,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(s,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(s,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(s,r);case"wc_sessionPing":return await this.onSessionPingRequest(s,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(s,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:s,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(s,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:s,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),I(this,"onRelayEventResponse",async t=>{const{topic:s,payload:r,transportType:n}=t,o=(await this.client.core.history.get(s,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(s,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(s,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(s,r);case"wc_sessionExtend":return this.onSessionExtendResponse(s,r);case"wc_sessionPing":return this.onSessionPingResponse(s,r);case"wc_sessionRequest":return this.onSessionRequestResponse(s,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(s,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),I(this,"onRelayEventUnknownPayload",t=>{const{topic:s}=t,{message:r}=C("MISSING_OR_INVALID",`Decoded payload on topic ${s} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),I(this,"shouldIgnorePairingRequest",t=>{const{topic:s,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(s);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),I(this,"onSessionProposeRequest",async t=>{const{topic:s,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:c}=r;try{const h=this.client.core.eventClient.getEvent({topic:s});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),h==null||h.setError(st.proposal_listener_not_found)),this.isValidConnect(Z({},r.params));const l=a.expiryTimestamp||ce(ue.wc_sessionPropose.req.ttl),p=Z({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,p);const d=await this.getVerifyContext({attestationId:n,hash:Je(JSON.stringify(r)),encryptedId:o,metadata:p.proposer.metadata});h==null||h.addTrace(We.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:p,verifyContext:d})}catch(h){await this.sendError({id:c,topic:s,error:h,rpcOpts:ue.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),I(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(u.isJsonRpcResult(s)){const{result:o}=s;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(c,h);this.pendingSessions.set(n,{sessionTopic:l,pairingTopic:t,proposalId:n,publicKey:c});const p=await this.client.core.relayer.subscribe(l,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:p}),await this.client.core.pairing.activate({topic:t})}else if(u.isJsonRpcError(s)){await this.client.proposal.delete(n,Q("USER_DISCONNECTED"));const o=J("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:s.error})}}),I(this,"onSessionSettleRequest",async(t,s)=>{const{id:r,params:n}=s;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:h,sessionProperties:l,scopedProperties:p,sessionConfig:d}=s.params,g=[...this.pendingSessions.values()].find(y=>y.sessionTopic===t);if(!g)return this.client.logger.error(`Pending session not found for topic ${t}`);const f=this.client.proposal.get(g.proposalId),w=Ie(Z(Z(Z({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:g.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:g.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),p&&{scopedProperties:p}),d&&{sessionConfig:d}),{transportType:te.relay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:g.pairingTopic,metadata:w.peer.metadata}),this.client.events.emit("session_connect",{session:w}),this.events.emit(J("session_connect",g.proposalId),{session:w}),this.pendingSessions.delete(g.proposalId),this.deleteProposal(g.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:s.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),I(this,"onSessionSettleResponse",async(t,s)=>{const{id:r}=s;u.isJsonRpcResult(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(J("session_approve",r),{})):u.isJsonRpcError(s)&&(await this.client.session.delete(t,Q("USER_DISCONNECTED")),this.events.emit(J("session_approve",r),{error:s.error}))}),I(this,"onSessionUpdateRequest",async(t,s)=>{const{params:r,id:n}=s;try{const o=`${t}_session_update`,a=fi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:t,error:Q("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Z({topic:t},r));try{fi.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 fi.delete(o),c}this.client.events.emit("session_update",{id:n,topic:t,params:r})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}}),I(this,"isRequestOutOfSync",(t,s)=>s.toString().slice(0,-3)<t.toString().slice(0,-3)),I(this,"onSessionUpdateResponse",(t,s)=>{const{id:r}=s,n=J("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(s)?this.events.emit(J("session_update",r),{}):u.isJsonRpcError(s)&&this.events.emit(J("session_update",r),{error:s.error})}),I(this,"onSessionExtendRequest",async(t,s)=>{const{id:r}=s;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ce(kt)),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),I(this,"onSessionExtendResponse",(t,s)=>{const{id:r}=s,n=J("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(s)?this.events.emit(J("session_extend",r),{}):u.isJsonRpcError(s)&&this.events.emit(J("session_extend",r),{error:s.error})}),I(this,"onSessionPingRequest",async(t,s)=>{const{id:r}=s;try{this.isValidPing({topic:t}),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),I(this,"onSessionPingResponse",(t,s)=>{const{id:r}=s,n=J("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);u.isJsonRpcResult(s)?this.events.emit(J("session_ping",r),{}):u.isJsonRpcError(s)&&this.events.emit(J("session_ping",r),{error:s.error})},500)}),I(this,"onSessionDeleteRequest",async(t,s)=>{const{id:r}=s;try{this.isValidDisconnect({topic:t,reason:s.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(de.publish,async()=>{n(await this.deleteSession({topic:t,id:r}))})}),this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Q("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),I(this,"onSessionRequest",async t=>{var s,r,n;const{topic:o,payload:a,attestation:c,encryptedId:h,transportType:l}=t,{id:p,params:d}=a;try{await this.isValidRequest(Z({topic:o},d));const g=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:Je(JSON.stringify(u.formatJsonRpcRequest("wc_sessionRequest",d,p))),encryptedId:h,metadata:g.peer.metadata,transportType:l}),w={id:p,topic:o,params:d,verifyContext:f};await this.setPendingSessionRequest(w),l===te.link_mode&&(s=g.peer.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp((r=g.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(g){await this.sendError({id:p,topic:o,error:g}),this.client.logger.error(g)}}),I(this,"onSessionRequestResponse",(t,s)=>{const{id:r}=s,n=J("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);u.isJsonRpcResult(s)?this.events.emit(J("session_request",r),{result:s.result}):u.isJsonRpcError(s)&&this.events.emit(J("session_request",r),{error:s.error})}),I(this,"onSessionEventRequest",async(t,s)=>{const{id:r,params:n}=s;try{const o=`${t}_session_event_${n.event.name}`,a=fi.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Z({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),fi.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),I(this,"onSessionAuthenticateResponse",(t,s)=>{const{id:r}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:s}),u.isJsonRpcResult(s)?this.events.emit(J("session_request",r),{result:s.result}):u.isJsonRpcError(s)&&this.events.emit(J("session_request",r),{error:s.error})}),I(this,"onSessionAuthenticateRequest",async t=>{var s;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:h,authPayload:l,expiryTimestamp:p}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Je(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),g={requester:h,pairingTopic:r,id:n.id,authPayload:l,verifyContext:d,expiryTimestamp:p};await this.setAuthRequest(n.id,{request:g,pairingTopic:r,transportType:c}),c===te.link_mode&&(s=h.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:d})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,p=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),g={type:at,receiverPublicKey:l,senderPublicKey:p};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:g,rpcOpts:ue.wc_sessionAuthenticate.autoReject,appLink:d})}}),I(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),I(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ge.idle,this.processSessionRequestQueue()},u.cjs.toMiliseconds(this.requestQueueDelay))}),I(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:s})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=J("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(J("session_request",n.request.id),{error:s})})}),I(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Ge.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=Ge.active,this.emitSessionRequest(t)}catch(s){this.client.logger.error(s)}}),I(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),I(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const s=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);s&&this.onSessionProposeRequest({topic:t.topic,payload:u.formatJsonRpcRequest("wc_sessionPropose",Ie(Z({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id)})}),I(this,"isValidConnect",async t=>{if(!$e(t)){const{message:h}=C("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:s,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(we(s)||await this.isValidPairingTopic(s),!Ip(c)){const{message:h}=C("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!we(r)&>(r)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(r,"requiredNamespaces")}if(!we(n)&>(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(l=>h.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(h)}`)}}),I(this,"validateNamespaces",(t,s)=>{const r=Ep(t,"connect()",s);if(r)throw new Error(r.message)}),I(this,"isValidApprove",async t=>{if(!$e(t))throw new Error(C("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:s,namespaces:r,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(s),await this.isValidProposalId(s);const c=this.client.proposal.get(s),h=Rs(r,"approve()");if(h)throw new Error(h.message);const l=Cn(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!ne(n,!0)){const{message:p}=C("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(p)}if(we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const p=new Set(Object.keys(r));if(!Object.keys(a).every(d=>p.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(p).join(", ")}`)}}),I(this,"isValidReject",async t=>{if(!$e(t)){const{message:n}=C("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:s,reason:r}=t;if(this.checkRecentlyDeleted(s),await this.isValidProposalId(s),!Pp(r)){const{message:n}=C("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),I(this,"isValidSessionSettleRequest",t=>{if(!$e(t)){const{message:h}=C("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:s,controller:r,namespaces:n,expiry:o}=t;if(!Aa(s)){const{message:h}=C("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=fp(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Rs(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(lt(o)){const{message:h}=C("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),I(this,"isValidUpdate",async t=>{if(!$e(t)){const{message:c}=C("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:s,namespaces:r}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const n=this.client.session.get(s),o=Rs(r,"update()");if(o)throw new Error(o.message);const a=Cn(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),I(this,"isValidExtend",async t=>{if(!$e(t)){const{message:r}=C("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:s}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s)}),I(this,"isValidRequest",async t=>{if(!$e(t)){const{message:c}=C("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:s,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const{namespaces:a}=this.client.session.get(s);if(!Rn(a,n)){const{message:c}=C("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!$p(r)){const{message:c}=C("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!Ap(a,n,r.method)){const{message:c}=C("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Np(o,Ds)){const{message:c}=C("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Ds.min} and ${Ds.max}`);throw new Error(c)}}),I(this,"isValidRespond",async t=>{var s;if(!$e(t)){const{message:o}=C("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(s=t==null?void 0:t.response)!=null&&s.id&&this.cleanupAfterResponse(t),o}if(!Sp(n)){const{message:o}=C("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),I(this,"isValidPing",async t=>{if(!$e(t)){const{message:r}=C("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),I(this,"isValidEmit",async t=>{if(!$e(t)){const{message:a}=C("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:s,event:r,chainId:n}=t;await this.isValidSessionTopic(s);const{namespaces:o}=this.client.session.get(s);if(!Rn(o,n)){const{message:a}=C("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Op(r)){const{message:a}=C("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!xp(o,n,r.name)){const{message:a}=C("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),I(this,"isValidDisconnect",async t=>{if(!$e(t)){const{message:r}=C("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),I(this,"isValidAuthenticate",t=>{const{chains:s,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(s)||s.length===0)throw new Error("chains is required and must be a non-empty array");if(!ne(r,!1))throw new Error("uri is required parameter");if(!ne(n,!1))throw new Error("domain is required parameter");if(!ne(o,!1))throw new Error("nonce is required parameter");if([...new Set(s.map(c=>Zt(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Zt(s[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),I(this,"getVerifyContext",async t=>{const{attestationId:s,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||Pi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===te.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const h=await this.client.core.verify.resolve({attestationId:s,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),I(this,"validateSessionProps",(t,s)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=C("MISSING_OR_INVALID",`${s} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),I(this,"getPendingAuthRequest",t=>{const s=this.client.auth.requests.get(t);return typeof s=="object"?s:void 0}),I(this,"addToRecentlyDeleted",(t,s)=>{if(this.recentlyDeletedMap.set(t,s),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=n)break;this.recentlyDeletedMap.delete(o)}}}),I(this,"checkRecentlyDeleted",t=>{const s=this.recentlyDeletedMap.get(t);if(s){const{message:r}=C("MISSING_OR_INVALID",`Record was recently deleted - ${s}: ${t}`);throw new Error(r)}}),I(this,"isLinkModeEnabled",(t,s)=>{var r,n,o,a,c,h,l,p,d;return!t||s!==te.link_mode?!1:((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((l=t==null?void 0:t.redirect)==null?void 0:l.universal)!==void 0&&((p=t==null?void 0:t.redirect)==null?void 0:p.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(q.dist.global==null?void 0:q.dist.global.Linking)<"u"}),I(this,"getAppLinkIfEnabled",(t,s)=>{var r;return this.isLinkModeEnabled(t,s)?(r=t==null?void 0:t.redirect)==null?void 0:r.universal:void 0}),I(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const s=Vr(t,"topic")||"",r=decodeURIComponent(Vr(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:te.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),I(this,"registerLinkModeListeners",async()=>{var t;if(Er()||ft()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const s=q.dist.global==null?void 0:q.dist.global.Linking;if(typeof s<"u"){s.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await s.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),I(this,"shouldSetTVF",(t,s)=>{if(!s||t!=="wc_sessionRequest")return!1;const{request:r}=s;return Object.keys(co).includes(r.method)}),I(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return Ie(Z({correlationId:t,rpcMethods:[a],chainId:s.chainId},this.isValidContractData(s.request.params)&&{contractAddresses:[(o=(n=s.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),I(this,"isValidContractData",t=>{var s;if(!t)return!1;try{const r=(t==null?void 0:t.data)||((s=t==null?void 0:t[0])==null?void 0:s.data);if(!r.startsWith("0x"))return!1;const n=r.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),I(this,"extractTxHashesFromResult",(t,s)=>{try{const r=co[t];if(typeof s=="string")return[s];const n=s[r.key];if(ze(n))return t==="solana_signAllTransactions"?n.map(o=>Zh(o)):n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[s,r]of Object.entries(t))for(const n of r)try{await this.onProviderMessageEvent({topic:s,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${s}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=C("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(de.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(ts)?this.client.auth.authKeys.get(ts):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===te.link_mode?ut:Be});u.isJsonRpcRequest(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:Je(s)})):u.isJsonRpcResponse(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,s)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ke.expired,async e=>{const{topic:t,id:s}=Go(e.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,C("EXPIRED"),!0);if(s&&this.client.auth.requests.keys.includes(s))return await this.deletePendingAuthRequest(s,C("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):s&&(await this.deleteProposal(s,!0),this.client.events.emit("proposal_expire",{id:s}))})}registerPairingEvents(){this.client.core.pairing.events.on(It.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(It.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ne(e,!1)){const{message:t}=C("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=C("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(lt(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=C("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ne(e,!1)){const{message:t}=C("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=C("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(lt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=C("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=C("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ne(e,!1)){const{message:t}=C("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=C("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!_p(e)){const{message:t}=C("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=C("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(lt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=C("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class nm extends Rt{constructor(e,t){super(e,t,zy,xr),this.core=e,this.logger=t}}let om=class extends Rt{constructor(e,t){super(e,t,Hy,xr),this.core=e,this.logger=t}};class am extends Rt{constructor(e,t){super(e,t,Ky,xr,s=>s.id),this.core=e,this.logger=t}}class cm extends Rt{constructor(e,t){super(e,t,Qy,ms,()=>ts),this.core=e,this.logger=t}}class hm extends Rt{constructor(e,t){super(e,t,Yy,ms),this.core=e,this.logger=t}}class lm extends Rt{constructor(e,t){super(e,t,Zy,ms,s=>s.id),this.core=e,this.logger=t}}var um=Object.defineProperty,pm=(i,e,t)=>e in i?um(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Fs=(i,e,t)=>pm(i,typeof e!="symbol"?e+"":e,t);class dm{constructor(e,t){this.core=e,this.logger=t,Fs(this,"authKeys"),Fs(this,"pairingTopics"),Fs(this,"requests"),this.authKeys=new cm(this.core,this.logger),this.pairingTopics=new hm(this.core,this.logger),this.requests=new lm(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var gm=Object.defineProperty,fm=(i,e,t)=>e in i?gm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,H=(i,e,t)=>fm(i,typeof e!="symbol"?e+"":e,t);let ym=class Wa extends rd{constructor(e){super(e),H(this,"protocol",Va),H(this,"version",Ka),H(this,"name",ks.name),H(this,"metadata"),H(this,"core"),H(this,"logger"),H(this,"events",new u.eventsExports.EventEmitter),H(this,"engine"),H(this,"session"),H(this,"proposal"),H(this,"pendingRequest"),H(this,"auth"),H(this,"signConfig"),H(this,"on",(s,r)=>this.events.on(s,r)),H(this,"once",(s,r)=>this.events.once(s,r)),H(this,"off",(s,r)=>this.events.off(s,r)),H(this,"removeListener",(s,r)=>this.events.removeListener(s,r)),H(this,"removeAllListeners",s=>this.events.removeAllListeners(s)),H(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"pair",async s=>{try{return await this.engine.pair(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"approve",async s=>{try{return await this.engine.approve(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"reject",async s=>{try{return await this.engine.reject(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"update",async s=>{try{return await this.engine.update(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"extend",async s=>{try{return await this.engine.extend(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"request",async s=>{try{return await this.engine.request(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"respond",async s=>{try{return await this.engine.respond(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"ping",async s=>{try{return await this.engine.ping(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"emit",async s=>{try{return await this.engine.emit(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"find",s=>{try{return this.engine.find(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}}),H(this,"authenticate",async(s,r)=>{try{return await this.engine.authenticate(s,r)}catch(n){throw this.logger.error(n.message),n}}),H(this,"formatAuthMessage",s=>{try{return this.engine.formatAuthMessage(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"approveSessionAuthenticate",async s=>{try{return await this.engine.approveSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),H(this,"rejectSessionAuthenticate",async s=>{try{return await this.engine.rejectSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||ks.name,this.metadata=uh(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:u.Ot(u.k({level:(e==null?void 0:e.logger)||ks.logger}));this.core=(e==null?void 0:e.core)||new By(e),this.logger=u.E(t,this.name),this.session=new om(this.core,this.logger),this.proposal=new nm(this.core,this.logger),this.pendingRequest=new am(this.core,this.logger),this.engine=new rm(this),this.auth=new dm(this.core,this.logger)}static async init(e){const t=new Wa(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 lo="error",mm="wss://relay.walletconnect.org",wm="wc",bm="universal_provider",Gi=`${wm}@2:${bm}:`,Ja="https://rpc.walletconnect.org/v1/",Wt="generic",vm=`${Ja}bundler`,De={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Em(){}function Rr(i){return i==null||typeof i!="object"&&typeof i!="function"}function Cr(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Im(i){if(Rr(i))return i;if(Array.isArray(i)||Cr(i)||i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);const e=Object.getPrototypeOf(i),t=e.constructor;if(i instanceof Date||i instanceof Map||i instanceof Set)return new t(i);if(i instanceof RegExp){const s=new t(i);return s.lastIndex=i.lastIndex,s}if(i instanceof DataView)return new t(i.buffer.slice(0));if(i instanceof Error){const s=new t(i.message);return s.stack=i.stack,s.name=i.name,s.cause=i.cause,s}if(typeof File<"u"&&i instanceof File)return new t([i],i.name,{type:i.type,lastModified:i.lastModified});if(typeof i=="object"){const s=Object.create(e);return Object.assign(s,i)}return i}function uo(i){return typeof i=="object"&&i!==null}function Qa(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Ya(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const _m="[object RegExp]",Za="[object String]",Xa="[object Number]",ec="[object Boolean]",tc="[object Arguments]",Pm="[object Symbol]",$m="[object Date]",Sm="[object Map]",Om="[object Set]",Am="[object Array]",xm="[object ArrayBuffer]",Rm="[object Object]",Cm="[object DataView]",Nm="[object Uint8Array]",Tm="[object Uint8ClampedArray]",jm="[object Uint16Array]",qm="[object Uint32Array]",km="[object Int8Array]",Dm="[object Int16Array]",Fm="[object Int32Array]",Um="[object Float32Array]",Mm="[object Float64Array]";function Lm(i,e){return Yt(i,void 0,i,new Map,e)}function Yt(i,e,t,s=new Map,r=void 0){const n=r==null?void 0:r(i,e,t,s);if(n!=null)return n;if(Rr(i))return i;if(s.has(i))return s.get(i);if(Array.isArray(i)){const o=new Array(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=Yt(i[a],a,t,s,r);return Object.hasOwn(i,"index")&&(o.index=i.index),Object.hasOwn(i,"input")&&(o.input=i.input),o}if(i instanceof Date)return new Date(i.getTime());if(i instanceof RegExp){const o=new RegExp(i.source,i.flags);return o.lastIndex=i.lastIndex,o}if(i instanceof Map){const o=new Map;s.set(i,o);for(const[a,c]of i)o.set(a,Yt(c,a,t,s,r));return o}if(i instanceof Set){const o=new Set;s.set(i,o);for(const a of i)o.add(Yt(a,void 0,t,s,r));return o}if(typeof q.dist.Buffer<"u"&&q.dist.Buffer.isBuffer(i))return i.subarray();if(Cr(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=Yt(i[a],a,t,s,r);return o}if(i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);if(i instanceof DataView){const o=new DataView(i.buffer.slice(0),i.byteOffset,i.byteLength);return s.set(i,o),_t(o,i,t,s,r),o}if(typeof File<"u"&&i instanceof File){const o=new File([i],i.name,{type:i.type});return s.set(i,o),_t(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),_t(o,i,t,s,r),o}if(i instanceof Error){const o=new i.constructor;return s.set(i,o),o.message=i.message,o.name=i.name,o.stack=i.stack,o.cause=i.cause,_t(o,i,t,s,r),o}if(typeof i=="object"&&Bm(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),_t(o,i,t,s,r),o}return i}function _t(i,e,t=i,s,r){const n=[...Object.keys(e),...Qa(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=Yt(e[a],a,t,s,r))}}function Bm(i){switch(Ya(i)){case tc:case Am:case xm:case Cm:case ec:case $m:case Um:case Mm:case km:case Dm:case Fm:case Sm:case Xa:case Rm:case _m:case Om:case Za:case Pm:case Nm:case Tm:case jm:case qm:return!0;default:return!1}}function zm(i,e){return Lm(i,(t,s,r,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case Xa:case Za:case ec:{const o=new i.constructor(i==null?void 0:i.valueOf());return _t(o,i),o}case tc:{const o={};return _t(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function po(i){return zm(i)}function go(i){return i!==null&&typeof i=="object"&&Ya(i)==="[object Arguments]"}function Hm(i){return Cr(i)}function Vm(i){var t;if(typeof i!="object"||i==null)return!1;if(Object.getPrototypeOf(i)===null)return!0;if(Object.prototype.toString.call(i)!=="[object Object]"){const s=i[Symbol.toStringTag];return s==null||!((t=Object.getOwnPropertyDescriptor(i,Symbol.toStringTag))!=null&&t.writable)?!1:i.toString()===`[object ${s}]`}let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function Km(i,...e){const t=e.slice(0,-1),s=e[e.length-1];let r=i;for(let n=0;n<t.length;n++){const o=t[n];r=fr(r,o,s,new Map)}return r}function fr(i,e,t,s){if(Rr(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(s.has(e))return Im(s.get(e));if(s.set(e,i),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const r=[...Object.keys(e),...Qa(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(go(a)&&(a={...a}),go(c)&&(c={...c}),typeof q.dist.Buffer<"u"&&q.dist.Buffer.isBuffer(a)&&(a=po(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],p=Reflect.ownKeys(c);for(let d=0;d<p.length;d++){const g=p[d];l[g]=c[g]}c=l}else c=[];const h=t(c,a,o,i,e,s);h!=null?i[o]=h:Array.isArray(a)||uo(c)&&uo(a)?i[o]=fr(c,a,t,s):c==null&&Vm(a)?i[o]=fr({},a,t,s):c==null&&Hm(a)?i[o]=po(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Gm(i,...e){return Km(i,...e,Em)}var Wm=Object.defineProperty,Jm=Object.defineProperties,Qm=Object.getOwnPropertyDescriptors,fo=Object.getOwnPropertySymbols,Ym=Object.prototype.hasOwnProperty,Zm=Object.prototype.propertyIsEnumerable,yo=(i,e,t)=>e in i?Wm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wi=(i,e)=>{for(var t in e||(e={}))Ym.call(e,t)&&yo(i,t,e[t]);if(fo)for(var t of fo(e))Zm.call(e,t)&&yo(i,t,e[t]);return i},Xm=(i,e)=>Jm(i,Qm(e));function Te(i,e,t){var s;const r=Zt(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${Ja}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Ct(i){return i.includes(":")?i.split(":")[1]:i}function ic(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function ew(i,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(i));if(!t.length)return[];const s=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;s.push(...n)}),s}function Ji(i={},e={}){const t=mo(i),s=mo(e);return Gm(t,s)}function mo(i){var e,t,s,r,n;const o={};if(!gt(i))return o;for(const[a,c]of Object.entries(i)){const h=fs(a)?[a]:c.chains,l=c.methods||[],p=c.events||[],d=c.rpcMap||{},g=Qt(a);o[g]=Xm(Wi(Wi({},o[g]),c),{chains:Qe(h,(e=o[g])==null?void 0:e.chains),methods:Qe(l,(t=o[g])==null?void 0:t.methods),events:Qe(p,(s=o[g])==null?void 0:s.events)}),(gt(d)||gt(((r=o[g])==null?void 0:r.rpcMap)||{}))&&(o[g].rpcMap=Wi(Wi({},d),(n=o[g])==null?void 0:n.rpcMap))}return o}function wo(i){return i.includes(":")?i.split(":")[2]:i}function bo(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=fs(t)?[t]:s.chains?s.chains:ic(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Us(i){return typeof i=="number"?i:i.includes("0x")?parseInt(i,16):(i=i.includes(":")?i.split(":")[1]:i,isNaN(Number(i))?i:Number(i))}const sc={},G=i=>sc[i],Ms=(i,e)=>{sc[i]=e};var tw=Object.defineProperty,iw=(i,e,t)=>e in i?tw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Dt=(i,e,t)=>iw(i,typeof e!="symbol"?e+"":e,t);class sw{constructor(e){Dt(this,"name","polkadot"),Dt(this,"client"),Dt(this,"httpProviders"),Dt(this,"events"),Dt(this,"namespace"),Dt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Ct(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var rw=Object.defineProperty,nw=Object.defineProperties,ow=Object.getOwnPropertyDescriptors,vo=Object.getOwnPropertySymbols,aw=Object.prototype.hasOwnProperty,cw=Object.prototype.propertyIsEnumerable,yr=(i,e,t)=>e in i?rw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Eo=(i,e)=>{for(var t in e||(e={}))aw.call(e,t)&&yr(i,t,e[t]);if(vo)for(var t of vo(e))cw.call(e,t)&&yr(i,t,e[t]);return i},Io=(i,e)=>nw(i,ow(e)),Ft=(i,e,t)=>yr(i,typeof e!="symbol"?e+"":e,t);class hw{constructor(e){Ft(this,"name","eip155"),Ft(this,"client"),Ft(this,"chainId"),Ft(this,"namespace"),Ft(this,"httpProviders"),Ft(this,"events"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const s=t||Te(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=parseInt(Ct(t));e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,s;let r=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const n=parseInt(r,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(s=this.namespace.chains)==null?void 0:s[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,s,r,n,o;const a=(s=(t=e.request)==null?void 0:t.params)==null?void 0:s[0],c=((n=(r=e.request)==null?void 0:r.params)==null?void 0:n[1])||[],h=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),p=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(p!=null&&p[h])return p==null?void 0:p[h];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Io(Eo({},l.sessionProperties||{}),{capabilities:Io(Eo({},p||{}),{[h]:d})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return d}async getCallStatus(e){var t,s;const r=this.client.session.get(e.topic),n=(t=r.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(s=r.sessionProperties)==null?void 0:s.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var s;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u.formatJsonRpcRequest("eth_getUserOperationReceipt",[(s=t.request.params)==null?void 0:s[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${vm}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var lw=Object.defineProperty,uw=(i,e,t)=>e in i?lw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ut=(i,e,t)=>uw(i,typeof e!="symbol"?e+"":e,t);class pw{constructor(e){Ut(this,"name","solana"),Ut(this,"client"),Ut(this,"httpProviders"),Ut(this,"events"),Ut(this,"namespace"),Ut(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Ct(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var dw=Object.defineProperty,gw=(i,e,t)=>e in i?dw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Mt=(i,e,t)=>gw(i,typeof e!="symbol"?e+"":e,t);class fw{constructor(e){Mt(this,"name","cosmos"),Mt(this,"client"),Mt(this,"httpProviders"),Mt(this,"events"),Mt(this,"namespace"),Mt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Ct(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var yw=Object.defineProperty,mw=(i,e,t)=>e in i?yw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Lt=(i,e,t)=>mw(i,typeof e!="symbol"?e+"":e,t);class ww{constructor(e){Lt(this,"name","algorand"),Lt(this,"client"),Lt(this,"httpProviders"),Lt(this,"events"),Lt(this,"namespace"),Lt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const s=t||Te(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.chainId=e,this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;e[t]=this.createHttpProvider(t,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Te(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new u.o(new u.f$1(s,G("disableProviderPing")))}}var bw=Object.defineProperty,vw=(i,e,t)=>e in i?bw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Bt=(i,e,t)=>vw(i,typeof e!="symbol"?e+"":e,t);class Ew{constructor(e){Bt(this,"name","cip34"),Bt(this,"client"),Bt(this,"httpProviders"),Bt(this,"events"),Bt(this,"namespace"),Bt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const s=this.getCardanoRPCUrl(t),r=Ct(t);e[r]=this.createHttpProvider(r,s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||this.getCardanoRPCUrl(e);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var Iw=Object.defineProperty,_w=(i,e,t)=>e in i?Iw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,zt=(i,e,t)=>_w(i,typeof e!="symbol"?e+"":e,t);class Pw{constructor(e){zt(this,"name","elrond"),zt(this,"client"),zt(this,"httpProviders"),zt(this,"events"),zt(this,"namespace"),zt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Ct(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var $w=Object.defineProperty,Sw=(i,e,t)=>e in i?$w(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ht=(i,e,t)=>Sw(i,typeof e!="symbol"?e+"":e,t);class Ow{constructor(e){Ht(this,"name","multiversx"),Ht(this,"client"),Ht(this,"httpProviders"),Ht(this,"events"),Ht(this,"namespace"),Ht(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Ct(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var Aw=Object.defineProperty,xw=(i,e,t)=>e in i?Aw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Vt=(i,e,t)=>xw(i,typeof e!="symbol"?e+"":e,t);class Rw{constructor(e){Vt(this,"name","near"),Vt(this,"client"),Vt(this,"httpProviders"),Vt(this,"events"),Vt(this,"namespace"),Vt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||Te(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;e[t]=this.createHttpProvider(t,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Te(e,this.namespace);return typeof s>"u"?void 0:new u.o(new u.f$1(s,G("disableProviderPing")))}}var Cw=Object.defineProperty,Nw=(i,e,t)=>e in i?Cw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Kt=(i,e,t)=>Nw(i,typeof e!="symbol"?e+"":e,t);class Tw{constructor(e){Kt(this,"name","tezos"),Kt(this,"client"),Kt(this,"httpProviders"),Kt(this,"events"),Kt(this,"namespace"),Kt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||Te(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Te(e,this.namespace);return typeof s>"u"?void 0:new u.o(new u.f$1(s))}}var jw=Object.defineProperty,qw=(i,e,t)=>e in i?jw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Gt=(i,e,t)=>qw(i,typeof e!="symbol"?e+"":e,t);class kw{constructor(e){Gt(this,"name",Wt),Gt(this,"client"),Gt(this,"httpProviders"),Gt(this,"events"),Gt(this,"namespace"),Gt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(De.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const s={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=Zt(r);s[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),s}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Te(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new u.o(new u.f$1(s,G("disableProviderPing")))}}var Dw=Object.defineProperty,Fw=Object.defineProperties,Uw=Object.getOwnPropertyDescriptors,_o=Object.getOwnPropertySymbols,Mw=Object.prototype.hasOwnProperty,Lw=Object.prototype.propertyIsEnumerable,mr=(i,e,t)=>e in i?Dw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qi=(i,e)=>{for(var t in e||(e={}))Mw.call(e,t)&&mr(i,t,e[t]);if(_o)for(var t of _o(e))Lw.call(e,t)&&mr(i,t,e[t]);return i},Ls=(i,e)=>Fw(i,Uw(e)),qe=(i,e,t)=>mr(i,typeof e!="symbol"?e+"":e,t);let Bw=class rc{constructor(e){qe(this,"client"),qe(this,"namespaces"),qe(this,"optionalNamespaces"),qe(this,"sessionProperties"),qe(this,"scopedProperties"),qe(this,"events",new u.Nt),qe(this,"rpcProviders",{}),qe(this,"session"),qe(this,"providerOpts"),qe(this,"logger"),qe(this,"uri"),qe(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:u.Ot(u.k({level:(e==null?void 0:e.logger)||lo})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new rc(e);return await t.initialize(),t}async request(e,t,s){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Qi({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:s})}sendAsync(e,t,s,r){const n=new Date().getTime();this.request(e,s,r).then(o=>t(null,u.formatJsonRpcResult(n,o))).catch(o=>t(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Q("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:s,response:r}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const n=await r();if(this.session=n.session,this.session){const o=bo(this.session.namespaces);this.namespaces=Ji(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await s();this.session=r;const n=bo(r.namespaces);return this.namespaces=Ji(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[s,r]=this.validateChain(e),n=this.getProvider(s);n.name===Wt?n.setDefaultChain(`${s}:${r}`,t):n.setDefaultChain(r,t)}catch(s){if(!/Please call connect/.test(s.message))throw s}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(ze(t)){for(const s of t)e.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,t;if(this.client=this.providerOpts.client||await ym.init({core:this.providerOpts.core,logger:this.providerOpts.logger||lo,relayUrl:this.providerOpts.relayUrl||mm,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(s){throw this.logger.error("Failed to get session",s),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const s=this.client.session.getAll();this.session=s[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>Qt(t)))];Ms("client",this.client),Ms("events",this.events),Ms("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=ew(t,this.session),r=ic(s),n=Ji(this.namespaces,this.optionalNamespaces),o=Ls(Qi({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new hw({namespace:o});break;case"algorand":this.rpcProviders[t]=new ww({namespace:o});break;case"solana":this.rpcProviders[t]=new pw({namespace:o});break;case"cosmos":this.rpcProviders[t]=new fw({namespace:o});break;case"polkadot":this.rpcProviders[t]=new sw({namespace:o});break;case"cip34":this.rpcProviders[t]=new Ew({namespace:o});break;case"elrond":this.rpcProviders[t]=new Pw({namespace:o});break;case"multiversx":this.rpcProviders[t]=new Ow({namespace:o});break;case"near":this.rpcProviders[t]=new Rw({namespace:o});break;case"tezos":this.rpcProviders[t]=new Tw({namespace:o});break;default:this.rpcProviders[Wt]?this.rpcProviders[Wt].updateNamespace(o):this.rpcProviders[Wt]=new kw({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:s}=e;s===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:s,topic:r}=e;if(r!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=s;if(n.name==="accountsChanged"){const o=n.data;o&&ze(o)&&this.events.emit("accountsChanged",o.map(wo))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=Qt(o),h=Us(o)!==Us(a)?`${c}:${Us(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var s,r;if(e!==((s=this.session)==null?void 0:s.topic))return;const{namespaces:n}=t,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Ls(Qi({},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",Ls(Qi({},Q("USER_DISCONNECTED")),{data:e.topic})))}),this.on(De.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Wt]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:s={},sessionProperties:r,scopedProperties:n}=e;this.optionalNamespaces=Ji(t,s),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,s]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(o=>Qt(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&s)return[t,s];const r=Qt(Object.keys(this.namespaces)[0]),n=this.rpcProviders[r].getDefaultChain();return[r,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[s,r]=this.validateChain(e);if(!r)return;this.updateNamespaceChain(s,r),this.events.emit("chainChanged",r);const n=this.getProvider(s).getDefaultChain();t||this.getProvider(s).setDefaultChain(r),this.emitAccountsChangedOnChainChange({namespace:s,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:s}){var r,n;try{if(t===s)return;const o=(n=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${s}:`)).map(wo);if(!ze(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const s=this.namespaces[e]?e:`${e}:${t}`,r={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[s]?this.namespaces[s]&&(this.namespaces[s].defaultChain=t):this.namespaces[s]=r}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var s;const r=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.setItem(`${Gi}/${e}${r}`,t)}async getFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${Gi}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${Gi}/${e}${s}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const s of t)s.startsWith(Gi)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const zw=Bw,Hw="wc",Vw="ethereum_provider",Kw=`${Hw}@2:${Vw}:`,Gw="https://rpc.walletconnect.org/v1/",as=["eth_sendTransaction","personal_sign"],nc=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],cs=["chainChanged","accountsChanged"],oc=["chainChanged","accountsChanged","message","disconnect","connect"],Ww=async()=>{const{createAppKit:i}=await Promise.resolve().then(()=>require("./core-CV23yxnG.js")).then(e=>e.core);return i};var Jw=Object.defineProperty,Qw=Object.defineProperties,Yw=Object.getOwnPropertyDescriptors,Po=Object.getOwnPropertySymbols,Zw=Object.prototype.hasOwnProperty,Xw=Object.prototype.propertyIsEnumerable,wr=(i,e,t)=>e in i?Jw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vt=(i,e)=>{for(var t in e||(e={}))Zw.call(e,t)&&wr(i,t,e[t]);if(Po)for(var t of Po(e))Xw.call(e,t)&&wr(i,t,e[t]);return i},vi=(i,e)=>Qw(i,Yw(e)),Ae=(i,e,t)=>wr(i,typeof e!="symbol"?e+"":e,t);function hs(i){return Number(i[0].split(":")[1])}function Yi(i){return`0x${i.toString(16)}`}function eb(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!ze(e))throw new Error("Invalid chains");const c={chains:e,methods:s||as,events:n||cs,rpcMap:vt({},e.length?{[hs(e)]:a[hs(e)]}:{})},h=n==null?void 0:n.filter(g=>!cs.includes(g)),l=s==null?void 0:s.filter(g=>!as.includes(g));if(!t&&!o&&!r&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const p=(h==null?void 0:h.length)&&(l==null?void 0:l.length)||!t,d={chains:[...new Set(p?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(r!=null&&r.length?r:nc))],events:[...new Set(c.events.concat(o!=null&&o.length?o:oc))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?d:void 0}}class ws{constructor(){Ae(this,"events",new u.eventsExports.EventEmitter),Ae(this,"namespace","eip155"),Ae(this,"accounts",[]),Ae(this,"signer"),Ae(this,"chainId",1),Ae(this,"modal"),Ae(this,"rpc"),Ae(this,"STORAGE_KEY",Kw),Ae(this,"on",(e,t)=>(this.events.on(e,t),this)),Ae(this,"once",(e,t)=>(this.events.once(e,t),this)),Ae(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),Ae(this,"off",(e,t)=>(this.events.off(e,t),this)),Ae(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new ws;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,s){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),s)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var t;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:s,optional:r}=eb(this.rpc);try{const n=await new Promise(async(a,c)=>{var h,l;this.rpc.showQrModal&&((h=this.modal)==null||h.open(),(l=this.modal)==null||l.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const p=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(vi(vt({namespaces:vt({},s&&{[this.namespace]:s})},r&&{optionalNamespaces:{[this.namespace]:r}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:p})).then(d=>{a(d)}).catch(d=>{var g;(g=this.modal)==null||g.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=Mr(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Yi(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(t=this.modal)==null||t.close()}}async authenticate(e,t){var s;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const r=await new Promise(async(o,a)=>{var c,h;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(h=this.modal)==null||h.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(vi(vt({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var p;(p=this.modal)==null||p.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=r.session;if(n){const o=Mr(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Yi(this.chainId)})}return r}catch(r){throw this.signer.logger.error(r),r}finally{(s=this.modal)==null||s.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:s}=t;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",Yi(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",vi(vt({},Q("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",Yi(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,s,r]=e.split(":");return{chainId:`${t}:${s}`,address:r}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,s;const r=(t=e==null?void 0:e.chains)!=null?t:[],n=(s=e==null?void 0:e.optionalChains)!=null?s:[],o=r.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=r.length?(e==null?void 0:e.methods)||as:[],c=r.length?(e==null?void 0:e.events)||cs:[],h=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],p=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:r==null?void 0:r.map(g=>this.formatChainId(g)),optionalChains:n.map(g=>this.formatChainId(g)),methods:a,events:c,optionalMethods:h,optionalEvents:l,rpcMap:p,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const s={};return e.forEach(r=>{s[r]=this.getRpcUrl(r,t)}),s}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?hs(this.rpc.chains):hs(this.rpc.optionalChains),this.signer=await zw.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let t;try{const s=await Ww(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return ub}),n=r(vi(vt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=s(vi(vt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:s,rpcMap:r}=e;t&&ze(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=(r==null?void 0:r[n])||this.getRpcUrl(n)})),s&&ze(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s==null?void 0:s.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=(r==null?void 0:r[n])||this.getRpcUrl(n)}))}getRpcUrl(e,t){var s;return((s=this.rpc.rpcMap)==null?void 0:s[e])||`${Gw}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t==null?void 0:t.accounts),this.setAccounts(t==null?void 0:t.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}}const tb=ws;var ib=Object.defineProperty,sb=Object.defineProperties,rb=Object.getOwnPropertyDescriptors,$o=Object.getOwnPropertySymbols,nb=Object.prototype.hasOwnProperty,ob=Object.prototype.propertyIsEnumerable,So=(i,e,t)=>e in i?ib(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ac=(i,e)=>{for(var t in e||(e={}))nb.call(e,t)&&So(i,t,e[t]);if($o)for(var t of $o(e))ob.call(e,t)&&So(i,t,e[t]);return i},ab=(i,e)=>sb(i,rb(e));function cb(i){if(i)return{"--w3m-font-family":i["--wcm-font-family"],"--w3m-accent":i["--wcm-accent-color"],"--w3m-color-mix":i["--wcm-background-color"],"--w3m-z-index":i["--wcm-z-index"]?Number(i["--wcm-z-index"]):void 0,"--w3m-qr-color":i["--wcm-accent-color"],"--w3m-font-size-master":i["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":i["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const hb=i=>{const[e,t]=i.split(":");return cc({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function lb(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(hb).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(p=>{var d;return p.id===((d=i.defaultChain)==null?void 0:d.id)}),l={projectId:i.projectId,networks:c,themeMode:i.themeMode,themeVariables:cb(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:ab(ac({},i.metadata),{name:((t=i.metadata)==null?void 0:t.name)||"WalletConnect",description:((s=i.metadata)==null?void 0:s.description)||"Connect to WalletConnect-compatible wallets",url:((r=i.metadata)==null?void 0:r.url)||"https://walletconnect.org",icons:((n=i.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:i.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(i.explorerRecommendedWalletIds)?i.explorerRecommendedWalletIds:[],excludeWalletIds:i.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(i.explorerExcludedWalletIds)?i.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=i.mobileWallets)!=null&&o.length||(a=i.desktopWallets)!=null&&a.length){const p=[...(i.mobileWallets||[]).map(f=>({id:f.id,name:f.name,links:f.links})),...(i.desktopWallets||[]).map(f=>({id:f.id,name:f.name,links:{native:f.links.native,universal:f.links.universal}}))],d=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],g=p.filter(f=>!d.includes(f.id));g.length&&(l.customWallets=g)}return l}function cc(i){return ac({formatters:void 0,fees:void 0,serializers:void 0},i)}var ub=Object.freeze({__proto__:null,convertWCMToAppKitOptions:lb,defineChain:cc});const pb=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:tb,OPTIONAL_EVENTS:oc,OPTIONAL_METHODS:nc,REQUIRED_EVENTS:cs,REQUIRED_METHODS:as,default:ws},Symbol.toStringTag,{value:"Module"}));exports.Hash=qo;exports.abytes=Ni;exports.aexists=Hs;exports.ahash=_c;exports.aoutput=jo;exports.bs58=Bo;exports.concatBytes=qc;exports.createView=Cc;exports.index_es=pb;exports.keccak_256=Mo;exports.randomBytes=kc;exports.rotr=Nc;exports.toBytes=br;exports.wrapConstructor=ko;
|