@dcl/blog-site 0.2.2 → 0.2.3-23948667956.commit-cfe47f9
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/assets/QueryClientProvider-mZKMZTwe.js +2 -0
- package/assets/RoobertPRO-Bold-DDyOqNrI.woff2 +0 -0
- package/assets/SignInRedirect-CXUOqOjy.js +11 -0
- package/assets/X-3yocgepi.js +15 -0
- package/assets/___vite-browser-external_commonjs-proxy-BqV5D26a.js +1 -0
- package/assets/__federation_expose_App-CMGDAIUH.js +1 -0
- package/assets/__federation_fn_import-C51lglKS.js +1 -0
- package/assets/__federation_shared_@dcl/hooks-Dm9PRmKy.js +535 -0
- package/assets/__federation_shared_@dcl/schemas-CVwtHlVJ.js +1 -0
- package/assets/__federation_shared_@emotion/react-AmEOkpjC.js +1 -0
- package/assets/__federation_shared_@emotion/styled-aZ9bk9Xh.js +1 -0
- package/assets/__federation_shared_@reduxjs/toolkit-DIZvwqf7.js +1 -0
- package/assets/__federation_shared_decentraland-ui2-KxrbFOTA.js +358 -0
- package/assets/__federation_shared_react-B3tlNTLg.js +1 -0
- package/assets/__federation_shared_react-dom-CCS4dT_K.js +1 -0
- package/assets/__federation_shared_react-redux-Ckcz2edF.js +13 -0
- package/assets/__federation_shared_react-router-dom-jUWpDOjR.js +49 -0
- package/assets/__federation_shared_viem-Cdp7wK0V.js +2 -0
- package/assets/__federation_shared_wagmi-CHWRoybR.js +17 -0
- package/assets/__vite-optional-peer-dep_lottie-react_decentraland-ui2-BIHI7g3E.js +1 -0
- package/assets/_commonjsHelpers-C4iS2aBk.js +1 -0
- package/assets/{add-Dnkf3E3Q.js → add-DHMb_tRw.js} +2 -2
- package/assets/all-wallets-Bo3QRxXL.js +6 -0
- package/assets/{app-store-C9FH4_zP.js → app-store-BHwDXU8D.js} +2 -2
- package/assets/{apple-Dm5w1W69.js → apple-BFX-plRw.js} +2 -2
- package/assets/arrow-bottom-Djx9NXV2.js +8 -0
- package/assets/{arrow-bottom-circle-Bgw9yiHN.js → arrow-bottom-circle-DcJnW2eo.js} +2 -2
- package/assets/arrow-left-BS_dJGSP.js +8 -0
- package/assets/arrow-right-B-mwy0Iu.js +8 -0
- package/assets/arrow-top-Di1bbZG1.js +8 -0
- package/assets/auto-track-pkMvCaah.js +1 -0
- package/assets/{bank-qNUWniDB.js → bank-B9SMq-ix.js} +2 -2
- package/assets/{basic-DJvhbg9L.js → basic-DijYF-IW.js} +124 -124
- package/assets/biconomy-CCw3vtwR.js +1 -0
- package/assets/{browser-Du0KKb8R.js → browser-CdKdszu-.js} +2 -2
- package/assets/{card-BpDAuOwe.js → card-CQu4Eu8c.js} +2 -2
- package/assets/ccip-AgQ5AD9v.js +1 -0
- package/assets/chains-D88UzVoE.js +1 -0
- package/assets/{checkmark-srdyV91l.js → checkmark-D2vezo75.js} +2 -2
- package/assets/{checkmark-bold-BYtPga6u.js → checkmark-bold-DriAapzP.js} +2 -2
- package/assets/chevron-bottom-CcFEOVdH.js +8 -0
- package/assets/chevron-left-BXS-ybhL.js +8 -0
- package/assets/chevron-right-TvO5COya.js +8 -0
- package/assets/chevron-top-D84SgxMg.js +8 -0
- package/assets/{chrome-store-D-UYtj15.js → chrome-store-rpsfVQln.js} +2 -2
- package/assets/{clock-BGyfn2Ix.js → clock-BMJ2gt7b.js} +2 -2
- package/assets/close-kAWkeKAP.js +8 -0
- package/assets/{coinPlaceholder-o1yCmFLN.js → coinPlaceholder-Dz8MKewa.js} +2 -2
- package/assets/common-D37S_OFt.js +1 -0
- package/assets/{compass-BrX88OdU.js → compass-BednEqu-.js} +2 -2
- package/assets/controller-D0Gc4Hsp.js +2 -0
- package/assets/{copy-CGKLgPMf.js → copy-D7rBk-hZ.js} +2 -2
- package/assets/core-Bn8Mr-tS.js +907 -0
- package/assets/create-submenu-Bu20F8-Z.webp +0 -0
- package/assets/createBundlerClient-DhRCLsYO.js +4 -0
- package/assets/createClient-C9QPJaZu.js +1 -0
- package/assets/cursor-C8UG2IDe.js +3 -0
- package/assets/{cursor-transparent--gaS-5ET.js → cursor-transparent-CyP0H3C5.js} +2 -2
- package/assets/decimals-B7Pm5rZk.js +1 -0
- package/assets/decimals-DedKFk8m.js +1 -0
- package/assets/defineChain-7I0Ce1VT.js +1 -0
- package/assets/{desktop-D3dzP-FX.js → desktop-LBcRpcZE.js} +2 -2
- package/assets/detectExtension-C2uVeK-n.js +1 -0
- package/assets/{disconnect-CsHX0nla.js → disconnect-DEBEe-yK.js} +2 -2
- package/assets/{discord-TnXCJHRv.js → discord-BlVFKMf0.js} +2 -2
- package/assets/emotion-react.browser.esm-BzYQLDSp.js +8 -0
- package/assets/emotion-use-insertion-effect-with-fallbacks.browser.esm-TsHx33zg.js +1 -0
- package/assets/encode-DvvW4ZKt.js +2 -0
- package/assets/engine-CD7SeAap.js +1 -0
- package/assets/estimate-gas-CeHGaIbG.js +3 -0
- package/assets/estimate-l1-fee-ClMO5l7U.js +1 -0
- package/assets/eth_estimateGas-C2ENZ_HR.js +1 -0
- package/assets/eth_getStorageAt-BHgF2qz5.js +1 -0
- package/assets/eth_getTransactionCount-DWnnw2mX.js +1 -0
- package/assets/ethereum-dN7ENYl_.js +1 -0
- package/assets/{etherscan-BNOTAlpJ.js → etherscan-C_pqcV9R.js} +2 -2
- package/assets/events-B5inrCVE.js +1 -0
- package/assets/{exclamation-triangle-3cTnBFEz.js → exclamation-triangle-R9Xq3IaG.js} +2 -2
- package/assets/explore-submenu-BFVuYMi9.webp +0 -0
- package/assets/{extension-C7i3kBcJ.js → extension-DkA_7Cbg.js} +2 -2
- package/assets/external-link-BPOw_fuW.js +8 -0
- package/assets/extractIPFS-B4LGER25.js +1 -0
- package/assets/{facebook-BtRXxuTh.js → facebook-CMZk_t1A.js} +2 -2
- package/assets/{farcaster-DuvCkOsj.js → farcaster-CveILPqa.js} +2 -2
- package/assets/fee-data-BKBGP5kG.js +1 -0
- package/assets/fetchTokenMetadata-BLDHgO8L.js +2 -0
- package/assets/{filters-q4uY0GXA.js → filters-BspTrZpX.js} +2 -2
- package/assets/get-ecosystem-wallet-info-D3PrM5FE.js +1 -0
- package/assets/getBalance-D7nzATjL.js +2 -0
- package/assets/getInstalledModules-Ck_Gj8FO.js +1 -0
- package/assets/getNFT-BcCS23O_.js +1 -0
- package/assets/getNFT-DXdMP0Q5.js +2 -0
- package/assets/{github-DdvkoPeB.js → github-DoFHEMIF.js} +2 -2
- package/assets/{google-d4Ql9qix.js → google-NTQi9GVe.js} +2 -2
- package/assets/governance-submenu-VTIKvCIL.webp +0 -0
- package/assets/{help-circle-BY_Weu8t.js → help-circle-DV0uNPdn.js} +2 -2
- package/assets/hex-B0Rx0hII.js +2 -0
- package/assets/{id-BJNb6vOI.js → id-UAVc1FOO.js} +1 -1
- package/assets/{image-DIsXNsXJ.js → image-BeHBzCPG.js} +2 -2
- package/assets/in-app-wallet-calls-CvFtsXP9.js +1 -0
- package/assets/index-B2OCb4Ez.js +1 -0
- package/assets/index-B65z14KI.js +4 -0
- package/assets/index-BAhlRyDG.js +1 -0
- package/assets/{index-DOqN8xaU.js → index-BTtTX-5z.js} +1 -1
- package/assets/index-BjzJcZq6.js +1 -0
- package/assets/index-BjzJcZq6__bundled.js +24 -0
- package/assets/index-BozJS3za.js +12 -0
- package/assets/index-C05H8NDX.js +1 -0
- package/assets/index-C1IoT2if.js +3 -0
- package/assets/index-C2hdqzGT.js +2 -0
- package/assets/index-CgMDPZul.js +13 -0
- package/assets/index-CjuQOkbh.js +2 -0
- package/assets/index-CpR9p5nk.js +1 -0
- package/assets/index-D1lXZVQu.js +45 -0
- package/assets/index-D6ZAha0r.js +395 -0
- package/assets/{index-X-a697cI.js → index-DJ7GgcJ9.js} +2 -2
- package/assets/index-DajuSfcu.js +2 -0
- package/assets/index-DeklogZX.js +1 -0
- package/assets/index-DmAaXUNv.js +1 -0
- package/assets/index-Dy0yjznp.js +1 -0
- package/assets/index-Dy0yjznp__bundled.js +9 -0
- package/assets/index-HvoTJwGm.js +1 -0
- package/assets/index-MYKNZAUu.js +8 -0
- package/assets/index-Tsk25L8E.js +1 -0
- package/assets/index.es-C8Kfv-K1.js +11 -0
- package/assets/index.es-CAXGMBEH.js +1 -0
- package/assets/index.es-D3pP9hN4.js +27 -0
- package/assets/index.es-D5YKsq2-.js +2 -0
- package/assets/index.umd-DK712HHb.js +1 -0
- package/assets/{info-BvPgRaaJ.js → info-CzcA85TO.js} +2 -2
- package/assets/{info-circle-sWcom9RD.js → info-circle-D3Mr3R9u.js} +2 -2
- package/assets/is-plan-event-enabled-DeNtQvA5.js +1 -0
- package/assets/json-BHzNJmTy.js +1 -0
- package/assets/jsx-runtime-DncYoG30.js +1 -0
- package/assets/jsx-runtime-DncYoG30__bundled.js +9 -0
- package/assets/learn-submenu-sfxVP5Db.webp +0 -0
- package/assets/{lightbulb-HJchniSu.js → lightbulb-B2FZtM_8.js} +2 -2
- package/assets/localBatchGatewayRequest-BIEAG3VG.js +1 -0
- package/assets/{mail-DlRijJmV.js → mail-CkhGbows.js} +2 -2
- package/assets/marketplace-submenu-CixWTv8_.webp +0 -0
- package/assets/{mobile-CoiDw6cg.js → mobile-1H3FtqAS.js} +2 -2
- package/assets/{more-LUiRL6x4.js → more-CZiQi624.js} +2 -2
- package/assets/{network-placeholder-Cj3jgVfo.js → network-placeholder-DA2bm2rC.js} +2 -2
- package/assets/{nftPlaceholder-LkhQmGFs.js → nftPlaceholder-C9t5Ydxp.js} +2 -2
- package/assets/off-D8z0OQ3M.js +8 -0
- package/assets/op-gas-fee-reducer-CfxMcvXl.js +1 -0
- package/assets/openzeppelin-ZKz6sLW9.js +1 -0
- package/assets/ownerOf-D1aXOt9Q.js +1 -0
- package/assets/parseNft-LjEwmOst.js +2 -0
- package/assets/passkeys-CTJ4NPfL.js +1 -0
- package/assets/{play-store-DBit2AoS.js → play-store-_X5LrPwx.js} +2 -2
- package/assets/{plus-CZe-WgSN.js → plus-JriDhMxt.js} +2 -2
- package/assets/preload-helper-BorDCKdG.js +1 -0
- package/assets/publicKeyToAddress-CxEKPAKT.js +1 -0
- package/assets/{qr-code-BhW7ZXY-.js → qr-code-DaB080BF.js} +2 -2
- package/assets/{qr-overlay-DsRPQv6v.js → qr-overlay-CGnFhcTk.js} +1 -1
- package/assets/{recycle-horizontal-DBnWoDRV.js → recycle-horizontal-CGeFmMrT.js} +2 -2
- package/assets/redux-BNDF-Lt-.js +1 -0
- package/assets/{refresh-qvocxvcf.js → refresh-Dgvxxw5C.js} +2 -2
- package/assets/remoteEntry.js +1 -0
- package/assets/{reown-logo-C-45v-AJ.js → reown-logo-CBX48aN9.js} +2 -2
- package/assets/resolveImplementation-Cb2bL1tx.js +1 -0
- package/assets/rich-text-react-renderer.es5-D_tE7AHo.js +2 -0
- package/assets/rpc-ti0b0r_u.js +3 -0
- package/assets/search-DamXBOxM.js +8 -0
- package/assets/secp256k1-UEF-yOzn.js +1 -0
- package/assets/{send-DI2x4DfJ.js → send-BLpUSx_G.js} +2 -2
- package/assets/send-batch-transaction-DnH876GL.js +1 -0
- package/assets/send-eip712-transaction-D_FU-Avh.js +2 -0
- package/assets/send-gasless-transaction-MP1Q_mLW.js +2 -0
- package/assets/serializeTransaction-mtsVBaO6.js +1 -0
- package/assets/session-proposal-CM3P7DaL.js +1 -0
- package/assets/session-request-Dqw67u3p.js +2 -0
- package/assets/sha256-DYtpy1Qz.js +1 -0
- package/assets/signing-BFeVjjPi.js +5 -0
- package/assets/store-DOLZnwHk.js +1 -0
- package/assets/{swapHorizontal-eTjjU7d8.js → swapHorizontal-Br-MZ1tO.js} +2 -2
- package/assets/{swapHorizontalBold-B86nJTAP.js → swapHorizontalBold-CkUNbZ1G.js} +2 -2
- package/assets/{swapHorizontalMedium-CNT7ELrN.js → swapHorizontalMedium-D3qEQNb5.js} +2 -2
- package/assets/{swapHorizontalRoundedBold-R_inXmIh.js → swapHorizontalRoundedBold-CzzBPCtt.js} +2 -2
- package/assets/{swapVertical-DBChOUj8.js → swapVertical-Mrn3zm_W.js} +2 -2
- package/assets/{telegram-DjYbgHgS.js → telegram-ZTLC9FiA.js} +2 -2
- package/assets/thirdweb-CHfVLLbM.js +1 -0
- package/assets/thirdweb-D5ezTmuN.js +27 -0
- package/assets/{three-dots-VoULPGrI.js → three-dots-DYl4uQjm.js} +2 -2
- package/assets/totalSupply-B5jHW8gx.js +1 -0
- package/assets/tslib.es6-DbvBTznf.js +1 -0
- package/assets/{twitch-ETBgqGHE.js → twitch-DPLkA98Q.js} +2 -2
- package/assets/{twitterIcon-N584dzfh.js → twitterIcon-BEY_UAyG.js} +2 -2
- package/assets/uid-D00jCazq.js +44 -0
- package/assets/{uint8-array-CjVHUazS.js → uint8-array-DZKEMhA1.js} +1 -1
- package/assets/utils-C7urdXtO.js +2 -0
- package/assets/utils-CozXUO91.js +1 -0
- package/assets/{verify-Dp4bztGk.js → verify-DuPdiufm.js} +2 -2
- package/assets/{verify-filled-B7WhO3Kn.js → verify-filled-CdqEW5AP.js} +2 -2
- package/assets/{w3m-modal-BmEHfmEu.js → w3m-modal-BLzhBUlF.js} +34 -34
- package/assets/wait-for-tx-receipt-B-o5aPQ8.js +1 -0
- package/assets/{wallet-tXSvlbUa.js → wallet-CZw1g3L8.js} +2 -2
- package/assets/{wallet-placeholder-B2e9Wl_u.js → wallet-placeholder-OAkoJuru.js} +2 -2
- package/assets/{walletconnect-D70wSjLs.js → walletconnect-BJ3w7-IU.js} +4 -4
- package/assets/wallets-Q5RcRyG6.js +16 -0
- package/assets/{warning-circle-CsTkZ4Rl.js → warning-circle-DpDeOZKv.js} +2 -2
- package/assets/web-connector-CB7tpRui.js +9 -0
- package/assets/webSocket-dQW3n9NM.js +3 -0
- package/assets/withCache-DYumIHzL.js +1 -0
- package/assets/{x-DwOCQuex.js → x-liJqLZUi.js} +2 -2
- package/assets/zora-sepolia-DNJ2DQat.js +1 -0
- package/index.html +17 -3
- package/package.json +3 -3
- package/assets/RoobertPRO-Bold-BLoSpx-h.otf +0 -0
- package/assets/all-wallets-C5N9p7Oh.js +0 -6
- package/assets/arrow-bottom-CXaxVEeb.js +0 -8
- package/assets/arrow-left-pgI3hg3C.js +0 -8
- package/assets/arrow-right-CyKp2yFa.js +0 -8
- package/assets/arrow-top-B2waxVPx.js +0 -8
- package/assets/auto-track-BvFI9h3i.js +0 -1
- package/assets/biconomy-DZsFbmF0.js +0 -1
- package/assets/ccip-CpLmER95.js +0 -1
- package/assets/chains-BJ1WS73W.js +0 -1
- package/assets/chevron-bottom-C2aa3E9i.js +0 -8
- package/assets/chevron-left-jGoftk_A.js +0 -8
- package/assets/chevron-right-Dt6SfcNy.js +0 -8
- package/assets/chevron-top-CBCgyIVe.js +0 -8
- package/assets/close-BQpWkcd5.js +0 -8
- package/assets/common-B5-2TPMC.js +0 -1
- package/assets/controller-BW9fJMCh.js +0 -2
- package/assets/core-f4taWsy5.js +0 -908
- package/assets/create-submenu-DEFVbrc5.png +0 -0
- package/assets/createBundlerClient-r1Kofl9Y.js +0 -8
- package/assets/cursor-l_ly71I2.js +0 -3
- package/assets/decimals-BB5yEnWu.js +0 -1
- package/assets/decimals-D7yTLBH-.js +0 -1
- package/assets/detectExtension-BOyq5ueD.js +0 -1
- package/assets/engine-COatTZhI.js +0 -1
- package/assets/estimate-l1-fee-gm3XrWSf.js +0 -1
- package/assets/eth_estimateGas-A6ba-Fl3.js +0 -1
- package/assets/eth_getStorageAt-DiqyV3Wq.js +0 -1
- package/assets/eth_getTransactionCount-CF50onAO.js +0 -1
- package/assets/ethereum-Bb-GI0c-.js +0 -1
- package/assets/events-CjOrSHaz.js +0 -1
- package/assets/explore-submenu-KVl6Dc-h.png +0 -0
- package/assets/external-link-C6RRSRES.js +0 -8
- package/assets/extractIPFS-BchHnCEN.js +0 -1
- package/assets/fetchTokenMetadata-ClRC5ORW.js +0 -2
- package/assets/get-ecosystem-wallet-info-C2CJ_2OU.js +0 -1
- package/assets/getBalance-DGuxWuYL.js +0 -1
- package/assets/getInstalledModules-A3tAP18V.js +0 -1
- package/assets/getNFT-C7cllYFm.js +0 -1
- package/assets/getNFT-CQKD7QHk.js +0 -2
- package/assets/governance-submenu-CXxLX9nT.png +0 -0
- package/assets/hashTypedData-7WNMs5EV.js +0 -1
- package/assets/in-app-wallet-calls-CIRR0eJZ.js +0 -1
- package/assets/index-B1P0UjN9.js +0 -1
- package/assets/index-BNdVKnva.js +0 -2
- package/assets/index-BtvcwkC4.js +0 -1
- package/assets/index-C3CMrfih.js +0 -1
- package/assets/index-C8ynIJrk.js +0 -395
- package/assets/index-Ca6sys5l.js +0 -3
- package/assets/index-CvqvWWYJ.js +0 -2
- package/assets/index-CxA55UWl.js +0 -1
- package/assets/index-D-W42D03.js +0 -12
- package/assets/index-DC9TKWAz.js +0 -23
- package/assets/index-DFfsl0Io.js +0 -4
- package/assets/index-DN2JqH-l.js +0 -895
- package/assets/index-DfqIHbWG.js +0 -2
- package/assets/index-pQ6ZXw4u.js +0 -13
- package/assets/index-qMD90g0X.js +0 -1
- package/assets/index.es-B2O4h03u.js +0 -12
- package/assets/index.es-BEAksKXY.js +0 -2
- package/assets/index.es-Dxxm_SKC.js +0 -1
- package/assets/index.es-MXG0VeeZ.js +0 -27
- package/assets/index.umd-DvfMpbcY.js +0 -1
- package/assets/is-plan-event-enabled-DS1Agtkw.js +0 -1
- package/assets/learn-submenu-Xs1jOwfy.png +0 -0
- package/assets/localBatchGatewayRequest-CHeIulW5.js +0 -1
- package/assets/marketplace-submenu-CjxTqNhj.png +0 -0
- package/assets/off-BCDn43Xl.js +0 -8
- package/assets/openzeppelin-_xpy9vRo.js +0 -1
- package/assets/ownerOf-ClSM4brX.js +0 -1
- package/assets/parseNft-BmEusGKu.js +0 -2
- package/assets/passkeys-CqFedyqV.js +0 -1
- package/assets/resolveImplementation-BssH7H5b.js +0 -1
- package/assets/rpc-DMtarHL0.js +0 -3
- package/assets/search-CAzZVrZw.js +0 -8
- package/assets/secp256k1-C_4ya0Qz.js +0 -1
- package/assets/secp256k1-CnKxz2gu.js +0 -1
- package/assets/secp256k1-oGq0B4P7.js +0 -1
- package/assets/send-batch-transaction-DfUNUZ4Z.js +0 -1
- package/assets/send-eip712-transaction-Ro5QmOlW.js +0 -2
- package/assets/send-gasless-transaction-B-Uu5KdW.js +0 -2
- package/assets/session-proposal-CRjqbz7W.js +0 -1
- package/assets/session-request-BI3BlMfs.js +0 -2
- package/assets/sha256-ChRob2fv.js +0 -1
- package/assets/signing-B1K_Jdsm.js +0 -30
- package/assets/thirdweb-0Fl_ECmE.js +0 -27
- package/assets/thirdweb-DZ2vK6IO.js +0 -1
- package/assets/totalSupply-ClM38QOc.js +0 -1
- package/assets/utils-B3vUvlNq.js +0 -1
- package/assets/wait-for-tx-receipt-pc2BJc62.js +0 -1
- package/assets/wallets-Dj6CY1yi.js +0 -17
- package/assets/web-connector-CiZO9RvI.js +0 -9
- package/assets/zora-sepolia-CZ4Tf1UH.js +0 -1
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const __vite__fileDeps=["assets/core-Bn8Mr-tS.js","assets/preload-helper-BorDCKdG.js","assets/events-B5inrCVE.js","assets/_commonjsHelpers-C4iS2aBk.js","assets/index.es-D3pP9hN4.js","assets/index-nibyPLVP.js","assets/__federation_fn_import-C51lglKS.js","assets/index.es-D5YKsq2-.js"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]);
|
|
2
|
+
import{_ as uc}from"./preload-helper-BorDCKdG.js";import{e as _t,N as Nr}from"./events-B5inrCVE.js";import{importShared as pc}from"./__federation_fn_import-C51lglKS.js";import{d as Wr,g as dc,e as N,h as hi,C as gc,j as zo,l as fc,m as mc,n as Xs,q as Ji,b as ds,s as Rr,I as yi,k as bs,A as yc,E as Pe,r as wc,y as ke,a as Tt,t as wi,O as Tr,o as ze,u as bc,v as qr,w as jr,f as vs,P as Jr,Q as vc,x as Ec,z as ri,c as Ko,B as ht,D as it,F as ft}from"./index.es-D3pP9hN4.js";import{c as Ic,a as _c,k as Pc,d as $c,s as Sc,g as Qr}from"./index-nibyPLVP.js";import{f as Qe}from"./index.es-D5YKsq2-.js";function Oc(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),u=l.charCodeAt(0);if(e[u]!==255)throw new TypeError(l+" is ambiguous");e[u]=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,u=0,p=0;const d=h.length;for(;p!==d&&h[p]===0;)p++,l++;const g=(d-p)*n+1>>>0,m=new Uint8Array(g);for(;p!==d;){let y=h[p],b=0;for(let _=g-1;(y!==0||b<u)&&_!==-1;_--,b++)y+=256*m[_]>>>0,m[_]=y%t>>>0,y=y/t>>>0;if(y!==0)throw new Error("Non-zero carry");u=b,p++}let f=g-u;for(;f!==g&&m[f]===0;)f++;let w=s.repeat(l);for(;f<g;++f)w+=i.charAt(m[f]);return w}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,u=0,p=0;for(;h[l]===s;)u++,l++;const d=(h.length-l)*r+1>>>0,g=new Uint8Array(d);for(;l<h.length;){const y=h.charCodeAt(l);if(y>255)return;let b=e[y];if(b===255)return;let _=0;for(let x=d-1;(b!==0||_<p)&&x!==-1;x--,_++)b+=t*g[x]>>>0,g[x]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");p=_,l++}let m=d-p;for(;m!==d&&g[m]===0;)m++;const f=new Uint8Array(u+(d-m));let w=u;for(;m!==d;)f[w++]=g[m++];return f}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 Ac="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const xc=Oc(Ac);function Vo(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Ri(i,e){e||(e=i.reduce((r,n)=>r+n.length,0));const t=Vo(e);let s=0;for(const r of i)t.set(r,s),s+=r.length;return t}function Ho(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Yr=Ho("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),xs=Ho("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=Vo(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),Fo={utf8:Yr,"utf-8":Yr,hex:Wr.base16,latin1:xs,ascii:xs,binary:xs,...Wr};function Be(i,e="utf8"){const t=Fo[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}`)}function xe(i,e="utf8"){const t=Fo[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.buffer,i.byteOffset,i.byteLength).toString("utf8"):t.encoder.encode(i).substring(1)}var Cc={};const{recoverAddress:Nc}=await pc("viem"),Rc=":";function ci(i){const[e,t]=i.split(Rc);return{namespace:e,reference:t}}function Zr(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 Go(i,e){return i.includes(":")?[i]:e.chains||[]}var Tc=Object.defineProperty,qc=Object.defineProperties,jc=Object.getOwnPropertyDescriptors,Xr=Object.getOwnPropertySymbols,Dc=Object.prototype.hasOwnProperty,kc=Object.prototype.propertyIsEnumerable,en=(i,e,t)=>e in i?Tc(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,tn=(i,e)=>{for(var t in e||(e={}))Dc.call(e,t)&&en(i,t,e[t]);if(Xr)for(var t of Xr(e))kc.call(e,t)&&en(i,t,e[t]);return i},Mc=(i,e)=>qc(i,jc(e));const Uc="ReactNative",je={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Lc="js";function gs(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Pt(){return!hi()&&!!zo()&&navigator.product===Uc}function Bc(){return Pt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function zc(){return Pt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function bi(){return!gs()&&!!zo()&&!!hi()}function Bi(){return Pt()?je.reactNative:gs()?je.node:bi()?je.browser:je.unknown}function sn(){var i;try{return Pt()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(i=global.Application)==null?void 0:i.applicationId:void 0}catch{return}}function Kc(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 Vc(i){var e,t;const s=Wo();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?.icons)!=null&&e.length&&i.icons.length>0&&(i.icons=i.icons.filter(r=>r!=="")),Mc(tn(tn({},s),i),{url:i?.url||s.url,name:i?.name||s.name,description:i?.description||s.description,icons:(t=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 Wo(){return dc()||{name:"",description:"",url:"",icons:[""]}}function Hc(){if(Bi()===je.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:t,Version:s}=global.Platform;return[t,s].join("-")}const i=fc();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 Fc(){var i;const e=Bi();return e===je.browser?[e,((i=mc())==null?void 0:i.host)||"unknown"].join(":"):e}function Jo(i,e,t){const s=Hc(),r=Fc();return[[i,e].join("-"),[Lc,t].join("-"),s,r].join("/")}function Gc({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Jo(i,e,s),u={auth:r,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=Kc(h[1]||"",u);return h[0]+"?"+p}function qt(i,e){return i.filter(t=>e.includes(t)).length===i.length}function er(i){return Object.fromEntries(i.entries())}function tr(i){return new Map(Object.entries(i))}function At(i=N.FIVE_MINUTES,e){const t=N.toMiliseconds(i||N.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 vt(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 Qo(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 Wc(i){return Qo("topic",i)}function Jc(i){return Qo("id",i)}function Yo(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 ae(i,e){return N.fromMiliseconds(Date.now()+N.toMiliseconds(i))}function wt(i){return Date.now()>=N.toMiliseconds(i)}function W(i,e){return`${i}${e?`:${e}`:""}`}function rt(i=[],e=[]){return[...new Set([...i,...e])]}async function Qc({id:i,topic:e,wcDeepLink:t}){var s;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r?.href;if(typeof n!="string")return;const o=Yc(n,i,e),a=Bi();if(a===je.browser){if(!((s=hi())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Zc(o)}else a===je.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(r){console.error(r)}}function Yc(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}${ih(s,!0)}`}else r=`${r}/wc?${s}`;return r}function Zc(i){let e="_self";th()?e="_top":(eh()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function Xc(i,e){let t="";try{if(bi()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function rn(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function nn(){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 Dr(){return typeof process<"u"&&Cc.IS_VITEST==="true"}function eh(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function th(){try{return window.self!==window.top}catch{return!1}}function ih(i,e=!1){const t=Buffer.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Zo(i){return Buffer.from(i,"base64").toString("utf-8")}function sh(i){return new Promise(e=>setTimeout(e,i))}function Di(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function rh(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function zi(i,...e){if(!rh(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 kr(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Di(i.outputLen),Di(i.blockLen)}function li(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 Xo(i,e){zi(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Qi=BigInt(2**32-1),on=BigInt(32);function nh(i,e=!1){return e?{h:Number(i&Qi),l:Number(i>>on&Qi)}:{h:Number(i>>on&Qi)|0,l:Number(i&Qi)|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}=nh(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const ah=(i,e,t)=>i<<t|e>>>32-t,ch=(i,e,t)=>e<<t|i>>>32-t,hh=(i,e,t)=>e<<t-32|i>>>64-t,lh=(i,e,t)=>i<<t-32|e>>>64-t,zt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function uh(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Cs(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Ze(i,e){return i<<32-e|i>>>e}const an=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ph(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function cn(i){for(let e=0;e<i.length;e++)i[e]=ph(i[e])}function dh(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function ui(i){return typeof i=="string"&&(i=dh(i)),zi(i),i}function gh(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];zi(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 Mr=class{clone(){return this._cloneInto()}};function ea(i){const e=s=>i().update(ui(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function vi(i=32){if(zt&&typeof zt.getRandomValues=="function")return zt.getRandomValues(new Uint8Array(i));if(zt&&typeof zt.randomBytes=="function")return zt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const ta=[],ia=[],sa=[],fh=BigInt(0),_i=BigInt(1),mh=BigInt(2),yh=BigInt(7),wh=BigInt(256),bh=BigInt(113);for(let i=0,e=_i,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],ta.push(2*(5*s+t)),ia.push((i+1)*(i+2)/2%64);let r=fh;for(let n=0;n<7;n++)e=(e<<_i^(e>>yh)*bh)%wh,e&mh&&(r^=_i<<(_i<<BigInt(n))-_i);sa.push(r)}const[vh,Eh]=oh(sa,!0),hn=(i,e,t)=>t>32?hh(i,e,t):ah(i,e,t),ln=(i,e,t)=>t>32?lh(i,e,t):ch(i,e,t);function Ih(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],u=hn(h,l,1)^t[a],p=ln(h,l,1)^t[a+1];for(let d=0;d<50;d+=10)i[o+d]^=u,i[o+d+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=ia[o],c=hn(r,n,a),h=ln(r,n,a),l=ta[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]^=vh[s],i[1]^=Eh[s]}t.fill(0)}let _h=class ra extends Mr{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,Di(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=uh(this.state)}keccak(){an||cn(this.state32),Ih(this.state32,this.rounds),an||cn(this.state32),this.posOut=0,this.pos=0}update(e){li(this);const{blockLen:t,state:s}=this;e=ui(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){li(this,!1),zi(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 Di(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Xo(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 ra(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 Ph=(i,e,t)=>ea(()=>new _h(e,i,t)),$h=Ph(1,136,256/8),Sh="https://rpc.walletconnect.org/v1";function na(i){const e=`Ethereum Signed Message:
|
|
3
|
+
${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+Buffer.from($h(t)).toString("hex")}async function Oh(i,e,t,s,r,n){switch(t.t){case"eip191":return await Ah(i,e,t.s);case"eip1271":return await xh(i,e,t.s,s,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function Ah(i,e,t){return(await Nc({hash:na(e),signature:t})).toLowerCase()===i.toLowerCase()}async function xh(i,e,t,s,r,n){const o=ci(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),u=na(e).substring(2),p=a+u+c+h+l,d=await fetch(`${n||Sh}/?chainId=${s}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:Ch(),jsonrpc:"2.0",method:"eth_call",params:[{to:i,data:p},"latest"]})}),{result:g}=await d.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Ch(){return Date.now()+Math.floor(Math.random()*1e3)}function Nh(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=Buffer.from(i,"base64").slice(1,65);return xc.encode(n)}var Rh=Object.defineProperty,Th=Object.defineProperties,qh=Object.getOwnPropertyDescriptors,un=Object.getOwnPropertySymbols,jh=Object.prototype.hasOwnProperty,Dh=Object.prototype.propertyIsEnumerable,pn=(i,e,t)=>e in i?Rh(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,kh=(i,e)=>{for(var t in e||(e={}))jh.call(e,t)&&pn(i,t,e[t]);if(un)for(var t of un(e))Dh.call(e,t)&&pn(i,t,e[t]);return i},Mh=(i,e)=>Th(i,qh(e));const Uh="did:pkh:",Ur=i=>i?.split(":"),Lh=i=>{const e=i&&Ur(i);if(e)return i.includes(Uh)?e[3]:e[1]},ir=i=>{const e=i&&Ur(i);if(e)return e[2]+":"+e[3]},fs=i=>{const e=i&&Ur(i);if(e)return e.pop()};async function dn(i){const{cacao:e,projectId:t}=i,{s,p:r}=e,n=oa(r,r.iss),o=fs(r.iss);return await Oh(o,n,s,ir(r.iss),t)}const oa=(i,e)=>{const t=`${i.domain} wants you to sign in with your Ethereum account:`,s=fs(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: ${Lh(e)}`,c=`Nonce: ${i.nonce}`,h=`Issued At: ${i.iat}`,l=i.exp?`Expiration Time: ${i.exp}`:void 0,u=i.nbf?`Not Before: ${i.nbf}`:void 0,p=i.requestId?`Request ID: ${i.requestId}`:void 0,d=i.resources?`Resources:${i.resources.map(m=>`
|
|
4
|
+
- ${m}`).join("")}`:void 0,g=as(i.resources);if(g){const m=ki(g);r=Jh(r,m)}return[t,s,"",r,"",n,o,a,c,h,l,u,p,d].filter(m=>m!=null).join(`
|
|
5
|
+
`)};function Bh(i){return Buffer.from(JSON.stringify(i)).toString("base64")}function zh(i){return JSON.parse(Buffer.from(i,"base64").toString("utf-8"))}function Dt(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 Kh(i,e,t,s={}){return t?.sort((r,n)=>r.localeCompare(n)),{att:{[i]:Vh(e,t,s)}}}function Vh(i,e,t={}){e=e?.sort((r,n)=>r.localeCompare(n));const s=e.map(r=>({[`${i}/${r}`]:[t]}));return Object.assign({},...s)}function aa(i){return Dt(i),`urn:recap:${Bh(i).replace(/=/g,"")}`}function ki(i){const e=zh(i.replace("urn:recap:",""));return Dt(e),e}function Hh(i,e,t){const s=Kh(i,e,t);return aa(s)}function Fh(i){return i&&i.includes("urn:recap:")}function Gh(i,e){const t=ki(i),s=ki(e),r=Wh(t,s);return aa(r)}function Wh(i,e){Dt(i),Dt(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]=Mh(kh({},s.att[r]),{[a]:((c=i.att[r])==null?void 0:c[a])||((h=e.att[r])==null?void 0:h[a])})})}),s}function Jh(i="",e){Dt(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(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,p)=>u.action.localeCompare(p.action));const h={};c.forEach(u=>{h[u.ability]||(h[u.ability]=[]),h[u.ability].push(u.action)});const l=Object.keys(h).map(u=>(r++,`(${r}) '${u}': '${h[u].join("', '")}' for '${a}'.`));s.push(l.join(", ").replace(".,","."))});const n=s.join(" "),o=`${t}${n}`;return`${i?i+" ":""}${o}`}function gn(i){var e;const t=ki(i);Dt(t);const s=(e=t.att)==null?void 0:e.eip155;return s?Object.keys(s).map(r=>r.split("/")[1]):[]}function fn(i){const e=ki(i);Dt(e);const t=[];return Object.values(e.att).forEach(s=>{Object.values(s).forEach(r=>{var n;(n=r?.[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function as(i){if(!i)return;const e=i?.[i.length-1];return Fh(e)?e:void 0}function Ns(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function ca(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function qe(i,...e){if(!ca(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 mn(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 Qh(i,e){qe(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function yn(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const Et=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),Yh=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Zh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Zh)throw new Error("Non little-endian hardware is not supported");function Xh(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function sr(i){if(typeof i=="string")i=Xh(i);else if(ca(i))i=rr(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 tl(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 il=(i,e)=>{function t(s,...r){if(qe(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?qe(h):qe(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&qe(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");qe(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,qe(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(qe(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 wn(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&&!sl(e))throw new Error("invalid output, must be aligned");return e}function bn(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 sl(i){return i.byteOffset%4===0}function rr(i){return Uint8Array.from(i)}function pi(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const ha=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),rl=ha("expand 16-byte k"),nl=ha("expand 32-byte k"),ol=Et(rl),al=Et(nl);function V(i,e){return i<<e|i>>>32-e}function nr(i){return i.byteOffset%4===0}const Yi=64,cl=16,la=2**32-1,vn=new Uint32Array;function hl(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(Yi),l=Et(h),u=nr(r)&&nr(n),p=u?Et(r):vn,d=u?Et(n):vn;for(let g=0;g<c;o++){if(i(e,t,s,l,o,a),o>=la)throw new Error("arx: counter overflow");const m=Math.min(Yi,c-g);if(u&&m===Yi){const f=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,y;w<cl;w++)y=f+w,d[y]=p[y]^l[w];g+=Yi;continue}for(let f=0,w;f<m;f++)w=g+f,n[w]=r[w]^h[f];g+=m}}function ll(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 Ns(r),Ns(o),yn(n),yn(t),(a,c,h,l,u=0)=>{qe(a),qe(c),qe(h);const p=h.length;if(l===void 0&&(l=new Uint8Array(p)),qe(l),Ns(u),u<0||u>=la)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const d=[];let g=a.length,m,f;if(g===32)d.push(m=rr(a)),f=al;else if(g===16&&t)m=new Uint8Array(32),m.set(a),m.set(a,16),f=ol,d.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);nr(c)||d.push(c=rr(c));const w=Et(m);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(f,w,Et(c.subarray(0,16)),w),c=c.subarray(16)}const y=16-r;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const _=new Uint8Array(12);_.set(c,n?0:12-c.length),c=_,d.push(c)}const b=Et(c);return hl(i,f,w,b,h,l,u,o),pi(...d),l}}const fe=(i,e)=>i[e++]&255|(i[e++]&255)<<8;class ul{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=sr(e),qe(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],u=o[4],p=o[5],d=o[6],g=o[7],m=o[8],f=o[9],w=fe(e,t+0),y=fe(e,t+2),b=fe(e,t+4),_=fe(e,t+6),x=fe(e,t+8),P=fe(e,t+10),S=fe(e,t+12),R=fe(e,t+14);let v=n[0]+(w&8191),k=n[1]+((w>>>13|y<<3)&8191),q=n[2]+((y>>>10|b<<6)&8191),D=n[3]+((b>>>7|_<<9)&8191),U=n[4]+((_>>>4|x<<12)&8191),I=n[5]+(x>>>1&8191),A=n[6]+((x>>>14|P<<2)&8191),O=n[7]+((P>>>11|S<<5)&8191),T=n[8]+((S>>>8|R<<8)&8191),j=n[9]+(R>>>5|r),$=0,M=$+v*a+k*(5*f)+q*(5*m)+D*(5*g)+U*(5*d);$=M>>>13,M&=8191,M+=I*(5*p)+A*(5*u)+O*(5*l)+T*(5*h)+j*(5*c),$+=M>>>13,M&=8191;let L=$+v*c+k*a+q*(5*f)+D*(5*m)+U*(5*g);$=L>>>13,L&=8191,L+=I*(5*d)+A*(5*p)+O*(5*u)+T*(5*l)+j*(5*h),$+=L>>>13,L&=8191;let B=$+v*h+k*c+q*a+D*(5*f)+U*(5*m);$=B>>>13,B&=8191,B+=I*(5*g)+A*(5*d)+O*(5*p)+T*(5*u)+j*(5*l),$+=B>>>13,B&=8191;let Z=$+v*l+k*h+q*c+D*a+U*(5*f);$=Z>>>13,Z&=8191,Z+=I*(5*m)+A*(5*g)+O*(5*d)+T*(5*p)+j*(5*u),$+=Z>>>13,Z&=8191;let G=$+v*u+k*l+q*h+D*c+U*a;$=G>>>13,G&=8191,G+=I*(5*f)+A*(5*m)+O*(5*g)+T*(5*d)+j*(5*p),$+=G>>>13,G&=8191;let ie=$+v*p+k*u+q*l+D*h+U*c;$=ie>>>13,ie&=8191,ie+=I*a+A*(5*f)+O*(5*m)+T*(5*g)+j*(5*d),$+=ie>>>13,ie&=8191;let ce=$+v*d+k*p+q*u+D*l+U*h;$=ce>>>13,ce&=8191,ce+=I*c+A*a+O*(5*f)+T*(5*m)+j*(5*g),$+=ce>>>13,ce&=8191;let ve=$+v*g+k*d+q*p+D*u+U*l;$=ve>>>13,ve&=8191,ve+=I*h+A*c+O*a+T*(5*f)+j*(5*m),$+=ve>>>13,ve&=8191;let ne=$+v*m+k*g+q*d+D*p+U*u;$=ne>>>13,ne&=8191,ne+=I*l+A*h+O*c+T*a+j*(5*f),$+=ne>>>13,ne&=8191;let oe=$+v*f+k*m+q*g+D*d+U*p;$=oe>>>13,oe&=8191,oe+=I*u+A*l+O*h+T*c+j*a,$+=oe>>>13,oe&=8191,$=($<<2)+$|0,$=$+M|0,M=$&8191,$=$>>>13,L+=$,n[0]=M,n[1]=L,n[2]=B,n[3]=Z,n[4]=G,n[5]=ie,n[6]=ce,n[7]=ve,n[8]=ne,n[9]=oe}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;pi(s)}update(e){mn(this);const{buffer:t,blockLen:s}=this;e=sr(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(){pi(this.h,this.r,this.buffer,this.pad)}digestInto(e){mn(this),Qh(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 pl(i){const e=(s,r)=>i(r).update(sr(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const dl=pl(i=>new ul(i));function gl(i,e,t,s,r,n=20){let o=i[0],a=i[1],c=i[2],h=i[3],l=e[0],u=e[1],p=e[2],d=e[3],g=e[4],m=e[5],f=e[6],w=e[7],y=r,b=t[0],_=t[1],x=t[2],P=o,S=a,R=c,v=h,k=l,q=u,D=p,U=d,I=g,A=m,O=f,T=w,j=y,$=b,M=_,L=x;for(let Z=0;Z<n;Z+=2)P=P+k|0,j=V(j^P,16),I=I+j|0,k=V(k^I,12),P=P+k|0,j=V(j^P,8),I=I+j|0,k=V(k^I,7),S=S+q|0,$=V($^S,16),A=A+$|0,q=V(q^A,12),S=S+q|0,$=V($^S,8),A=A+$|0,q=V(q^A,7),R=R+D|0,M=V(M^R,16),O=O+M|0,D=V(D^O,12),R=R+D|0,M=V(M^R,8),O=O+M|0,D=V(D^O,7),v=v+U|0,L=V(L^v,16),T=T+L|0,U=V(U^T,12),v=v+U|0,L=V(L^v,8),T=T+L|0,U=V(U^T,7),P=P+q|0,L=V(L^P,16),O=O+L|0,q=V(q^O,12),P=P+q|0,L=V(L^P,8),O=O+L|0,q=V(q^O,7),S=S+D|0,j=V(j^S,16),T=T+j|0,D=V(D^T,12),S=S+D|0,j=V(j^S,8),T=T+j|0,D=V(D^T,7),R=R+U|0,$=V($^R,16),I=I+$|0,U=V(U^I,12),R=R+U|0,$=V($^R,8),I=I+$|0,U=V(U^I,7),v=v+k|0,M=V(M^v,16),A=A+M|0,k=V(k^A,12),v=v+k|0,M=V(M^v,8),A=A+M|0,k=V(k^A,7);let B=0;s[B++]=o+P|0,s[B++]=a+S|0,s[B++]=c+R|0,s[B++]=h+v|0,s[B++]=l+k|0,s[B++]=u+q|0,s[B++]=p+D|0,s[B++]=d+U|0,s[B++]=g+I|0,s[B++]=m+A|0,s[B++]=f+O|0,s[B++]=w+T|0,s[B++]=y+j|0,s[B++]=b+$|0,s[B++]=_+M|0,s[B++]=x+L|0}const fl=ll(gl,{counterRight:!1,counterLength:4,allowShortKeys:!1}),ml=new Uint8Array(16),En=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(ml.subarray(t))},yl=new Uint8Array(32);function In(i,e,t,s,r){const n=i(e,t,yl),o=dl.create(n);r&&En(o,r),En(o,s);const a=new Uint8Array(16),c=Yh(a);bn(c,0,BigInt(r?r.length:0),!0),bn(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return pi(n,a),h}const wl=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=wn(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=In(i,e,t,a,s);return n.set(c,o),pi(c),n},decrypt(r,n){n=wn(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=In(i,e,t,o,s);if(!tl(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),pi(c),n}}),ua=il({blockSize:64,nonceLength:12,tagLength:16},wl(fl));let pa=class extends Mr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,kr(e);const s=ui(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 li(this),this.iHash.update(e),this}digestInto(e){li(this),zi(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 Es=(i,e,t)=>new pa(i,e).update(t).digest();Es.create=(i,e)=>new pa(i,e);function bl(i,e,t){return kr(i),t===void 0&&(t=new Uint8Array(i.outputLen)),Es(i,ui(t),ui(e))}const Rs=new Uint8Array([0]),_n=new Uint8Array;function vl(i,e,t,s=32){if(kr(i),Di(s),s>255*i.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(s/i.outputLen);t===void 0&&(t=_n);const n=new Uint8Array(r*i.outputLen),o=Es.create(i,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let h=0;h<r;h++)Rs[0]=h+1,a.update(h===0?_n:c).update(t).update(Rs).digestInto(c),n.set(c,i.outputLen*h),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Rs.fill(0),n.slice(0,s)}const El=(i,e,t,s,r)=>vl(i,bl(i,e,t),s,r);function Il(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 _l(i,e,t){return i&e^~i&t}function Pl(i,e,t){return i&e^i&t^e&t}let $l=class extends Mr{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=Cs(this.buffer)}update(e){li(this);const{view:t,buffer:s,blockLen:r}=this;e=ui(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=Cs(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){li(this),Xo(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 u=o;u<r;u++)t[u]=0;Il(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=Cs(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 u=0;u<h;u++)a.setUint32(4*u,l[u],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 Sl=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]),mt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),yt=new Uint32Array(64);class Ol extends $l{constructor(){super(64,32,8,!1),this.A=mt[0]|0,this.B=mt[1]|0,this.C=mt[2]|0,this.D=mt[3]|0,this.E=mt[4]|0,this.F=mt[5]|0,this.G=mt[6]|0,this.H=mt[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 u=0;u<16;u++,t+=4)yt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=yt[u-15],d=yt[u-2],g=Ze(p,7)^Ze(p,18)^p>>>3,m=Ze(d,17)^Ze(d,19)^d>>>10;yt[u]=m+yt[u-7]+g+yt[u-16]|0}let{A:s,B:r,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let u=0;u<64;u++){const p=Ze(a,6)^Ze(a,11)^Ze(a,25),d=l+p+_l(a,c,h)+Sl[u]+yt[u]|0,g=(Ze(s,2)^Ze(s,13)^Ze(s,22))+Pl(s,r,n)|0;l=h,h=c,c=a,a=o+d|0,o=n,n=r,r=s,s=d+g|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(){yt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Ki=ea(()=>new Ol);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Is=BigInt(0),_s=BigInt(1),Al=BigInt(2);function kt(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Vi(i){if(!kt(i))throw new Error("Uint8Array expected")}function di(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const xl=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function gi(i){Vi(i);let e="";for(let t=0;t<i.length;t++)e+=xl[i[t]];return e}function ni(i){const e=i.toString(16);return e.length&1?"0"+e:e}function Lr(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?Is:BigInt("0x"+i)}const ct={_0:48,_9:57,A:65,F:70,a:97,f:102};function Pn(i){if(i>=ct._0&&i<=ct._9)return i-ct._0;if(i>=ct.A&&i<=ct.F)return i-(ct.A-10);if(i>=ct.a&&i<=ct.f)return i-(ct.a-10)}function fi(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 jt(i){return Lr(gi(i))}function Mi(i){return Vi(i),Lr(gi(Uint8Array.from(i).reverse()))}function mi(i,e){return fi(i.toString(16).padStart(e*2,"0"))}function Ps(i,e){return mi(i,e).reverse()}function Cl(i){return fi(ni(i))}function Te(i,e,t){let s;if(typeof e=="string")try{s=fi(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(kt(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 Ui(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Vi(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 Nl(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 Rl(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const Ts=i=>typeof i=="bigint"&&Is<=i;function $s(i,e,t){return Ts(i)&&Ts(e)&&Ts(t)&&e<=i&&i<t}function dt(i,e,t,s){if(!$s(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function da(i){let e;for(e=0;i>Is;i>>=_s,e+=1);return e}function Tl(i,e){return i>>BigInt(e)&_s}function ql(i,e,t){return i|(t?_s:Is)<<BigInt(e)}const Br=i=>(Al<<BigInt(i-1))-_s,qs=i=>new Uint8Array(i),$n=i=>Uint8Array.from(i);function ga(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=qs(i),r=qs(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=qs())=>{r=a($n([0]),l),s=a(),l.length!==0&&(r=a($n([1]),l),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const u=[];for(;l<e;){s=a();const p=s.slice();u.push(p),l+=s.length}return Ui(...u)};return(l,u)=>{o(),c(l);let p;for(;!(p=u(h()));)c();return o(),p}}const jl={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"||kt(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 Ei(i,e,t={}){const s=(r,n,o)=>{const a=jl[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 Dl=()=>{throw new Error("not implemented")};function or(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 kl=Object.freeze({__proto__:null,isBytes:kt,abytes:Vi,abool:di,bytesToHex:gi,numberToHexUnpadded:ni,hexToNumber:Lr,hexToBytes:fi,bytesToNumberBE:jt,bytesToNumberLE:Mi,numberToBytesBE:mi,numberToBytesLE:Ps,numberToVarBytesBE:Cl,ensureBytes:Te,concatBytes:Ui,equalBytes:Nl,utf8ToBytes:Rl,inRange:$s,aInRange:dt,bitLen:da,bitGet:Tl,bitSet:ql,bitMask:Br,createHmacDrbg:ga,validateObject:Ei,notImplemented:Dl,memoized:or});const ge=BigInt(0),te=BigInt(1),Ct=BigInt(2),Ml=BigInt(3),ar=BigInt(4),Sn=BigInt(5),On=BigInt(8);function Ae(i,e){const t=i%e;return t>=ge?t:e+t}function fa(i,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===te)return ge;let s=te;for(;e>ge;)e&te&&(s=s*i%t),i=i*i%t,e>>=te;return s}function Ge(i,e,t){let s=i;for(;e-- >ge;)s*=s,s%=t;return s}function cr(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=Ae(i,e),s=e,r=ge,n=te;for(;t!==ge;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==te)throw new Error("invert: does not exist");return Ae(r,e)}function Ul(i){const e=(i-te)/Ct;let t,s,r;for(t=i-te,s=0;t%Ct===ge;t/=Ct,s++);for(r=Ct;r<i&&fa(r,e,i)!==i-te;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+te)/ar;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+te)/Ct;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),u=o.pow(a,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let p=1;for(let g=o.sqr(u);p<c&&!o.eql(g,o.ONE);p++)g=o.sqr(g);const d=o.pow(h,te<<BigInt(c-p-1));h=o.sqr(d),l=o.mul(l,d),u=o.mul(u,h),c=p}return l}}function Ll(i){if(i%ar===Ml){const e=(i+te)/ar;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%On===Sn){const e=(i-Sn)/On;return function(t,s){const r=t.mul(s,Ct),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,Ct),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 Ul(i)}const Bl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function zl(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Bl.reduce((s,r)=>(s[r]="function",s),e);return Ei(i,t)}function Kl(i,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return i.ONE;if(t===te)return e;let s=i.ONE,r=e;for(;t>ge;)t&te&&(s=i.mul(s,r)),r=i.sqr(r),t>>=te;return s}function Vl(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 ma(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function ya(i,e,t=!1,s={}){if(i<=ge)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=ma(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:Br(r),ZERO:ge,ONE:te,create:c=>Ae(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&te)===te,neg:c=>Ae(-c,i),eql:(c,h)=>c===h,sqr:c=>Ae(c*c,i),add:(c,h)=>Ae(c+h,i),sub:(c,h)=>Ae(c-h,i),mul:(c,h)=>Ae(c*h,i),pow:(c,h)=>Kl(a,c,h),div:(c,h)=>Ae(c*cr(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>cr(c,i),sqrt:s.sqrt||(c=>(o||(o=Ll(i)),o(a,c))),invertBatch:c=>Vl(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?Ps(c,n):mi(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?Mi(c):jt(c)}});return Object.freeze(a)}function wa(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 ba(i){const e=wa(i);return e+Math.ceil(e/2)}function Hl(i,e,t=!1){const s=i.length,r=wa(e),n=ba(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?Mi(i):jt(i),a=Ae(o,e-te)+te;return t?Ps(a,r):mi(a,r)}const An=BigInt(0),Zi=BigInt(1);function js(i,e){const t=e.negate();return i?t:e}function va(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function Ds(i,e){va(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function Fl(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 Gl(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 ks=new WeakMap,Ea=new WeakMap;function Ms(i){return Ea.get(i)||1}function Wl(i,e){return{constTimeNegate:js,hasPrecomputes(t){return Ms(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>An;)s&Zi&&(r=r.add(n)),n=n.double(),s>>=Zi;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=Ds(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}=Ds(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),l=2**t,u=BigInt(t);for(let p=0;p<n;p++){const d=p*o;let g=Number(r&h);r>>=u,g>o&&(g-=l,r+=Zi);const m=d,f=d+Math.abs(g)-1,w=p%2!==0,y=g<0;g===0?c=c.add(js(w,s[m])):a=a.add(js(y,s[f]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=Ds(t,e),c=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let u=0;u<o;u++){const p=u*a;if(r===An)break;let d=Number(r&c);if(r>>=l,d>a&&(d-=h,r+=Zi),d===0)continue;let g=s[p+Math.abs(d)-1];d<0&&(g=g.negate()),n=n.add(g)}return n},getPrecomputes(t,s,r){let n=ks.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&ks.set(s,r(n))),n},wNAFCached(t,s,r){const n=Ms(t);return this.wNAF(n,this.getPrecomputes(n,t,r),s)},wNAFCachedUnsafe(t,s,r,n){const o=Ms(t);return o===1?this.unsafeLadder(t,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,r),s,n)},setWindowSize(t,s){va(s,e),Ea.set(t,s),ks.delete(t)}}}function Jl(i,e,t,s){if(Fl(t,i),Gl(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=da(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 u=h;u>=0;u-=o){c.fill(r);for(let d=0;d<s.length;d++){const g=s[d],m=Number(g>>BigInt(u)&BigInt(a));c[m]=c[m].add(t[d])}let p=r;for(let d=c.length-1,g=r;d>0;d--)g=g.add(c[d]),p=p.add(g);if(l=l.add(p),u!==0)for(let d=0;d<o;d++)l=l.double()}return l}function Ia(i){return zl(i.Fp),Ei(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ma(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Kt=BigInt(0),Us=BigInt(1);function Ql(i){return Ei(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function Yl(i){const e=Ql(i),{P:t}=e,s=y=>Ae(y,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(y=>y),c=e.powPminus2||(y=>fa(y,t-BigInt(2),t));function h(y,b,_){const x=s(y*(b-_));return b=s(b-x),_=s(_+x),[b,_]}const l=(e.a-BigInt(2))/BigInt(4);function u(y,b){dt("u",y,Kt,t),dt("scalar",b,Kt,t);const _=b,x=y;let P=Us,S=Kt,R=y,v=Us,k=Kt,q;for(let U=BigInt(r-1);U>=Kt;U--){const I=_>>U&Us;k^=I,q=h(k,P,R),P=q[0],R=q[1],q=h(k,S,v),S=q[0],v=q[1],k=I;const A=P+S,O=s(A*A),T=P-S,j=s(T*T),$=O-j,M=R+v,L=R-v,B=s(L*A),Z=s(M*T),G=B+Z,ie=B-Z;R=s(G*G),v=s(x*s(ie*ie)),P=s(O*j),S=s($*(O+s(l*$)))}q=h(k,P,R),P=q[0],R=q[1],q=h(k,S,v),S=q[0],v=q[1];const D=c(S);return s(P*D)}function p(y){return Ps(s(y),n)}function d(y){const b=Te("u coordinate",y,n);return o===32&&(b[31]&=127),Mi(b)}function g(y){const b=Te("scalar",y),_=b.length;if(_!==n&&_!==o){let x=""+n+" or "+o;throw new Error("invalid scalar, expected "+x+" bytes, got "+_)}return Mi(a(b))}function m(y,b){const _=d(b),x=g(y),P=u(_,x);if(P===Kt)throw new Error("invalid private or public key received");return p(P)}const f=p(e.Gu);function w(y){return m(y,f)}return{scalarMult:m,scalarMultBase:w,getSharedSecret:(y,b)=>m(y,b),getPublicKey:y=>w(y),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:f}}const hr=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Zl=BigInt(1),xn=BigInt(2),Xl=BigInt(3),eu=BigInt(5);BigInt(8);function tu(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=hr,o=i*i%n*i%n,a=Ge(o,xn,n)*o%n,c=Ge(a,Zl,n)*i%n,h=Ge(c,eu,n)*c%n,l=Ge(h,e,n)*h%n,u=Ge(l,t,n)*l%n,p=Ge(u,s,n)*u%n,d=Ge(p,r,n)*p%n,g=Ge(d,r,n)*p%n,m=Ge(g,e,n)*h%n;return{pow_p_5_8:Ge(m,xn,n)*i%n,b2:o}}function iu(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}const lr=Yl({P:hr,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=hr,{pow_p_5_8:t,b2:s}=tu(i);return Ae(Ge(t,Xl,e)*s,e)},adjustScalarBytes:iu,randomBytes:vi});function Cn(i){i.lowS!==void 0&&di("lowS",i.lowS),i.prehash!==void 0&&di("prehash",i.prehash)}function su(i){const e=Ia(i);Ei(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:ru,hexToBytes:nu}=kl;class ou extends Error{constructor(e=""){super(e)}}const ut={Err:ou,_tlv:{encode:(i,e)=>{const{Err:t}=ut;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=ni(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?ni(r.length/2|128):"";return ni(i)+n+r+e},decode(i,e){const{Err:t}=ut;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}=ut;if(i<pt)throw new e("integer: negative integers are not allowed");let t=ni(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}=ut;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 ru(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=ut,r=typeof i=="string"?nu(i):i;Vi(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}=ut,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},pt=BigInt(0),pe=BigInt(1);BigInt(2);const Nn=BigInt(3);BigInt(4);function au(i){const e=su(i),{Fp:t}=e,s=ya(e.n,e.nBitLength),r=e.toBytes||((m,f,w)=>{const y=f.toAffine();return Ui(Uint8Array.from([4]),t.toBytes(y.x),t.toBytes(y.y))}),n=e.fromBytes||(m=>{const f=m.subarray(1),w=t.fromBytes(f.subarray(0,t.BYTES)),y=t.fromBytes(f.subarray(t.BYTES,2*t.BYTES));return{x:w,y}});function o(m){const{a:f,b:w}=e,y=t.sqr(m),b=t.mul(y,m);return t.add(t.add(b,t.mul(m,f)),w)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return $s(m,pe,e.n)}function c(m){const{allowedPrivateKeyLengths:f,nByteLength:w,wrapPrivateKey:y,n:b}=e;if(f&&typeof m!="bigint"){if(kt(m)&&(m=gi(m)),typeof m!="string"||!f.includes(m.length))throw new Error("invalid private key");m=m.padStart(w*2,"0")}let _;try{_=typeof m=="bigint"?m:jt(Te("private key",m,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof m)}return y&&(_=Ae(_,b)),dt("private key",_,pe,b),_}function h(m){if(!(m instanceof p))throw new Error("ProjectivePoint expected")}const l=or((m,f)=>{const{px:w,py:y,pz:b}=m;if(t.eql(b,t.ONE))return{x:w,y};const _=m.is0();f==null&&(f=_?t.ONE:t.inv(b));const x=t.mul(w,f),P=t.mul(y,f),S=t.mul(b,f);if(_)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x,y:P}}),u=or(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}const{x:f,y:w}=m.toAffine();if(!t.isValid(f)||!t.isValid(w))throw new Error("bad point: x or y not FE");const y=t.sqr(w),b=o(f);if(!t.eql(y,b))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class p{constructor(f,w,y){if(this.px=f,this.py=w,this.pz=y,f==null||!t.isValid(f))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(y==null||!t.isValid(y))throw new Error("z required");Object.freeze(this)}static fromAffine(f){const{x:w,y}=f||{};if(!f||!t.isValid(w)||!t.isValid(y))throw new Error("invalid affine point");if(f instanceof p)throw new Error("projective point not allowed");const b=_=>t.eql(_,t.ZERO);return b(w)&&b(y)?p.ZERO:new p(w,y,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const w=t.invertBatch(f.map(y=>y.pz));return f.map((y,b)=>y.toAffine(w[b])).map(p.fromAffine)}static fromHex(f){const w=p.fromAffine(n(Te("pointHex",f)));return w.assertValidity(),w}static fromPrivateKey(f){return p.BASE.multiply(c(f))}static msm(f,w){return Jl(p,s,f,w)}_setWindowSize(f){g.setWindowSize(this,f)}assertValidity(){u(this)}hasEvenY(){const{y:f}=this.toAffine();if(t.isOdd)return!t.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){h(f);const{px:w,py:y,pz:b}=this,{px:_,py:x,pz:P}=f,S=t.eql(t.mul(w,P),t.mul(_,b)),R=t.eql(t.mul(y,P),t.mul(x,b));return S&&R}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:f,b:w}=e,y=t.mul(w,Nn),{px:b,py:_,pz:x}=this;let P=t.ZERO,S=t.ZERO,R=t.ZERO,v=t.mul(b,b),k=t.mul(_,_),q=t.mul(x,x),D=t.mul(b,_);return D=t.add(D,D),R=t.mul(b,x),R=t.add(R,R),P=t.mul(f,R),S=t.mul(y,q),S=t.add(P,S),P=t.sub(k,S),S=t.add(k,S),S=t.mul(P,S),P=t.mul(D,P),R=t.mul(y,R),q=t.mul(f,q),D=t.sub(v,q),D=t.mul(f,D),D=t.add(D,R),R=t.add(v,v),v=t.add(R,v),v=t.add(v,q),v=t.mul(v,D),S=t.add(S,v),q=t.mul(_,x),q=t.add(q,q),v=t.mul(q,D),P=t.sub(P,v),R=t.mul(q,k),R=t.add(R,R),R=t.add(R,R),new p(P,S,R)}add(f){h(f);const{px:w,py:y,pz:b}=this,{px:_,py:x,pz:P}=f;let S=t.ZERO,R=t.ZERO,v=t.ZERO;const k=e.a,q=t.mul(e.b,Nn);let D=t.mul(w,_),U=t.mul(y,x),I=t.mul(b,P),A=t.add(w,y),O=t.add(_,x);A=t.mul(A,O),O=t.add(D,U),A=t.sub(A,O),O=t.add(w,b);let T=t.add(_,P);return O=t.mul(O,T),T=t.add(D,I),O=t.sub(O,T),T=t.add(y,b),S=t.add(x,P),T=t.mul(T,S),S=t.add(U,I),T=t.sub(T,S),v=t.mul(k,O),S=t.mul(q,I),v=t.add(S,v),S=t.sub(U,v),v=t.add(U,v),R=t.mul(S,v),U=t.add(D,D),U=t.add(U,D),I=t.mul(k,I),O=t.mul(q,O),U=t.add(U,I),I=t.sub(D,I),I=t.mul(k,I),O=t.add(O,I),D=t.mul(U,O),R=t.add(R,D),D=t.mul(T,O),S=t.mul(A,S),S=t.sub(S,D),D=t.mul(A,U),v=t.mul(T,v),v=t.add(v,D),new p(S,R,v)}subtract(f){return this.add(f.negate())}is0(){return this.equals(p.ZERO)}wNAF(f){return g.wNAFCached(this,f,p.normalizeZ)}multiplyUnsafe(f){const{endo:w,n:y}=e;dt("scalar",f,pt,y);const b=p.ZERO;if(f===pt)return b;if(this.is0()||f===pe)return this;if(!w||g.hasPrecomputes(this))return g.wNAFCachedUnsafe(this,f,p.normalizeZ);let{k1neg:_,k1:x,k2neg:P,k2:S}=w.splitScalar(f),R=b,v=b,k=this;for(;x>pt||S>pt;)x&pe&&(R=R.add(k)),S&pe&&(v=v.add(k)),k=k.double(),x>>=pe,S>>=pe;return _&&(R=R.negate()),P&&(v=v.negate()),v=new p(t.mul(v.px,w.beta),v.py,v.pz),R.add(v)}multiply(f){const{endo:w,n:y}=e;dt("scalar",f,pe,y);let b,_;if(w){const{k1neg:x,k1:P,k2neg:S,k2:R}=w.splitScalar(f);let{p:v,f:k}=this.wNAF(P),{p:q,f:D}=this.wNAF(R);v=g.constTimeNegate(x,v),q=g.constTimeNegate(S,q),q=new p(t.mul(q.px,w.beta),q.py,q.pz),b=v.add(q),_=k.add(D)}else{const{p:x,f:P}=this.wNAF(f);b=x,_=P}return p.normalizeZ([b,_])[0]}multiplyAndAddUnsafe(f,w,y){const b=p.BASE,_=(P,S)=>S===pt||S===pe||!P.equals(b)?P.multiplyUnsafe(S):P.multiply(S),x=_(this,w).add(_(f,y));return x.is0()?void 0:x}toAffine(f){return l(this,f)}isTorsionFree(){const{h:f,isTorsionFree:w}=e;if(f===pe)return!0;if(w)return w(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:w}=e;return f===pe?this:w?w(p,this):this.multiplyUnsafe(e.h)}toRawBytes(f=!0){return di("isCompressed",f),this.assertValidity(),r(p,this,f)}toHex(f=!0){return di("isCompressed",f),gi(this.toRawBytes(f))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const d=e.nBitLength,g=Wl(p,e.endo?Math.ceil(d/2):d);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function cu(i){const e=Ia(i);return Ei(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function hu(i){const e=cu(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(I){return Ae(I,s)}function a(I){return cr(I,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=au({...e,toBytes(I,A,O){const T=A.toAffine(),j=t.toBytes(T.x),$=Ui;return di("isCompressed",O),O?$(Uint8Array.from([A.hasEvenY()?2:3]),j):$(Uint8Array.from([4]),j,t.toBytes(T.y))},fromBytes(I){const A=I.length,O=I[0],T=I.subarray(1);if(A===r&&(O===2||O===3)){const j=jt(T);if(!$s(j,pe,t.ORDER))throw new Error("Point is not on curve");const $=l(j);let M;try{M=t.sqrt($)}catch(B){const Z=B instanceof Error?": "+B.message:"";throw new Error("Point is not on curve"+Z)}const L=(M&pe)===pe;return(O&1)===1!==L&&(M=t.neg(M)),{x:j,y:M}}else if(A===n&&O===4){const j=t.fromBytes(T.subarray(0,t.BYTES)),$=t.fromBytes(T.subarray(t.BYTES,2*t.BYTES));return{x:j,y:$}}else{const j=r,$=n;throw new Error("invalid Point, expected length of "+j+", or uncompressed "+$+", got "+A)}}}),p=I=>gi(mi(I,e.nByteLength));function d(I){const A=s>>pe;return I>A}function g(I){return d(I)?o(-I):I}const m=(I,A,O)=>jt(I.slice(A,O));class f{constructor(A,O,T){this.r=A,this.s=O,this.recovery=T,this.assertValidity()}static fromCompact(A){const O=e.nByteLength;return A=Te("compactSignature",A,O*2),new f(m(A,0,O),m(A,O,2*O))}static fromDER(A){const{r:O,s:T}=ut.toSig(Te("DER",A));return new f(O,T)}assertValidity(){dt("r",this.r,pe,s),dt("s",this.s,pe,s)}addRecoveryBit(A){return new f(this.r,this.s,A)}recoverPublicKey(A){const{r:O,s:T,recovery:j}=this,$=P(Te("msgHash",A));if(j==null||![0,1,2,3].includes(j))throw new Error("recovery id invalid");const M=j===2||j===3?O+e.n:O;if(M>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=j&1?"03":"02",B=c.fromHex(L+p(M)),Z=a(M),G=o(-$*Z),ie=o(T*Z),ce=c.BASE.multiplyAndAddUnsafe(B,G,ie);if(!ce)throw new Error("point at infinify");return ce.assertValidity(),ce}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return fi(this.toDERHex())}toDERHex(){return ut.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return fi(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const w={isValidPrivateKey(I){try{return h(I),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const I=ba(e.n);return Hl(e.randomBytes(I),e.n)},precompute(I=8,A=c.BASE){return A._setWindowSize(I),A.multiply(BigInt(3)),A}};function y(I,A=!0){return c.fromPrivateKey(I).toRawBytes(A)}function b(I){const A=kt(I),O=typeof I=="string",T=(A||O)&&I.length;return A?T===r||T===n:O?T===2*r||T===2*n:I instanceof c}function _(I,A,O=!0){if(b(I))throw new Error("first arg must be private key");if(!b(A))throw new Error("second arg must be public key");return c.fromHex(A).multiply(h(I)).toRawBytes(O)}const x=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const A=jt(I),O=I.length*8-e.nBitLength;return O>0?A>>BigInt(O):A},P=e.bits2int_modN||function(I){return o(x(I))},S=Br(e.nBitLength);function R(I){return dt("num < 2^"+e.nBitLength,I,pt,S),mi(I,e.nByteLength)}function v(I,A,O=k){if(["recovered","canonical"].some(ne=>ne in O))throw new Error("sign() legacy options not supported");const{hash:T,randomBytes:j}=e;let{lowS:$,prehash:M,extraEntropy:L}=O;$==null&&($=!0),I=Te("msgHash",I),Cn(O),M&&(I=Te("prehashed msgHash",T(I)));const B=P(I),Z=h(A),G=[R(Z),R(B)];if(L!=null&&L!==!1){const ne=L===!0?j(t.BYTES):L;G.push(Te("extraEntropy",ne))}const ie=Ui(...G),ce=B;function ve(ne){const oe=x(ne);if(!u(oe))return;const $t=a(oe),ot=c.BASE.multiply(oe).toAffine(),Ye=o(ot.x);if(Ye===pt)return;const at=o($t*o(ce+Ye*Z));if(at===pt)return;let Bt=(ot.x===Ye?0:2)|Number(ot.y&pe),Wi=at;return $&&d(at)&&(Wi=g(at),Bt^=1),new f(Ye,Wi,Bt)}return{seed:ie,k2sig:ve}}const k={lowS:e.lowS,prehash:!1},q={lowS:e.lowS,prehash:!1};function D(I,A,O=k){const{seed:T,k2sig:j}=v(I,A,O),$=e;return ga($.hash.outputLen,$.nByteLength,$.hmac)(T,j)}c.BASE._setWindowSize(8);function U(I,A,O,T=q){const j=I;A=Te("msgHash",A),O=Te("publicKey",O);const{lowS:$,prehash:M,format:L}=T;if(Cn(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 j=="string"||kt(j),Z=!B&&!L&&typeof j=="object"&&j!==null&&typeof j.r=="bigint"&&typeof j.s=="bigint";if(!B&&!Z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let G,ie;try{if(Z&&(G=new f(j.r,j.s)),B){try{L!=="compact"&&(G=f.fromDER(j))}catch(at){if(!(at instanceof ut.Err))throw at}!G&&L!=="der"&&(G=f.fromCompact(j))}ie=c.fromHex(O)}catch{return!1}if(!G||$&&G.hasHighS())return!1;M&&(A=e.hash(A));const{r:ce,s:ve}=G,ne=P(A),oe=a(ve),$t=o(ne*oe),ot=o(ce*oe),Ye=c.BASE.multiplyAndAddUnsafe(ie,$t,ot)?.toAffine();return Ye?o(Ye.x)===ce:!1}return{CURVE:e,getPublicKey:y,getSharedSecret:_,sign:D,verify:U,ProjectivePoint:c,Signature:f,utils:w}}function lu(i){return{hash:i,hmac:(e,...t)=>Es(i,e,gh(...t)),randomBytes:vi}}function uu(i,e){const t=s=>hu({...i,...lu(s)});return{...t(e),create:t}}const _a=ya(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),pu=_a.create(BigInt("-3")),du=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),gu=uu({a:pu,b:du,Fp:_a,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Ki),Pa="base10",_e="base16",We="base64pad",bt="base64url",Hi="utf8",$a=0,gt=1,Fi=2,fu=0,Rn=1,Ti=12,zr=32;function mu(){const i=lr.utils.randomPrivateKey(),e=lr.getPublicKey(i);return{privateKey:xe(i,_e),publicKey:xe(e,_e)}}function ur(){const i=vi(zr);return xe(i,_e)}function yu(i,e){const t=lr.getSharedSecret(Be(i,_e),Be(e,_e)),s=El(Ki,t,void 0,void 0,zr);return xe(s,_e)}function cs(i){const e=Ki(Be(i,_e));return xe(e,_e)}function st(i){const e=Ki(Be(i,Hi));return xe(e,_e)}function Sa(i){return Be(`${i}`,Pa)}function Mt(i){return Number(xe(i,Pa))}function Oa(i){return i.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Aa(i){const e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function wu(i){const e=Sa(typeof i.type<"u"?i.type:$a);if(Mt(e)===gt&&typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof i.senderPublicKey<"u"?Be(i.senderPublicKey,_e):void 0,s=typeof i.iv<"u"?Be(i.iv,_e):vi(Ti),r=Be(i.symKey,_e),n=ua(r,s).encrypt(Be(i.message,Hi)),o=xa({type:e,sealed:n,iv:s,senderPublicKey:t});return i.encoding===bt?Oa(o):o}function bu(i){const e=Be(i.symKey,_e),{sealed:t,iv:s}=Li({encoded:i.encoded,encoding:i.encoding}),r=ua(e,s).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return xe(r,Hi)}function vu(i,e){const t=Sa(Fi),s=vi(Ti),r=Be(i,Hi),n=xa({type:t,sealed:r,iv:s});return e===bt?Oa(n):n}function Eu(i,e){const{sealed:t}=Li({encoded:i,encoding:e});return xe(t,Hi)}function xa(i){if(Mt(i.type)===Fi)return xe(Ri([i.type,i.sealed]),We);if(Mt(i.type)===gt){if(typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return xe(Ri([i.type,i.senderPublicKey,i.iv,i.sealed]),We)}return xe(Ri([i.type,i.iv,i.sealed]),We)}function Li(i){const e=(i.encoding||We)===bt?Aa(i.encoded):i.encoded,t=Be(e,We),s=t.slice(fu,Rn),r=Rn;if(Mt(s)===gt){const c=r+zr,h=c+Ti,l=t.slice(r,c),u=t.slice(c,h),p=t.slice(h);return{type:s,sealed:p,iv:u,senderPublicKey:l}}if(Mt(s)===Fi){const c=t.slice(r),h=vi(Ti);return{type:s,sealed:c,iv:h}}const n=r+Ti,o=t.slice(r,n),a=t.slice(n);return{type:s,sealed:a,iv:o}}function Iu(i,e){const t=Li({encoded:i,encoding:e?.encoding});return Ca({type:Mt(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?xe(t.senderPublicKey,_e):void 0,receiverPublicKey:e?.receiverPublicKey})}function Ca(i){const e=i?.type||$a;if(e===gt){if(typeof i?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof i?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:i?.senderPublicKey,receiverPublicKey:i?.receiverPublicKey}}function Tn(i){return i.type===gt&&typeof i.senderPublicKey=="string"&&typeof i.receiverPublicKey=="string"}function qn(i){return i.type===Fi}function _u(i){const e=Buffer.from(i.x,"base64"),t=Buffer.from(i.y,"base64");return Ri([new Uint8Array([4]),e,t])}function Pu(i,e){const[t,s,r]=i.split("."),n=Buffer.from(Aa(r),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${t}.${s}`,h=Ki(c),l=_u(e);if(!gu.verify(Ri([o,a]),h,l))throw new Error("Invalid signature");return Xs(i).payload}const $u="irn";function ms(i){return i?.relay||{protocol:$u}}function Ci(i){const e=gc[i];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${i}`);return e}function Su(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 jn(i){if(!i.includes("wc:")){const h=Zo(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:Ou(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:Su(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Ou(i){return i.startsWith("//")?i.substring(2):i}function Au(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 Dn(i){const e=new URLSearchParams,t=Au(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 Xi(i,e,t){return`${i}?wc_ev=${t}&topic=${e}`}var xu=Object.defineProperty,Cu=Object.defineProperties,Nu=Object.getOwnPropertyDescriptors,kn=Object.getOwnPropertySymbols,Ru=Object.prototype.hasOwnProperty,Tu=Object.prototype.propertyIsEnumerable,Mn=(i,e,t)=>e in i?xu(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qu=(i,e)=>{for(var t in e||(e={}))Ru.call(e,t)&&Mn(i,t,e[t]);if(kn)for(var t of kn(e))Tu.call(e,t)&&Mn(i,t,e[t]);return i},ju=(i,e)=>Cu(i,Nu(e));function Ii(i){const e=[];return i.forEach(t=>{const[s,r]=t.split(":");e.push(`${s}:${r}`)}),e}function Du(i){const e=[];return Object.values(i).forEach(t=>{e.push(...Ii(t.accounts))}),e}function ku(i,e){const t=[];return Object.values(i).forEach(s=>{Ii(s.accounts).includes(e)&&t.push(...s.methods)}),t}function Mu(i,e){const t=[];return Object.values(i).forEach(s=>{Ii(s.accounts).includes(e)&&t.push(...s.events)}),t}function Ss(i){return i.includes(":")}function oi(i){return Ss(i)?i.split(":")[0]:i}function Un(i){var e,t,s;const r={};if(!It(i))return r;for(const[n,o]of Object.entries(i)){const a=Ss(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],l=oi(n);r[l]=ju(qu({},r[l]),{chains:rt(a,(e=r[l])==null?void 0:e.chains),methods:rt(c,(t=r[l])==null?void 0:t.methods),events:rt(h,(s=r[l])==null?void 0:s.events)})}return r}function Uu(i){const e={};return 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 Ln(i,e){e=e.map(s=>s.replace("did:pkh:",""));const t=Uu(e);for(const[s,r]of Object.entries(t))r.methods?r.methods=rt(r.methods,i):r.methods=i,r.events=["chainChanged","accountsChanged"];return t}function Lu(i,e){var t,s,r,n,o,a;const c=Un(i),h=Un(e),l={},u=Object.keys(c).concat(Object.keys(h));for(const p of u)l[p]={chains:rt((t=c[p])==null?void 0:t.chains,(s=h[p])==null?void 0:s.chains),methods:rt((r=c[p])==null?void 0:r.methods,(n=h[p])==null?void 0:n.methods),events:rt((o=c[p])==null?void 0:o.events,(a=h[p])==null?void 0:a.events)};return l}const Bu={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}},zu={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}=zu[i];return{message:e?`${t} ${e}`:t,code:s}}function J(i,e){const{message:t,code:s}=Bu[i];return{message:e?`${t} ${e}`:t,code:s}}function Je(i,e){return!!Array.isArray(i)}function It(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}function we(i){return typeof i>"u"}function re(i,e){return e&&we(i)?!0:typeof i=="string"&&!!i.trim().length}function Kr(i,e){return e&&we(i)?!0:typeof i=="number"&&!isNaN(i)}function Ku(i,e){const{requiredNamespaces:t}=e,s=Object.keys(i.namespaces),r=Object.keys(t);let n=!0;return qt(r,s)?(s.forEach(o=>{const{accounts:a,methods:c,events:h}=i.namespaces[o],l=Ii(a),u=t[o];(!qt(Go(o,u),l)||!qt(u.methods,c)||!qt(u.events,h))&&(n=!1)}),n):!1}function ys(i){return re(i,!1)&&i.includes(":")?i.split(":").length===2:!1}function Vu(i){if(re(i,!1)&&i.includes(":")){const e=i.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&ys(t)}}return!1}function Hu(i){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(re(i,!1)){if(e(i))return!0;const t=Zo(i);return e(t)}}catch{}return!1}function Fu(i){var e;return(e=i?.proposer)==null?void 0:e.publicKey}function Gu(i){return i?.topic}function Wu(i,e){let t=null;return re(i?.publicKey,!1)||(t=C("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function Bn(i){let e=!0;return Je(i)?i.length&&(e=i.every(t=>re(t,!1))):e=!1,e}function Ju(i,e,t){let s=null;return Je(e)&&e.length?e.forEach(r=>{s||ys(r)||(s=J("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):ys(i)||(s=J("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 Qu(i,e,t){let s=null;return Object.entries(i).forEach(([r,n])=>{if(s)return;const o=Ju(r,Go(r,n),`${e} ${t}`);o&&(s=o)}),s}function Yu(i,e){let t=null;return Je(i)?i.forEach(s=>{t||Vu(s)||(t=J("UNSUPPORTED_ACCOUNTS",`${e}, account ${s} should be a string and conform to "namespace:chainId:address" format`))}):t=J("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function Zu(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=Yu(s?.accounts,`${e} namespace`);r&&(t=r)}),t}function Xu(i,e){let t=null;return Bn(i?.methods)?Bn(i?.events)||(t=J("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=J("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function Na(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=Xu(s,`${e}, namespace`);r&&(t=r)}),t}function ep(i,e,t){let s=null;if(i&&It(i)){const r=Na(i,e);r&&(s=r);const n=Qu(i,e,t);n&&(s=n)}else s=C("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return s}function Ls(i,e){let t=null;if(i&&It(i)){const s=Na(i,e);s&&(t=s);const r=Zu(i,e);r&&(t=r)}else t=C("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Ra(i){return re(i.protocol,!0)}function tp(i,e){let t=!1;return i?i&&Je(i)&&i.length&&i.forEach(s=>{t=Ra(s)}):t=!0,t}function ip(i){return typeof i=="number"}function Oe(i){return typeof i<"u"&&typeof i!==null}function sp(i){return!(!i||typeof i!="object"||!i.code||!Kr(i.code,!1)||!i.message||!re(i.message,!1))}function rp(i){return!(we(i)||!re(i.method,!1))}function np(i){return!(we(i)||we(i.result)&&we(i.error)||!Kr(i.id,!1)||!re(i.jsonrpc,!1))}function op(i){return!(we(i)||!re(i.name,!1))}function zn(i,e){return!(!ys(e)||!Du(i).includes(e))}function ap(i,e,t){return re(t,!1)?ku(i,e).includes(t):!1}function cp(i,e,t){return re(t,!1)?Mu(i,e).includes(t):!1}function Kn(i,e,t){let s=null;const r=hp(i),n=lp(e),o=Object.keys(r),a=Object.keys(n),c=Vn(Object.keys(i)),h=Vn(Object.keys(e)),l=c.filter(u=>!h.includes(u));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()}`)),qt(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(u=>{if(!u.includes(":")||s)return;const p=Ii(e[u].accounts);p.includes(u)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${u}
|
|
10
|
+
Required: ${u}
|
|
11
|
+
Approved: ${p.toString()}`))}),o.forEach(u=>{s||(qt(r[u].methods,n[u].methods)?qt(r[u].events,n[u].events)||(s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):s=C("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),s}function hp(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 Vn(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function lp(i){const e={};return Object.keys(i).forEach(t=>{t.includes(":")?e[t]=i[t]:Ii(i[t].accounts)?.forEach(r=>{e[r]={accounts:i[t].accounts.filter(n=>n.includes(`${r}:`)),methods:i[t].methods,events:i[t].events}})}),e}function up(i,e){return Kr(i,!1)&&i<=e.max&&i>=e.min}function Hn(){const i=Bi();return new Promise(e=>{switch(i){case je.browser:e(pp());break;case je.reactNative:e(dp());break;case je.node:e(gp());break;default:e(!0)}})}function pp(){return bi()&&navigator?.onLine}async function dp(){return Pt()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function gp(){return!0}function fp(i){switch(Bi()){case je.browser:mp(i);break;case je.reactNative:yp(i);break}}function mp(i){!Pt()&&bi()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function yp(i){Pt()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>i(e?.isConnected))}function wp(){var i;return bi()&&hi()?((i=hi())==null?void 0:i.visibilityState)==="visible":!0}const Bs={};class Pi{static get(e){return Bs[e]}static set(e,t){Bs[e]=t}static delete(e){delete Bs[e]}}function bp(i){return!i||typeof i.then!="function"?Promise.resolve(i):i}function ue(i,...e){try{return bp(i(...e))}catch(t){return Promise.reject(t)}}function vp(i){const e=typeof i;return i===null||e!=="object"&&e!=="function"}function Ep(i){const e=Object.getPrototypeOf(i);return!e||e.isPrototypeOf(Object)}function hs(i){if(vp(i))return String(i);if(Ep(i)||Array.isArray(i))return JSON.stringify(i);if(typeof i.toJSON=="function")return hs(i.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const pr="base64:";function Ip(i){return typeof i=="string"?i:pr+$p(i)}function _p(i){return typeof i!="string"||!i.startsWith(pr)?i:Pp(i.slice(pr.length))}function Pp(i){return globalThis.Buffer?Buffer.from(i,"base64"):Uint8Array.from(globalThis.atob(i),e=>e.codePointAt(0))}function $p(i){return globalThis.Buffer?Buffer.from(i).toString("base64"):globalThis.btoa(String.fromCodePoint(...i))}function Se(i){return i&&i.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Sp(...i){return Se(i.join(":"))}function es(i){return i=Se(i),i?i+":":""}function Op(i,e){if(e===void 0)return!0;let t=0,s=i.indexOf(":");for(;s>-1;)t++,s=i.indexOf(":",s+1);return t<=e}function Ap(i,e){return e?i.startsWith(e)&&i[i.length-1]!=="$":i[i.length-1]!=="$"}const xp="memory",Cp=()=>{const i=new Map;return{name:xp,getInstance:()=>i,hasItem(e){return i.has(e)},getItem(e){return i.get(e)??null},getItemRaw(e){return i.get(e)??null},setItem(e,t){i.set(e,t)},setItemRaw(e,t){i.set(e,t)},removeItem(e){i.delete(e)},getKeys(){return[...i.keys()]},clear(){i.clear()},dispose(){i.clear()}}};function Np(i={}){const e={mounts:{"":i.driver||Cp()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=h=>{for(const l of e.mountpoints)if(h.startsWith(l))return{base:l,relativeKey:h.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:h,driver:e.mounts[""]}},s=(h,l)=>e.mountpoints.filter(u=>u.startsWith(h)||l&&h.startsWith(u)).map(u=>({relativeBase:h.length>u.length?h.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(h,l)=>{if(e.watching){l=Se(l);for(const u of e.watchListeners)u(h,l)}},n=async()=>{if(!e.watching){e.watching=!0;for(const h in e.mounts)e.unwatch[h]=await Fn(e.mounts[h],r,h)}},o=async()=>{if(e.watching){for(const h in e.unwatch)await e.unwatch[h]();e.unwatch={},e.watching=!1}},a=(h,l,u)=>{const p=new Map,d=g=>{let m=p.get(g.base);return m||(m={driver:g.driver,base:g.base,items:[]},p.set(g.base,m)),m};for(const g of h){const m=typeof g=="string",f=Se(m?g:g.key),w=m?void 0:g.value,y=m||!g.options?l:{...l,...g.options},b=t(f);d(b).items.push({key:f,value:w,relativeKey:b.relativeKey,options:y})}return Promise.all([...p.values()].map(g=>u(g))).then(g=>g.flat())},c={hasItem(h,l={}){h=Se(h);const{relativeKey:u,driver:p}=t(h);return ue(p.hasItem,u,l)},getItem(h,l={}){h=Se(h);const{relativeKey:u,driver:p}=t(h);return ue(p.getItem,u,l).then(d=>Ji(d))},getItems(h,l={}){return a(h,l,u=>u.driver.getItems?ue(u.driver.getItems,u.items.map(p=>({key:p.relativeKey,options:p.options})),l).then(p=>p.map(d=>({key:Sp(u.base,d.key),value:Ji(d.value)}))):Promise.all(u.items.map(p=>ue(u.driver.getItem,p.relativeKey,p.options).then(d=>({key:p.key,value:Ji(d)})))))},getItemRaw(h,l={}){h=Se(h);const{relativeKey:u,driver:p}=t(h);return p.getItemRaw?ue(p.getItemRaw,u,l):ue(p.getItem,u,l).then(d=>_p(d))},async setItem(h,l,u={}){if(l===void 0)return c.removeItem(h);h=Se(h);const{relativeKey:p,driver:d}=t(h);d.setItem&&(await ue(d.setItem,p,hs(l),u),d.watch||r("update",h))},async setItems(h,l){await a(h,l,async u=>{if(u.driver.setItems)return ue(u.driver.setItems,u.items.map(p=>({key:p.relativeKey,value:hs(p.value),options:p.options})),l);u.driver.setItem&&await Promise.all(u.items.map(p=>ue(u.driver.setItem,p.relativeKey,hs(p.value),p.options)))})},async setItemRaw(h,l,u={}){if(l===void 0)return c.removeItem(h,u);h=Se(h);const{relativeKey:p,driver:d}=t(h);if(d.setItemRaw)await ue(d.setItemRaw,p,l,u);else if(d.setItem)await ue(d.setItem,p,Ip(l),u);else return;d.watch||r("update",h)},async removeItem(h,l={}){typeof l=="boolean"&&(l={removeMeta:l}),h=Se(h);const{relativeKey:u,driver:p}=t(h);p.removeItem&&(await ue(p.removeItem,u,l),(l.removeMeta||l.removeMata)&&await ue(p.removeItem,u+"$",l),p.watch||r("remove",h))},async getMeta(h,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),h=Se(h);const{relativeKey:u,driver:p}=t(h),d=Object.create(null);if(p.getMeta&&Object.assign(d,await ue(p.getMeta,u,l)),!l.nativeOnly){const g=await ue(p.getItem,u+"$",l).then(m=>Ji(m));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(d,g))}return d},setMeta(h,l,u={}){return this.setItem(h+"$",l,u)},removeMeta(h,l={}){return this.removeItem(h+"$",l)},async getKeys(h,l={}){h=es(h);const u=s(h,!0);let p=[];const d=[];let g=!0;for(const f of u){f.driver.flags?.maxDepth||(g=!1);const w=await ue(f.driver.getKeys,f.relativeBase,l);for(const y of w){const b=f.mountpoint+Se(y);p.some(_=>b.startsWith(_))||d.push(b)}p=[f.mountpoint,...p.filter(y=>!y.startsWith(f.mountpoint))]}const m=l.maxDepth!==void 0&&!g;return d.filter(f=>(!m||Op(f,l.maxDepth))&&Ap(f,h))},async clear(h,l={}){h=es(h),await Promise.all(s(h,!1).map(async u=>{if(u.driver.clear)return ue(u.driver.clear,u.relativeBase,l);if(u.driver.removeItem){const p=await u.driver.getKeys(u.relativeBase||"",l);return Promise.all(p.map(d=>u.driver.removeItem(d,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(h=>Gn(h)))},async watch(h){return await n(),e.watchListeners.push(h),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==h),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(h,l){if(h=es(h),h&&e.mounts[h])throw new Error(`already mounted at ${h}`);return h&&(e.mountpoints.push(h),e.mountpoints.sort((u,p)=>p.length-u.length)),e.mounts[h]=l,e.watching&&Promise.resolve(Fn(l,r,h)).then(u=>{e.unwatch[h]=u}).catch(console.error),c},async unmount(h,l=!0){h=es(h),!(!h||!e.mounts[h])&&(e.watching&&h in e.unwatch&&(e.unwatch[h]?.(),delete e.unwatch[h]),l&&await Gn(e.mounts[h]),e.mountpoints=e.mountpoints.filter(u=>u!==h),delete e.mounts[h])},getMount(h=""){h=Se(h)+":";const l=t(h);return{driver:l.driver,base:l.base}},getMounts(h="",l={}){return h=Se(h),s(h,l.parents).map(p=>({driver:p.driver,base:p.mountpoint}))},keys:(h,l={})=>c.getKeys(h,l),get:(h,l={})=>c.getItem(h,l),set:(h,l,u={})=>c.setItem(h,l,u),has:(h,l={})=>c.hasItem(h,l),del:(h,l={})=>c.removeItem(h,l),remove:(h,l={})=>c.removeItem(h,l)};return c}function Fn(i,e,t){return i.watch?i.watch((s,r)=>e(s,t+r)):()=>{}}async function Gn(i){typeof i.dispose=="function"&&await ue(i.dispose)}const Rp="idb-keyval";var Tp=(i={})=>{const e=i.base&&i.base.length>0?`${i.base}:`:"",t=r=>e+r;let s;return i.dbName&&i.storeName&&(s=Ic(i.dbName,i.storeName)),{name:Rp,options:i,async hasItem(r){return!(typeof await Qr(t(r),s)>"u")},async getItem(r){return await Qr(t(r),s)??null},setItem(r,n){return Sc(t(r),n,s)},removeItem(r){return $c(t(r),s)},getKeys(){return Pc(s)},clear(){return _c(s)}}};const qp="WALLET_CONNECT_V2_INDEXED_DB",jp="keyvaluestorage";let Dp=class{constructor(){this.indexedDb=Np({driver:Tp({dbName:qp,storeName:jp})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,Rr(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var zs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ls={exports:{}};(function(){let i;function e(){}i=e,i.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},i.prototype.setItem=function(t,s){this[t]=String(s)},i.prototype.removeItem=function(t){delete this[t]},i.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(s){t[s]=void 0,delete t[s]})},i.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},i.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof zs<"u"&&zs.localStorage?ls.exports=zs.localStorage:typeof window<"u"&&window.localStorage?ls.exports=window.localStorage:ls.exports=new e})();function kp(i){var e;return[i[0],ds((e=i[1])!=null?e:"")]}let Mp=class{constructor(){this.localStorage=ls.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(kp)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return ds(t)}async setItem(e,t){this.localStorage.setItem(e,Rr(t))}async removeItem(e){this.localStorage.removeItem(e)}};const Up="wc_storage_version",Wn=1,Lp=async(i,e,t)=>{const s=Up,r=await e.getItem(s);if(r&&r>=Wn){t(e);return}const n=await i.getKeys();if(!n.length){t(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const h=await i.getItem(a);await e.setItem(a,h),o.push(a)}}await e.setItem(s,Wn),t(e),Bp(i,o)},Bp=async(i,e)=>{e.length&&e.forEach(async t=>{await i.removeItem(t)})};let zp=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new Mp;this.storage=e;try{const t=new Dp;Lp(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}};var Kp=Object.defineProperty,Vp=(i,e,t)=>e in i?Kp(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Jn=(i,e,t)=>Vp(i,typeof e!="symbol"?e+"":e,t);let Hp=class extends yi{constructor(e){super(),this.opts=e,Jn(this,"protocol","wc"),Jn(this,"version",2)}};var Fp=Object.defineProperty,Gp=(i,e,t)=>e in i?Fp(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wp=(i,e,t)=>Gp(i,e+"",t);let Jp=class extends yi{constructor(e,t){super(),this.core=e,this.logger=t,Wp(this,"records",new Map)}},Qp=class{constructor(e,t){this.logger=e,this.core=t}};class Yp extends yi{constructor(e,t){super(),this.relayer=e,this.logger=t}}let Zp=class extends yi{constructor(e){super()}},Xp=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},ed=class extends yi{constructor(e,t){super(),this.relayer=e,this.logger=t}},td=class extends yi{constructor(e,t){super(),this.core=e,this.logger=t}},id=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},sd=class{constructor(e,t){this.projectId=e,this.logger=t}},rd=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var nd=Object.defineProperty,od=(i,e,t)=>e in i?nd(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qn=(i,e,t)=>od(i,typeof e!="symbol"?e+"":e,t);let ad=class{constructor(e){this.opts=e,Qn(this,"protocol","wc"),Qn(this,"version",2)}},cd=class{constructor(e){this.client=e}};var hd={};const Ta="wc",qa=2,dr="core",nt=`${Ta}@2:${dr}:`,ld={logger:"error"},ud={database:":memory:"},pd="crypto",Yn="client_ed25519_seed",dd=N.ONE_DAY,gd="keychain",fd="0.3",md="messages",yd="0.3",Zn=N.SIX_HOURS,wd="publisher",ja="irn",bd="error",Da="wss://relay.walletconnect.org",vd="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"},Ed="_subscription",Me={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Id=.1,gr="2.21.1",ee={link_mode:"link_mode",relay:"relay"},us={inbound:"inbound",outbound:"outbound"},_d="0.3",Pd="WALLETCONNECT_CLIENT_ID",Xn="WALLETCONNECT_LINK_MODE_APPS",Re={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},$d="subscription",Sd="0.3",Od="pairing",Ad="0.3",$i={wc_pairingDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:N.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:N.ONE_DAY,prompt:!1,tag:0},res:{ttl:N.ONE_DAY,prompt:!1,tag:0}}},Nt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ve={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},xd="history",Cd="0.3",Nd="expirer",Le={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Rd="0.3",Td="verify-api",qd="https://verify.walletconnect.com",ka="https://verify.walletconnect.org",qi=ka,jd=`${qi}/v3`,Dd=[qd,ka],kd="echo",Md="https://echo.walletconnect.com",tt={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"},lt={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"},He={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"},St={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"},Ot={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"},Si={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"},Ud=.1,Ld="event-client",Bd=86400,zd="https://pulse.walletconnect.org/batch";function Kd(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 u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,f=0,w=0,y=g.length;w!==y&&g[w]===0;)w++,m++;for(var b=(y-w)*l+1>>>0,_=new Uint8Array(b);w!==y;){for(var x=g[w],P=0,S=b-1;(x!==0||P<f)&&S!==-1;S--,P++)x+=256*_[S]>>>0,_[S]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");f=P,w++}for(var R=b-f;R!==b&&_[R]===0;)R++;for(var v=c.repeat(m);R<b;++R)v+=i.charAt(_[R]);return v}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var m=0;if(g[m]!==" "){for(var f=0,w=0;g[m]===c;)f++,m++;for(var y=(g.length-m)*h+1>>>0,b=new Uint8Array(y);g[m];){var _=t[g.charCodeAt(m)];if(_===255)return;for(var x=0,P=y-1;(_!==0||x<w)&&P!==-1;P--,x++)_+=a*b[P]>>>0,b[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");w=x,m++}if(g[m]!==" "){for(var S=y-w;S!==y&&b[S]===0;)S++;for(var R=new Uint8Array(f+(y-S)),v=f;S!==y;)R[v++]=b[S++];return R}}}function d(g){var m=p(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:d}}var Vd=Kd,Hd=Vd;const Ma=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")},Fd=i=>new TextEncoder().encode(i),Gd=i=>new TextDecoder().decode(i);class Wd{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 Jd{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 Ua(this,e)}}class Qd{constructor(e){this.decoders=e}or(e){return Ua(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 Ua=(i,e)=>new Qd({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Yd{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Wd(e,t,s),this.decoder=new Jd(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Os=({name:i,prefix:e,encode:t,decode:s})=>new Yd(i,e,t,s),Gi=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=Hd(t,e);return Os({prefix:i,name:e,encode:s,decode:n=>Ma(r(n))})},Zd=(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 u=r[i[l]];if(u===void 0)throw new SyntaxError(`Non-${s} character`);c=c<<t|u,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},Xd=(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})=>Os({prefix:e,name:i,encode(r){return Xd(r,s,t)},decode(r){return Zd(r,s,t,i)}}),eg=Os({prefix:"\0",name:"identity",encode:i=>Gd(i),decode:i=>Fd(i)});var tg=Object.freeze({__proto__:null,identity:eg});const ig=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sg=Object.freeze({__proto__:null,base2:ig});const rg=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ng=Object.freeze({__proto__:null,base8:rg});const og=Gi({prefix:"9",name:"base10",alphabet:"0123456789"});var ag=Object.freeze({__proto__:null,base10:og});const cg=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),hg=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var lg=Object.freeze({__proto__:null,base16:cg,base16upper:hg});const ug=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),pg=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),dg=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),gg=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fg=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),mg=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yg=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wg=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bg=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var vg=Object.freeze({__proto__:null,base32:ug,base32upper:pg,base32pad:dg,base32padupper:gg,base32hex:fg,base32hexupper:mg,base32hexpad:yg,base32hexpadupper:wg,base32z:bg});const Eg=Gi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ig=Gi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var _g=Object.freeze({__proto__:null,base36:Eg,base36upper:Ig});const Pg=Gi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$g=Gi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Sg=Object.freeze({__proto__:null,base58btc:Pg,base58flickr:$g});const Og=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ag=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xg=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Cg=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ng=Object.freeze({__proto__:null,base64:Og,base64pad:Ag,base64url:xg,base64urlpad:Cg});const La=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Rg=La.reduce((i,e,t)=>(i[t]=e,i),[]),Tg=La.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function qg(i){return i.reduce((e,t)=>(e+=Rg[t],e),"")}function jg(i){const e=[];for(const t of i){const s=Tg[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const Dg=Os({prefix:"🚀",name:"base256emoji",encode:qg,decode:jg});var kg=Object.freeze({__proto__:null,base256emoji:Dg}),Mg=Ba,eo=128,Ug=-128,Lg=Math.pow(2,31);function Ba(i,e,t){e=e||[],t=t||0;for(var s=t;i>=Lg;)e[t++]=i&255|eo,i/=128;for(;i&Ug;)e[t++]=i&255|eo,i>>>=7;return e[t]=i|0,Ba.bytes=t-s+1,e}var Bg=fr,zg=128,to=127;function fr(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw fr.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&to)<<r:(o&to)*Math.pow(2,r),r+=7}while(o>=zg);return fr.bytes=n-s,t}var Kg=Math.pow(2,7),Vg=Math.pow(2,14),Hg=Math.pow(2,21),Fg=Math.pow(2,28),Gg=Math.pow(2,35),Wg=Math.pow(2,42),Jg=Math.pow(2,49),Qg=Math.pow(2,56),Yg=Math.pow(2,63),Zg=function(i){return i<Kg?1:i<Vg?2:i<Hg?3:i<Fg?4:i<Gg?5:i<Wg?6:i<Jg?7:i<Qg?8:i<Yg?9:10},Xg={encode:Mg,decode:Bg,encodingLength:Zg},za=Xg;const io=(i,e,t=0)=>(za.encode(i,e,t),e),so=i=>za.encodingLength(i),mr=(i,e)=>{const t=e.byteLength,s=so(i),r=s+so(t),n=new Uint8Array(r+t);return io(i,n,0),io(t,n,s),n.set(e,r),new ef(i,t,e,n)};class ef{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}}const Ka=({name:i,code:e,encode:t})=>new tf(i,e,t);class tf{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?mr(this.code,t):t.then(s=>mr(this.code,s))}else throw Error("Unknown type, must be binary type")}}const Va=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),sf=Ka({name:"sha2-256",code:18,encode:Va("SHA-256")}),rf=Ka({name:"sha2-512",code:19,encode:Va("SHA-512")});var nf=Object.freeze({__proto__:null,sha256:sf,sha512:rf});const Ha=0,of="identity",Fa=Ma,af=i=>mr(Ha,Fa(i)),cf={code:Ha,name:of,encode:Fa,digest:af};var hf=Object.freeze({__proto__:null,identity:cf});new TextEncoder,new TextDecoder;const ro={...tg,...sg,...ng,...ag,...lg,...vg,..._g,...Sg,...Ng,...kg};({...nf,...hf});function lf(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Ga(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const no=Ga("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Ks=Ga("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=lf(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),uf={utf8:no,"utf-8":no,hex:ro.base16,latin1:Ks,ascii:Ks,binary:Ks,...ro};function pf(i,e="utf8"){const t=uf[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 df=Object.defineProperty,gf=(i,e,t)=>e in i?df(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xe=(i,e,t)=>gf(i,typeof e!="symbol"?e+"":e,t);class ff{constructor(e,t){this.core=e,this.logger=t,Xe(this,"keychain",new Map),Xe(this,"name",gd),Xe(this,"version",fd),Xe(this,"initialized",!1),Xe(this,"storagePrefix",nt),Xe(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),Xe(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),Xe(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),Xe(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}),Xe(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=Pe(t,this.name)}get context(){return ke(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,er(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?tr(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 mf=Object.defineProperty,yf=(i,e,t)=>e in i?mf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,me=(i,e,t)=>yf(i,typeof e!="symbol"?e+"":e,t);class wf{constructor(e,t,s){this.core=e,this.logger=t,me(this,"name",pd),me(this,"keychain"),me(this,"randomSessionIdentifier",ur()),me(this,"initialized",!1),me(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),me(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),me(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=Jr(r);return vc(n.publicKey)}),me(this,"generateKeyPair",()=>{this.isInitialized();const r=mu();return this.setPrivateKey(r.publicKey,r.privateKey)}),me(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=Jr(n),a=this.randomSessionIdentifier;return await Ec(a,r,dd,o)}),me(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=yu(a,n);return this.setSymKey(c,o)}),me(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||cs(r);return await this.keychain.set(o,r),o}),me(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),me(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),me(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Ca(o),c=Rr(n);if(qn(a))return vu(c,o?.encoding);if(Tn(a)){const p=a.senderPublicKey,d=a.receiverPublicKey;r=await this.generateSharedKey(p,d)}const h=this.getSymKey(r),{type:l,senderPublicKey:u}=a;return wu({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o?.encoding})}),me(this,"decode",async(r,n,o)=>{this.isInitialized();const a=Iu(n,o);if(qn(a)){const c=Eu(n,o?.encoding);return ds(c)}if(Tn(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=bu({symKey:c,encoded:n,encoding:o?.encoding});return ds(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),me(this,"getPayloadType",(r,n=We)=>{const o=Li({encoded:r,encoding:n});return Mt(o.type)}),me(this,"getPayloadSenderPublicKey",(r,n=We)=>{const o=Li({encoded:r,encoding:n});return o.senderPublicKey?xe(o.senderPublicKey,_e):void 0}),this.core=e,this.logger=Pe(t,this.name),this.keychain=s||new ff(this.core,this.logger)}get context(){return ke(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(Yn)}catch{e=ur(),await this.keychain.set(Yn,e)}return pf(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 bf=Object.defineProperty,vf=Object.defineProperties,Ef=Object.getOwnPropertyDescriptors,oo=Object.getOwnPropertySymbols,If=Object.prototype.hasOwnProperty,_f=Object.prototype.propertyIsEnumerable,yr=(i,e,t)=>e in i?bf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Pf=(i,e)=>{for(var t in e||(e={}))If.call(e,t)&&yr(i,t,e[t]);if(oo)for(var t of oo(e))_f.call(e,t)&&yr(i,t,e[t]);return i},$f=(i,e)=>vf(i,Ef(e)),Ce=(i,e,t)=>yr(i,typeof e!="symbol"?e+"":e,t);class Sf extends Qp{constructor(e,t){super(e,t),this.logger=e,this.core=t,Ce(this,"messages",new Map),Ce(this,"messagesWithoutClientAck",new Map),Ce(this,"name",md),Ce(this,"version",yd),Ce(this,"initialized",!1),Ce(this,"storagePrefix",nt),Ce(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}}}),Ce(this,"set",async(s,r,n)=>{this.isInitialized();const o=st(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===us.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,$f(Pf({},c),{[o]:r}))}return await this.persist(),o}),Ce(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),Ce(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}),Ce(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=st(r);return typeof n[o]<"u"}),Ce(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=st(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),Ce(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=Pe(e,this.name),this.core=t}get context(){return ke(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,er(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,er(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?tr(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?tr(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 Of=Object.defineProperty,Af=Object.defineProperties,xf=Object.getOwnPropertyDescriptors,ao=Object.getOwnPropertySymbols,Cf=Object.prototype.hasOwnProperty,Nf=Object.prototype.propertyIsEnumerable,wr=(i,e,t)=>e in i?Of(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ts=(i,e)=>{for(var t in e||(e={}))Cf.call(e,t)&&wr(i,t,e[t]);if(ao)for(var t of ao(e))Nf.call(e,t)&&wr(i,t,e[t]);return i},Vs=(i,e)=>Af(i,xf(e)),Fe=(i,e,t)=>wr(i,typeof e!="symbol"?e+"":e,t);class Rf extends Yp{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Fe(this,"events",new _t.EventEmitter),Fe(this,"name",wd),Fe(this,"queue",new Map),Fe(this,"publishTimeout",N.toMiliseconds(N.ONE_MINUTE)),Fe(this,"initialPublishTimeout",N.toMiliseconds(N.ONE_SECOND*15)),Fe(this,"needsTransportRestart",!1),Fe(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?.ttl||Zn,c=ms(n),h=n?.prompt||!1,l=n?.tag||0,u=n?.id||ri().toString(),p={topic:s,message:r,opts:{ttl:a,relay:c,prompt:h,tag:l,id:u,attestation:n?.attestation,tvf:n?.tvf}},d=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const g=new Promise(async m=>{const f=({id:y})=>{p.opts.id===y&&(this.removeRequestFromQueue(y),this.relayer.events.removeListener(de.publish,f),m(p))};this.relayer.events.on(de.publish,f);const w=vt(new Promise((y,b)=>{this.rpcPublish({topic:s,message:r,ttl:a,prompt:h,tag:l,id:u,attestation:n?.attestation,tvf:n?.tvf}).then(y).catch(_=>{this.logger.warn(_,_?.message),b(_)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await w,this.events.removeListener(de.publish,f)}catch(y){this.queue.set(u,Vs(ts({},p),{attempt:1})),this.logger.warn(y,y?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:s,message:r,opts:n}}),await vt(g,this.publishTimeout,d)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=n?.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(u)}}),Fe(this,"on",(s,r)=>{this.events.on(s,r)}),Fe(this,"once",(s,r)=>{this.events.once(s,r)}),Fe(this,"off",(s,r)=>{this.events.off(s,r)}),Fe(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=Pe(t,this.name),this.registerEventListeners()}get context(){return ke(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=Zn,prompt:h,tag:l,id:u,attestation:p,tvf:d}=e,g={method:Ci(ms().protocol).publish,params:ts({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:p},d),id:u};we((t=g.params)==null?void 0:t.prompt)&&((s=g.params)==null||delete s.prompt),we((r=g.params)==null?void 0:r.tag)&&((n=g.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const m=await this.relayer.request(g);return this.relayer.events.emit(de.publish,e),this.logger.debug("Successfully Published Payload"),m}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,Vs(ts({},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(Vs(ts({},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(wi.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 Tf=Object.defineProperty,qf=(i,e,t)=>e in i?Tf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Vt=(i,e,t)=>qf(i,typeof e!="symbol"?e+"":e,t);class jf{constructor(){Vt(this,"map",new Map),Vt(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),Vt(this,"get",e=>this.map.get(e)||[]),Vt(this,"exists",(e,t)=>this.get(e).includes(t)),Vt(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)}),Vt(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Df=Object.defineProperty,kf=Object.defineProperties,Mf=Object.getOwnPropertyDescriptors,co=Object.getOwnPropertySymbols,Uf=Object.prototype.hasOwnProperty,Lf=Object.prototype.propertyIsEnumerable,br=(i,e,t)=>e in i?Df(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Oi=(i,e)=>{for(var t in e||(e={}))Uf.call(e,t)&&br(i,t,e[t]);if(co)for(var t of co(e))Lf.call(e,t)&&br(i,t,e[t]);return i},Hs=(i,e)=>kf(i,Mf(e)),Q=(i,e,t)=>br(i,typeof e!="symbol"?e+"":e,t);class Bf extends ed{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Q(this,"subscriptions",new Map),Q(this,"topicMap",new jf),Q(this,"events",new _t.EventEmitter),Q(this,"name",$d),Q(this,"version",Sd),Q(this,"pending",new Map),Q(this,"cached",[]),Q(this,"initialized",!1),Q(this,"storagePrefix",nt),Q(this,"subscribeTimeout",N.toMiliseconds(N.ONE_MINUTE)),Q(this,"initialSubscribeTimeout",N.toMiliseconds(N.ONE_SECOND*15)),Q(this,"clientId"),Q(this,"batchSubscribeTopicsLimit",500),Q(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Q(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=ms(r),o={topic:s,relay:n,transportType: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}}),Q(this,"unsubscribe",async(s,r)=>{this.isInitialized(),typeof r?.id<"u"?await this.unsubscribeById(s,r.id,r):await this.unsubscribeByTopic(s,r)}),Q(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),Q(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),Q(this,"on",(s,r)=>{this.events.on(s,r)}),Q(this,"once",(s,r)=>{this.events.once(s,r)}),Q(this,"off",(s,r)=>{this.events.off(s,r)}),Q(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),Q(this,"start",async()=>{await this.onConnect()}),Q(this,"stop",async()=>{await this.onDisconnect()}),Q(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Q(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)}),Q(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(wi.pulse,async()=>{await this.checkPending()}),this.events.on(Re.created,async s=>{const r=Re.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(Re.deleted,async s=>{const r=Re.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=Pe(t,this.name),this.clientId=""}get context(){return ke(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=ms(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=J("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?.transportType===ee.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Ci(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?.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(s?.transportType===ee.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},N.toMiliseconds(N.ONE_SECOND)),a;const c=new Promise(async l=>{const u=p=>{p.topic===e&&(this.events.removeListener(Re.created,u),l(p.id))};this.events.on(Re.created,u);try{const p=await vt(new Promise((d,g)=>{this.relayer.request(n).catch(m=>{this.logger.warn(m,m?.message),g(m)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Re.created,u),l(p)}catch{}}),h=await vt(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:Ci(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 vt(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:Ci(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 vt(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:Ci(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,Hs(Oi({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Oi({},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,Oi({},t)),this.topicMap.set(t.topic,e),this.events.emit(Re.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(Re.deleted,Hs(Oi({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Re.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(Re.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=>Hs(Oi({},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 sh(N.toMiliseconds(N.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=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 st(e+await this.getClientId())}}var zf=Object.defineProperty,ho=Object.getOwnPropertySymbols,Kf=Object.prototype.hasOwnProperty,Vf=Object.prototype.propertyIsEnumerable,vr=(i,e,t)=>e in i?zf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,lo=(i,e)=>{for(var t in e||(e={}))Kf.call(e,t)&&vr(i,t,e[t]);if(ho)for(var t of ho(e))Vf.call(e,t)&&vr(i,t,e[t]);return i},H=(i,e,t)=>vr(i,typeof e!="symbol"?e+"":e,t);class Hf extends Zp{constructor(e){super(e),H(this,"protocol","wc"),H(this,"version",2),H(this,"core"),H(this,"logger"),H(this,"events",new _t.EventEmitter),H(this,"provider"),H(this,"messages"),H(this,"subscriber"),H(this,"publisher"),H(this,"name",vd),H(this,"transportExplicitlyClosed",!1),H(this,"initialized",!1),H(this,"connectionAttemptInProgress",!1),H(this,"relayUrl"),H(this,"projectId"),H(this,"packageName"),H(this,"bundleId"),H(this,"hasExperiencedNetworkDisruption",!1),H(this,"pingTimeout"),H(this,"heartBeatTimeout",N.toMiliseconds(N.THIRTY_SECONDS+N.FIVE_SECONDS)),H(this,"reconnectTimeout"),H(this,"connectPromise"),H(this,"reconnectInProgress",!1),H(this,"requestsInFlight",[]),H(this,"connectTimeout",N.toMiliseconds(N.ONE_SECOND*15)),H(this,"request",async t=>{var s,r;this.logger.debug("Publishing Request Payload");const n=t.id||ri().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}}),H(this,"resetPingTimeout",()=>{gs()&&(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?.message)}},this.heartBeatTimeout))}),H(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),H(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(de.connect)}),H(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),H(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()}),H(this,"registerProviderListeners",()=>{this.provider.on(Me.payload,this.onPayloadHandler),this.provider.on(Me.connect,this.onConnectHandler),this.provider.on(Me.disconnect,this.onDisconnectHandler),this.provider.on(Me.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Pe(e.logger,this.name):Tr(bs({level:e.logger||bd})),this.messages=new Sf(this.logger,e.core),this.subscriber=new Bf(this,this.logger),this.publisher=new Rf(this,this.logger),this.relayUrl=e?.relayUrl||Da,this.projectId=e.projectId,Bc()?this.packageName=sn():zc()&&(this.bundleId=sn()),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?.message)}}get context(){return ke(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:ee.relay},us.outbound)}async subscribe(e,t){var s,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((s=t?.internal)==null?void 0:s.throwOnFailedPublish)>"u"?!0:(r=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(Re.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Re.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,lo({internal:{throwOnFailedPublish:o}},t)).catch(p=>{o&&u(p)})||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 vt(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 Hn())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(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?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:s}=e;if(!t.sessionExists){const r=ae(N.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,us.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(Me.disconnect,n),await vt(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(Me.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(Me.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Me.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,N.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,s,r,n;if(gs())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?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new ze(new bc(Gc({sdkVersion:gr,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}),qr(e)){if(!e.method.endsWith(Ed))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:ee.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(lo({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else jr(e)&&this.events.emit(de.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,us.inbound),this.events.emit(de.message,e))}async acknowledgePayload(e){const t=vs(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Me.payload,this.onPayloadHandler),this.provider.off(Me.connect,this.onConnectHandler),this.provider.off(Me.disconnect,this.onDisconnectHandler),this.provider.off(Me.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Hn();fp(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(s=>this.logger.error(s,s?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(wi.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&wp())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,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?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},N.toMiliseconds(Id)))))}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 Ff(){}function uo(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 po(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function go(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Gf="[object RegExp]",Wf="[object String]",Jf="[object Number]",Qf="[object Boolean]",fo="[object Arguments]",Yf="[object Symbol]",Zf="[object Date]",Xf="[object Map]",em="[object Set]",tm="[object Array]",im="[object Function]",sm="[object ArrayBuffer]",Fs="[object Object]",rm="[object Error]",nm="[object DataView]",om="[object Uint8Array]",am="[object Uint8ClampedArray]",cm="[object Uint16Array]",hm="[object Uint32Array]",lm="[object BigUint64Array]",um="[object Int8Array]",pm="[object Int16Array]",dm="[object Int32Array]",gm="[object BigInt64Array]",fm="[object Float32Array]",mm="[object Float64Array]";function ym(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function wm(i,e,t){return Ni(i,e,void 0,void 0,void 0,void 0,t)}function Ni(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 ji(i,e,n,o)}return ji(i,e,n,o)}function ji(i,e,t,s){if(Object.is(i,e))return!0;let r=go(i),n=go(e);if(r===fo&&(r=Fs),n===fo&&(n=Fs),r!==n)return!1;switch(r){case Wf:return i.toString()===e.toString();case Jf:{const c=i.valueOf(),h=e.valueOf();return ym(c,h)}case Qf:case Zf:case Yf:return Object.is(i.valueOf(),e.valueOf());case Gf:return i.source===e.source&&i.flags===e.flags;case im: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 Xf:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!Ni(h,e.get(c),c,i,e,t,s))return!1;return!0}case em:{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 u=c[l],p=h.findIndex(d=>Ni(u,d,void 0,i,e,t,s));if(p===-1)return!1;h.splice(p,1)}return!0}case tm:case om:case am:case cm:case hm:case lm:case um:case pm:case dm:case gm:case fm:case mm:{if(typeof Buffer<"u"&&Buffer.isBuffer(i)!==Buffer.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!Ni(i[c],e[c],c,i,e,t,s))return!1;return!0}case sm:return i.byteLength!==e.byteLength?!1:ji(new Uint8Array(i),new Uint8Array(e),t,s);case nm:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:ji(new Uint8Array(i),new Uint8Array(e),t,s);case rm:return i.name===e.name&&i.message===e.message;case Fs:{if(!(ji(i.constructor,e.constructor,t,s)||uo(i)&&uo(e)))return!1;const c=[...Object.keys(i),...po(i)],h=[...Object.keys(e),...po(e)];if(c.length!==h.length)return!1;for(let l=0;l<c.length;l++){const u=c[l],p=i[u];if(!Object.hasOwn(e,u))return!1;const d=e[u];if(!Ni(p,d,u,i,e,t,s))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function bm(i,e){return wm(i,e,Ff)}var vm=Object.defineProperty,mo=Object.getOwnPropertySymbols,Em=Object.prototype.hasOwnProperty,Im=Object.prototype.propertyIsEnumerable,Er=(i,e,t)=>e in i?vm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,yo=(i,e)=>{for(var t in e||(e={}))Em.call(e,t)&&Er(i,t,e[t]);if(mo)for(var t of mo(e))Im.call(e,t)&&Er(i,t,e[t]);return i},$e=(i,e,t)=>Er(i,typeof e!="symbol"?e+"":e,t);class Ut extends Xp{constructor(e,t,s,r=nt,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,$e(this,"map",new Map),$e(this,"version",_d),$e(this,"cached",[]),$e(this,"initialized",!1),$e(this,"getKey"),$e(this,"storagePrefix",nt),$e(this,"recentlyDeleted",[]),$e(this,"recentlyDeletedLimit",200),$e(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):Fu(o)?this.map.set(o.id,o):Gu(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),$e(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())}),$e(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),$e(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>bm(a[c],o[c]))):this.values)),$e(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=yo(yo({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),$e(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=Pe(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return ke(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 _m=Object.defineProperty,Pm=(i,e,t)=>e in i?_m(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,z=(i,e,t)=>Pm(i,typeof e!="symbol"?e+"":e,t);class $m{constructor(e,t){this.core=e,this.logger=t,z(this,"name",Od),z(this,"version",Ad),z(this,"events",new Nr),z(this,"pairings"),z(this,"initialized",!1),z(this,"storagePrefix",nt),z(this,"ignoredPayloadTypes",[gt]),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=ur(),n=await this.core.crypto.setSymKey(r),o=ae(N.FIVE_MINUTES),a={protocol:ja},c={topic:n,expiry:o,relay:a,active:!1,methods:s?.methods},h=Dn({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:s?.methods});return this.events.emit(Nt.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:s?.transportType}),{topic:n,uri:h}}),z(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s?.uri,trace:[tt.pairing_started]}});this.isValidPair(s,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=jn(s.uri);r.props.properties.topic=n,r.addTrace(tt.pairing_uri_validation_success),r.addTrace(tt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(tt.existing_pairing),l.active)throw r.setError(lt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(tt.pairing_not_expired)}const u=c||ae(N.FIVE_MINUTES),p={topic:n,relay:a,expiry:u,active:!1,methods:h};this.core.expirer.set(n,u),await this.pairings.set(n,p),r.addTrace(tt.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(Nt.create,p),r.addTrace(tt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(tt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(lt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(d){throw r.setError(lt.subscribe_pairing_topic_failure),d}return r.addTrace(tt.subscribe_pairing_topic_success),p}),z(this,"activate",async({topic:s})=>{this.isInitialized();const r=ae(N.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}=At();this.events.once(W("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",J("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 Dn({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=Tt(r,n),a=await this.core.crypto.encode(s,o),c=$i[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=vs(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=$i[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=Ko(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=$i[c]?$i[c].res:$i.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,J("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=>wt(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(Nt.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(()=>{ht(r)?this.events.emit(W("pairing_ping",n),{}):it(r)&&this.events.emit(W("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(Nt.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=J("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(J("WC_METHOD_UNSUPPORTED",s))}),z(this,"isValidPair",(s,r)=>{var n;if(!Oe(s)){const{message:a}=C("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(lt.malformed_pairing_uri),new Error(a)}if(!Hu(s.uri)){const{message:a}=C("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(lt.malformed_pairing_uri),new Error(a)}const o=jn(s?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=C("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(lt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=C("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(lt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&N.toMiliseconds(o?.expiryTimestamp)<Date.now()){r.setError(lt.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(!Oe(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(!Oe(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(!re(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(wt(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=Pe(t,this.name),this.pairings=new Ut(this.core,this.logger,this.name,this.storagePrefix)}get context(){return ke(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!==ee.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);qr(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):jr(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(Le.expired,async e=>{const{topic:t}=Yo(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Nt.expire,{topic:t}))})}}var Sm=Object.defineProperty,Om=(i,e,t)=>e in i?Sm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ye=(i,e,t)=>Om(i,typeof e!="symbol"?e+"":e,t);class Am extends Jp{constructor(e,t){super(e,t),this.core=e,this.logger=t,ye(this,"records",new Map),ye(this,"events",new _t.EventEmitter),ye(this,"name",xd),ye(this,"version",Cd),ye(this,"cached",[]),ye(this,"initialized",!1),ye(this,"storagePrefix",nt),ye(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)}),ye(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:ae(N.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ve.created,o)}),ye(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=it(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(Ve.updated,r))}),ye(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))),ye(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(Ve.deleted,n)}}),this.persist()}),ye(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),ye(this,"on",(s,r)=>{this.events.on(s,r)}),ye(this,"once",(s,r)=>{this.events.once(s,r)}),ye(this,"off",(s,r)=>{this.events.off(s,r)}),ye(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=Pe(t,this.name)}get context(){return ke(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:Tt(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(Ve.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(Ve.created,e=>{const t=Ve.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ve.updated,e=>{const t=Ve.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ve.deleted,e=>{const t=Ve.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(wi.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{N.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Ve.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 xm=Object.defineProperty,Cm=(i,e,t)=>e in i?xm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ee=(i,e,t)=>Cm(i,typeof e!="symbol"?e+"":e,t);class Nm extends td{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ee(this,"expirations",new Map),Ee(this,"events",new _t.EventEmitter),Ee(this,"name",Nd),Ee(this,"version",Rd),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",nt),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(Le.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(Le.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=Pe(t,this.name)}get context(){return ke(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 Wc(e);if(typeof e=="number")return Jc(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(Le.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;N.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Le.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(wi.pulse,()=>this.checkExpirations()),this.events.on(Le.created,e=>{const t=Le.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Le.expired,e=>{const t=Le.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Le.deleted,e=>{const t=Le.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 Rm=Object.defineProperty,Tm=(i,e,t)=>e in i?Rm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,se=(i,e,t)=>Tm(i,typeof e!="symbol"?e+"":e,t);class qm extends id{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,se(this,"name",Td),se(this,"abortController"),se(this,"isDevEnv"),se(this,"verifyUrlV3",jd),se(this,"storagePrefix",nt),se(this,"version",qa),se(this,"publicKey"),se(this,"fetchPromise"),se(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&N.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),se(this,"register",async r=>{if(!bi()||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=hi(),l=this.startAbortTimer(N.ONE_SECOND*5),u=await new Promise((p,d)=>{const g=()=>{window.removeEventListener("message",f),h.body.removeChild(m),d("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const m=h.createElement("iframe");m.src=c,m.style.display="none",m.addEventListener("error",g,{signal:this.abortController.signal});const f=w=>{if(w.data&&typeof w.data=="string")try{const y=JSON.parse(w.data);if(y.type==="verify_attestation"){if(Xs(y.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(m),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",f),p(y.attestation===null?"":y.attestation)}}catch(y){this.logger.warn(y)}};h.body.appendChild(m),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),se(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(Xs(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?.verifyUrl);return this.fetchAttestation(o,c)}),se(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(N.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),se(this,"getVerifyUrl",r=>{let n=r||qi;return Dd.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${qi}`),n=qi),n}),se(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(N.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),se(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),se(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),se(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")}}),se(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),se(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}),se(this,"validateAttestation",(r,n)=>{const o=Pu(r,n.publicKey),a={hasExpired:N.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Pe(t,this.name),this.abortController=new AbortController,this.isDevEnv=Dr(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return ke(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),N.toMiliseconds(e))}}var jm=Object.defineProperty,Dm=(i,e,t)=>e in i?jm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,wo=(i,e,t)=>Dm(i,typeof e!="symbol"?e+"":e,t);class km extends sd{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,wo(this,"context",kd),wo(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${Md}/${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=Pe(t,this.context)}}var Mm=Object.defineProperty,bo=Object.getOwnPropertySymbols,Um=Object.prototype.hasOwnProperty,Lm=Object.prototype.propertyIsEnumerable,Ir=(i,e,t)=>e in i?Mm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ai=(i,e)=>{for(var t in e||(e={}))Um.call(e,t)&&Ir(i,t,e[t]);if(bo)for(var t of bo(e))Lm.call(e,t)&&Ir(i,t,e[t]);return i},he=(i,e,t)=>Ir(i,typeof e!="symbol"?e+"":e,t);class Bm extends rd{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,he(this,"context",Ld),he(this,"storagePrefix",nt),he(this,"storageVersion",Ud),he(this,"events",new Map),he(this,"shouldPersist",!1),he(this,"init",async()=>{if(!Dr())try{const r={eventId:nn(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Jo(this.core.relayer.protocol,this.core.relayer.version,gr)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),he(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,h=nn(),l=this.core.projectId||"",u=Date.now(),p=Ai({eventId:h,timestamp:u,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,p),this.shouldPersist=!0),p}),he(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 Ai(Ai({},a),this.setMethods(a.eventId))}),he(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),he(this,"setEventListeners",()=>{this.core.heartbeat.on(wi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{N.fromMiliseconds(Date.now())-N.fromMiliseconds(r.timestamp)>Bd&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),he(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),he(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)}),he(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)}),he(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),he(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,Ai(Ai({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),he(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)}}),he(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${zd}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${gr}${n}`,{method:"POST",body:JSON.stringify(r)})}),he(this,"getAppDomain",()=>Wo().url),this.logger=Pe(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 zm=Object.defineProperty,vo=Object.getOwnPropertySymbols,Km=Object.prototype.hasOwnProperty,Vm=Object.prototype.propertyIsEnumerable,_r=(i,e,t)=>e in i?zm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Eo=(i,e)=>{for(var t in e||(e={}))Km.call(e,t)&&_r(i,t,e[t]);if(vo)for(var t of vo(e))Vm.call(e,t)&&_r(i,t,e[t]);return i},X=(i,e,t)=>_r(i,typeof e!="symbol"?e+"":e,t);let Hm=class Wa extends Hp{constructor(e){var t;super(e),X(this,"protocol",Ta),X(this,"version",qa),X(this,"name",dr),X(this,"relayUrl"),X(this,"projectId"),X(this,"customStoragePrefix"),X(this,"events",new _t.EventEmitter),X(this,"logger"),X(this,"heartbeat"),X(this,"relayer"),X(this,"crypto"),X(this,"storage"),X(this,"history"),X(this,"expirer"),X(this,"pairing"),X(this,"verify"),X(this,"echoClient"),X(this,"linkModeSupportedApps"),X(this,"eventClient"),X(this,"initialized",!1),X(this,"logChunkController"),X(this,"on",(a,c)=>this.events.on(a,c)),X(this,"once",(a,c)=>this.events.once(a,c)),X(this,"off",(a,c)=>this.events.off(a,c)),X(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),X(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ee.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(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?.projectId,this.relayUrl=e?.relayUrl||Da,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=bs({level:typeof e?.logger=="string"&&e.logger?e.logger:ld.logger,name:dr}),{logger:n,chunkLoggerController:o}=yc({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride: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=Pe(n,this.name),this.heartbeat=new wc,this.crypto=new wf(this,this.logger,e?.keychain),this.history=new Am(this,this.logger),this.expirer=new Nm(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new zp(Eo(Eo({},ud),e?.storageOptions)),this.relayer=new Hf({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new $m(this,this.logger),this.verify=new qm(this,this.logger,this.storage),this.echoClient=new km(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Bm(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Wa(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(Pd,s),t}get context(){return ke(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(Xn,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(Xn)||[],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 process<"u"&&hd.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const Fm=Hm,Ja="wc",Qa=2,Ya="client",Vr=`${Ja}@${Qa}:${Ya}:`,Gs={name:Ya,logger:"error"},Io="WALLETCONNECT_DEEPLINK_CHOICE",Gm="proposal",_o="Proposal expired",Wm="session",Ht=N.SEVEN_DAYS,Jm="engine",le={wc_sessionPropose:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1104},res:{ttl:N.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1106},res:{ttl:N.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1112},res:{ttl:N.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1114},res:{ttl:N.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:N.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:N.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1119}}},Ws={min:N.FIVE_MINUTES,max:N.SEVEN_DAYS},et={idle:"IDLE",active:"ACTIVE"},Po={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Qm="request",Ym=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Zm="wc",Xm="auth",ey="authKeys",ty="pairingTopics",iy="requests",As=`${Zm}@${1.5}:${Xm}:`,ps=`${As}:PUB_KEY`;var sy=Object.defineProperty,ry=Object.defineProperties,ny=Object.getOwnPropertyDescriptors,$o=Object.getOwnPropertySymbols,oy=Object.prototype.hasOwnProperty,ay=Object.prototype.propertyIsEnumerable,Pr=(i,e,t)=>e in i?sy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Y=(i,e)=>{for(var t in e||(e={}))oy.call(e,t)&&Pr(i,t,e[t]);if($o)for(var t of $o(e))ay.call(e,t)&&Pr(i,t,e[t]);return i},Ie=(i,e)=>ry(i,ny(e)),E=(i,e,t)=>Pr(i,typeof e!="symbol"?e+"":e,t);class cy extends cd{constructor(e){super(e),E(this,"name",Jm),E(this,"events",new Nr),E(this,"initialized",!1),E(this,"requestQueue",{state:et.idle,queue:[]}),E(this,"sessionRequestQueue",{state:et.idle,queue:[]}),E(this,"requestQueueDelay",N.ONE_SECOND),E(this,"expectedPairingMethodMap",new Map),E(this,"recentlyDeletedMap",new Map),E(this,"recentlyDeletedLimit",200),E(this,"relayMessageCache",[]),E(this,"pendingSessions",new Map),E(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(le)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay)))}),E(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=Ie(Y({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=Lu(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h}=s;let l=r,u,p=!1;try{if(l){const P=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."),p=P.active}}catch(P){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),P}if(!l||!p){const{topic:P,uri:S}=await this.client.core.pairing.create();l=P,u=S}if(!l){const{message:P}=C("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(P)}const d=await this.client.core.crypto.generateKeyPair(),g=le.wc_sessionPropose.req.ttl||N.FIVE_MINUTES,m=ae(g),f=Ie(Y(Y({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:ja}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:ft()}),w=W("session_connect",f.id),{reject:y,resolve:b,done:_}=At(g,_o),x=({id:P})=>{P===f.id&&(this.client.events.off("proposal_expire",x),this.pendingSessions.delete(f.id),this.events.emit(w,{error:{message:_o,code:0}}))};return this.client.events.on("proposal_expire",x),this.events.once(w,({error:P,session:S})=>{this.client.events.off("proposal_expire",x),P?y(P):S&&b(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:u,approval:_}}),E(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}}),E(this,"approve",async t=>{var s,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(s=t?.id)==null?void 0:s.toString(),trace:[He.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(v){throw o.setError(St.no_internet_connection),v}try{await this.isValidProposalId(t?.id)}catch(v){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),o.setError(St.proposal_not_found),v}try{await this.isValidApprove(t)}catch(v){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(St.session_approve_namespace_validation_failure),v}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=t,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:m,requiredNamespaces:f,optionalNamespaces:w}=d;let y=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});y||(y=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:He.session_approve_started,properties:{topic:g,trace:[He.session_approve_started,He.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),_=m.publicKey,x=await this.client.core.crypto.generateSharedKey(b,_),P=Y(Y(Y({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:b,metadata:this.client.metadata},expiry:ae(Ht)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),S=ee.relay;y.addTrace(He.subscribing_session_topic);try{await this.client.core.relayer.subscribe(x,{transportType:S})}catch(v){throw y.setError(St.subscribe_session_topic_failure),v}y.addTrace(He.subscribe_session_topic_success);const R=Ie(Y({},P),{topic:x,requiredNamespaces:f,optionalNamespaces:w,pairingTopic:g,acknowledged:!1,self:P.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:b,transportType:ee.relay});await this.client.session.set(x,R),y.addTrace(He.store_session);try{y.addTrace(He.publishing_session_settle),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:P,throwOnFailedPublish:!0}).catch(v=>{throw y?.setError(St.session_settle_publish_failure),v}),y.addTrace(He.session_settle_publish_success),y.addTrace(He.publishing_session_approve),await this.sendResult({id:a,topic:g,result:{relay:{protocol:c??"irn"},responderPublicKey:b},throwOnFailedPublish:!0}).catch(v=>{throw y?.setError(St.session_approve_publish_failure),v}),y.addTrace(He.session_approve_publish_success)}catch(v){throw this.client.logger.error(v),this.client.session.delete(x,J("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),v}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:m.metadata}),await this.client.proposal.delete(a,J("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(x,ae(Ht)),{topic:x,acknowledged:()=>Promise.resolve(this.client.session.get(x))}}),E(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:le.wc_sessionPropose.reject}),await this.client.proposal.delete(s,J("USER_DISCONNECTED")))}),E(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:s,namespaces:r}=t,{done:n,resolve:o,reject:a}=At(),c=ft(),h=ri().toString(),l=this.client.session.get(s).namespaces;return this.events.once(W("session_update",c),({error:u})=>{u?a(u):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(u=>{this.client.logger.error(u),this.client.session.update(s,{namespaces:l}),a(u)}),{acknowledged:n}}),E(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=ft(),{done:n,resolve:o,reject:a}=At();return this.events.once(W("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,ae(Ht)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),E(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:s,request:r,topic:n,expiry:o=le.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);a?.transportType===ee.relay&&await this.confirmOnlineStateOrThrow();const c=ft(),h=ri().toString(),{done:l,resolve:u,reject:p}=At(o,"Request expired. Please try again.");this.events.once(W("session_request",c),({error:w,result:y})=>{w?p(w):u(y)});const d="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:{request:Ie(Y({},r),{expiryTimestamp:ae(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(w=>p(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const m={request:Ie(Y({},r),{expiryTimestamp:ae(o)}),chainId:s},f=this.shouldSetTVF(d,m);return await Promise.all([new Promise(async w=>{await this.sendRequest(Y({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:m,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,m)})).catch(y=>p(y)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),w()}),new Promise(async w=>{var y;if(!((y=a.sessionConfig)!=null&&y.disableDeepLink)){const b=await Xc(this.client.core.storage,Io);await Qc({id:c,topic:n,wcDeepLink:b})}w()}),l()]).then(w=>w[2])}),E(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===ee.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);ht(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):it(r)&&await this.sendError({id:n,topic:s,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),E(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=ft(),n=ri().toString(),{done:o,resolve:a,reject:c}=At();this.events.once(W("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}))}),E(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:s,event:r,chainId:n}=t,o=ri().toString(),a=ft();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),E(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:J("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)}}),E(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(s=>Ku(s,t)))),E(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),E(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?ee.link_mode:ee.relay;o===ee.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:p,exp:d,nbf:g,methods:m=[],expiry:f}=t,w=[...t.resources||[]],{topic:y,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:y,uri:b}});const _=await this.client.core.crypto.generateKeyPair(),x=cs(_);if(await Promise.all([this.client.auth.authKeys.set(ps,{responseTopic:x,publicKey:_}),this.client.auth.pairingTopics.set(x,{topic:x,pairingTopic:y})]),await this.client.core.relayer.subscribe(x,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${y}`),m.length>0){const{namespace:$}=ci(a[0]);let M=Hh($,"request",m);as(w)&&(M=Gh(M,w.pop())),w.push(M)}const P=f&&f>le.wc_sessionAuthenticate.req.ttl?f:le.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:p??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:d,nbf:g,resources:w},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:ae(P)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},v={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:y,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:ae(le.wc_sessionPropose.req.ttl),id:ft()},{done:k,resolve:q,reject:D}=At(P,"Request expired"),U=ft(),I=W("session_connect",v.id),A=W("session_request",U),O=async({error:$,session:M})=>{this.events.off(A,T),$?D($):M&&q({session:M})},T=async $=>{var M,L,B;if(await this.deletePendingAuthRequest(U,{message:"fulfilled",code:0}),$.error){const oe=J("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return $.error.code===oe.code?void 0:(this.events.off(I,O),D($.error.message))}await this.deleteProposal(v.id),this.events.off(I,O);const{cacaos:Z,responder:G}=$.result,ie=[],ce=[];for(const oe of Z){await dn({cacao:oe,projectId:this.client.core.projectId})||(this.client.logger.error(oe,"Signature verification failed"),D(J("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:$t}=oe,ot=as($t.resources),Ye=[ir($t.iss)],at=fs($t.iss);if(ot){const Bt=gn(ot),Wi=fn(ot);ie.push(...Bt),Ye.push(...Wi)}for(const Bt of Ye)ce.push(`${Bt}:${at}`)}const ve=await this.client.core.crypto.generateSharedKey(_,G.publicKey);let ne;ie.length>0&&(ne={topic:ve,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:G,controller:G.publicKey,expiry:ae(Ht),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:y,namespaces:Ln([...new Set(ie)],[...new Set(ce)]),transportType:o},await this.client.core.relayer.subscribe(ve,{transportType:o}),await this.client.session.set(ve,ne),y&&await this.client.core.pairing.updateMetadata({topic:y,metadata:G.metadata}),ne=this.client.session.get(ve)),(M=this.client.metadata.redirect)!=null&&M.linkMode&&(L=G.metadata.redirect)!=null&&L.linkMode&&(B=G.metadata.redirect)!=null&&B.universal&&s&&(this.client.core.addLinkModeSupportedApp(G.metadata.redirect.universal),this.client.session.update(ve,{transportType:ee.link_mode})),q({auths:Z,session:ne})};this.events.once(I,O),this.events.once(A,T);let j;try{if(n){const $=Tt("wc_sessionAuthenticate",S,U);this.client.core.history.set(y,$);const M=await this.client.core.crypto.encode("",$,{type:Fi,encoding:bt});j=Xi(s,y,M)}else await Promise.all([this.sendRequest({topic:y,method:"wc_sessionAuthenticate",params:S,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:U}),this.sendRequest({topic:y,method:"wc_sessionPropose",params:v,expiry:le.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:v.id})])}catch($){throw this.events.off(I,O),this.events.off(A,T),$}return await this.setProposal(v.id,v),await this.setAuthRequest(U,{request:Ie(Y({},S),{verifyContext:{}}),pairingTopic:y,transportType:o}),{uri:j??b,response:k}}),E(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[Ot.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(Si.no_internet_connection),f}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(Si.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||ee.relay;a===ee.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=cs(c),u={type:gt,receiverPublicKey:c,senderPublicKey:h},p=[],d=[];for(const f of r){if(!await dn({cacao:f,projectId:this.client.core.projectId})){n.setError(Si.invalid_cacao);const x=J("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:x,encodeOpts:u}),new Error(x.message)}n.addTrace(Ot.cacaos_verified);const{p:w}=f,y=as(w.resources),b=[ir(w.iss)],_=fs(w.iss);if(y){const x=gn(y),P=fn(y);p.push(...x),b.push(...P)}for(const x of b)d.push(`${x}:${_}`)}const g=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Ot.create_authenticated_session_topic);let m;if(p?.length>0){m={topic:g,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ae(Ht),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Ln([...new Set(p)],[...new Set(d)]),transportType:a},n.addTrace(Ot.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(f){throw n.setError(Si.subscribe_authenticated_session_topic_failure),f}n.addTrace(Ot.subscribe_authenticated_session_topic_success),await this.client.session.set(g,m),n.addTrace(Ot.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Ot.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:s,result:{cacaos:r,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(f){throw n.setError(Si.authenticated_session_approve_publish_failure),f}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:m}}),E(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===ee.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=cs(o),h={type:gt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:s,topic:c,error:r,encodeOpts:h,rpcOpts:le.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,J("USER_DISCONNECTED"))}),E(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return oa(s,r)}),E(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)}),E(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)}}),E(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,J("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(Io).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,J("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=et.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),E(this,"deleteProposal",async(t,s)=>{if(s)try{const r=this.client.proposal.get(t);this.client.core.eventClient.getEvent({topic:r.pairingTopic})?.setError(St.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,J("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),E(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=et.idle,this.client.events.emit("session_request_expire",{id:t}))}),E(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)])}),E(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}))}),E(this,"setProposal",async(t,s)=>{this.client.core.expirer.set(t,ae(le.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),E(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=ee.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})}),E(this,"setPendingSessionRequest",async t=>{const{id:s,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ae(le.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})}),E(this,"sendRequest",async t=>{const{topic:s,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:u}=t,p=Tt(r,n,c);let d;const g=!!l;try{const w=g?bt:We;d=await this.client.core.crypto.encode(s,p,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),w}let m;if(Ym.includes(r)){const w=st(JSON.stringify(p)),y=st(d);m=await this.client.core.verify.register({id:y,decryptedId:w})}const f=le[r].req;if(f.attestation=m,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(s,p),g){const w=Xi(l,s,d);await global.Linking.openURL(w,this.client.name)}else{const w=le[r].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=Ie(Y({},u),{correlationId:p.id}),h?(w.internal=Ie(Y({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,d,w)):this.client.core.relayer.publish(s,d,w).catch(y=>this.client.logger.error(y))}return p.id}),E(this,"sendResult",async t=>{const{id:s,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=vs(s,n);let l;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const g=u?bt:We;l=await this.client.core.crypto.encode(r,h,Ie(Y({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let p,d;try{p=await this.client.core.history.get(r,s);const g=p.request;try{this.shouldSetTVF(g.method,g.params)&&(d=this.getTVFParams(s,g.params,n))}catch(m){this.client.logger.warn("sendResult() -> getTVFParams() failed",m)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),g}if(u){const g=Xi(c,r,l);await global.Linking.openURL(g,this.client.name)}else{const g=p.request.method,m=le[g].res;m.tvf=Ie(Y({},d),{correlationId:s}),o?(m.internal=Ie(Y({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,m)):this.client.core.relayer.publish(r,l,m).catch(f=>this.client.logger.error(f))}await this.client.core.history.resolve(h)}),E(this,"sendError",async t=>{const{id:s,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=Ko(s,n);let l;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=u?bt:We;l=await this.client.core.crypto.encode(r,h,Ie(Y({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),d}let p;try{p=await this.client.core.history.get(r,s)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${r}, ${s}) failed`),d}if(u){const d=Xi(c,r,l);await global.Linking.openURL(d,this.client.name)}else{const d=p.request.method,g=a||le[d].res;this.client.core.relayer.publish(r,l,g)}await this.client.core.history.resolve(h)}),E(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;wt(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=>{wt(r.expiryTimestamp)&&s.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...s.map(r=>this.deleteProposal(r))])}),E(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),E(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),E(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===et.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=et.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=et.idle}),E(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}`)}}),E(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}`)}}),E(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)}),E(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)}),E(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?.setError(lt.proposal_listener_not_found)),this.isValidConnect(Y({},r.params));const l=a.expiryTimestamp||ae(le.wc_sessionPropose.req.ttl),u=Y({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,u);const p=await this.getVerifyContext({attestationId:n,hash:st(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});h?.addTrace(tt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:p})}catch(h){await this.sendError({id:c,topic:s,error:h,rpcOpts:le.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),E(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(ht(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 u=await this.client.core.relayer.subscribe(l,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(it(s)){await this.client.proposal.delete(n,J("USER_DISCONNECTED"));const o=W("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})}}),E(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:u,sessionConfig:p}=s.params,d=[...this.pendingSessions.values()].find(f=>f.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const g=this.client.proposal.get(d.proposalId),m=Ie(Y(Y(Y({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),{transportType:ee.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(W("session_connect",d.proposalId),{session:m}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(m),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)}}),E(this,"onSessionSettleResponse",async(t,s)=>{const{id:r}=s;ht(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(W("session_approve",r),{})):it(s)&&(await this.client.session.delete(t,J("USER_DISCONNECTED")),this.events.emit(W("session_approve",r),{error:s.error}))}),E(this,"onSessionUpdateRequest",async(t,s)=>{const{params:r,id:n}=s;try{const o=`${t}_session_update`,a=Pi.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:J("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Y({topic:t},r));try{Pi.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 Pi.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)}}),E(this,"isRequestOutOfSync",(t,s)=>s.toString().slice(0,-3)<t.toString().slice(0,-3)),E(this,"onSessionUpdateResponse",(t,s)=>{const{id:r}=s,n=W("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ht(s)?this.events.emit(W("session_update",r),{}):it(s)&&this.events.emit(W("session_update",r),{error:s.error})}),E(this,"onSessionExtendRequest",async(t,s)=>{const{id:r}=s;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ae(Ht)),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)}}),E(this,"onSessionExtendResponse",(t,s)=>{const{id:r}=s,n=W("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ht(s)?this.events.emit(W("session_extend",r),{}):it(s)&&this.events.emit(W("session_extend",r),{error:s.error})}),E(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)}}),E(this,"onSessionPingResponse",(t,s)=>{const{id:r}=s,n=W("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);ht(s)?this.events.emit(W("session_ping",r),{}):it(s)&&this.events.emit(W("session_ping",r),{error:s.error})},500)}),E(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:J("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),E(this,"onSessionRequest",async t=>{var s,r,n;const{topic:o,payload:a,attestation:c,encryptedId:h,transportType:l}=t,{id:u,params:p}=a;try{await this.isValidRequest(Y({topic:o},p));const d=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:st(JSON.stringify(Tt("wc_sessionRequest",p,u))),encryptedId:h,metadata:d.peer.metadata,transportType:l}),m={id:u,topic:o,params:p,verifyContext:g};await this.setPendingSessionRequest(m),l===ee.link_mode&&(s=d.peer.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp((r=d.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(d){await this.sendError({id:u,topic:o,error:d}),this.client.logger.error(d)}}),E(this,"onSessionRequestResponse",(t,s)=>{const{id:r}=s,n=W("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ht(s)?this.events.emit(W("session_request",r),{result:s.result}):it(s)&&this.events.emit(W("session_request",r),{error:s.error})}),E(this,"onSessionEventRequest",async(t,s)=>{const{id:r,params:n}=s;try{const o=`${t}_session_event_${n.event.name}`,a=Pi.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Y({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),Pi.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),E(this,"onSessionAuthenticateResponse",(t,s)=>{const{id:r}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:s}),ht(s)?this.events.emit(W("session_request",r),{result:s.result}):it(s)&&this.events.emit(W("session_request",r),{error:s.error})}),E(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:u}=n.params,p=await this.getVerifyContext({attestationId:o,hash:st(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),d={requester:h,pairingTopic:r,id:n.id,authPayload:l,verifyContext:p,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:d,pairingTopic:r,transportType:c}),c===ee.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:p})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(n.params.requester.metadata,c),d={type:gt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:d,rpcOpts:le.wc_sessionAuthenticate.autoReject,appLink:p})}}),E(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),E(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=et.idle,this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay))}),E(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=W("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(W("session_request",n.request.id),{error:s})})}),E(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===et.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=et.active,this.emitSessionRequest(t)}catch(s){this.client.logger.error(s)}}),E(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),E(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:Tt("wc_sessionPropose",Ie(Y({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id)})}),E(this,"isValidConnect",async t=>{if(!Oe(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),!tp(c)){const{message:h}=C("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!we(r)&&It(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)&&It(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)}`)}}),E(this,"validateNamespaces",(t,s)=>{const r=ep(t,"connect()",s);if(r)throw new Error(r.message)}),E(this,"isValidApprove",async t=>{if(!Oe(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=Ls(r,"approve()");if(h)throw new Error(h.message);const l=Kn(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!re(n,!0)){const{message:u}=C("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(p=>u.has(p)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),E(this,"isValidReject",async t=>{if(!Oe(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),!sp(r)){const{message:n}=C("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),E(this,"isValidSessionSettleRequest",t=>{if(!Oe(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(!Ra(s)){const{message:h}=C("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=Wu(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Ls(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(wt(o)){const{message:h}=C("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),E(this,"isValidUpdate",async t=>{if(!Oe(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=Ls(r,"update()");if(o)throw new Error(o.message);const a=Kn(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),E(this,"isValidExtend",async t=>{if(!Oe(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)}),E(this,"isValidRequest",async t=>{if(!Oe(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(!zn(a,n)){const{message:c}=C("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!rp(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&&!up(o,Ws)){const{message:c}=C("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Ws.min} and ${Ws.max}`);throw new Error(c)}}),E(this,"isValidRespond",async t=>{var s;if(!Oe(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?.response)!=null&&s.id&&this.cleanupAfterResponse(t),o}if(!np(n)){const{message:o}=C("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),E(this,"isValidPing",async t=>{if(!Oe(t)){const{message:r}=C("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),E(this,"isValidEmit",async t=>{if(!Oe(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(!zn(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(!cp(o,n,r.name)){const{message:a}=C("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),E(this,"isValidDisconnect",async t=>{if(!Oe(t)){const{message:r}=C("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),E(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(!re(r,!1))throw new Error("uri is required parameter");if(!re(n,!1))throw new Error("domain is required parameter");if(!re(o,!1))throw new Error("nonce is required parameter");if([...new Set(s.map(c=>ci(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ci(s[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),E(this,"getVerifyContext",async t=>{const{attestationId:s,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||qi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ee.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}),E(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)}})}),E(this,"getPendingAuthRequest",t=>{const s=this.client.auth.requests.get(t);return typeof s=="object"?s:void 0}),E(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)}}}),E(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)}}),E(this,"isLinkModeEnabled",(t,s)=>{var r,n,o,a,c,h,l,u,p;return!t||s!==ee.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?.redirect)==null?void 0:l.universal)!==void 0&&((u=t?.redirect)==null?void 0:u.universal)!==""&&((p=t?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),E(this,"getAppLinkIfEnabled",(t,s)=>{var r;return this.isLinkModeEnabled(t,s)?(r=t?.redirect)==null?void 0:r.universal:void 0}),E(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const s=rn(t,"topic")||"",r=decodeURIComponent(rn(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:ee.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),E(this,"registerLinkModeListeners",async()=>{var t;if(Dr()||Pt()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const s=global==null?void 0: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)}}}),E(this,"shouldSetTVF",(t,s)=>{if(!s||t!=="wc_sessionRequest")return!1;const{request:r}=s;return Object.keys(Po).includes(r.method)}),E(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return Ie(Y({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{}}),E(this,"isValidContractData",t=>{var s;if(!t)return!1;try{const r=t?.data||((s=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}),E(this,"extractTxHashesFromResult",(t,s)=>{try{const r=Po[t];if(typeof s=="string")return[s];const n=s[r.key];if(Je(n))return t==="solana_signAllTransactions"?n.map(o=>Nh(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(ps)?this.client.auth.authKeys.get(ps):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===ee.link_mode?bt:We});qr(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:st(s)})):jr(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(Le.expired,async e=>{const{topic:t,id:s}=Yo(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(Nt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Nt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!re(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(wt(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=C("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!re(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(wt(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(re(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(!ip(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(wt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=C("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class hy extends Ut{constructor(e,t){super(e,t,Gm,Vr),this.core=e,this.logger=t}}let ly=class extends Ut{constructor(e,t){super(e,t,Wm,Vr),this.core=e,this.logger=t}};class uy extends Ut{constructor(e,t){super(e,t,Qm,Vr,s=>s.id),this.core=e,this.logger=t}}class py extends Ut{constructor(e,t){super(e,t,ey,As,()=>ps),this.core=e,this.logger=t}}class dy extends Ut{constructor(e,t){super(e,t,ty,As),this.core=e,this.logger=t}}class gy extends Ut{constructor(e,t){super(e,t,iy,As,s=>s.id),this.core=e,this.logger=t}}var fy=Object.defineProperty,my=(i,e,t)=>e in i?fy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Js=(i,e,t)=>my(i,typeof e!="symbol"?e+"":e,t);class yy{constructor(e,t){this.core=e,this.logger=t,Js(this,"authKeys"),Js(this,"pairingTopics"),Js(this,"requests"),this.authKeys=new py(this.core,this.logger),this.pairingTopics=new dy(this.core,this.logger),this.requests=new gy(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var wy=Object.defineProperty,by=(i,e,t)=>e in i?wy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,K=(i,e,t)=>by(i,typeof e!="symbol"?e+"":e,t);let vy=class Za extends ad{constructor(e){super(e),K(this,"protocol",Ja),K(this,"version",Qa),K(this,"name",Gs.name),K(this,"metadata"),K(this,"core"),K(this,"logger"),K(this,"events",new _t.EventEmitter),K(this,"engine"),K(this,"session"),K(this,"proposal"),K(this,"pendingRequest"),K(this,"auth"),K(this,"signConfig"),K(this,"on",(s,r)=>this.events.on(s,r)),K(this,"once",(s,r)=>this.events.once(s,r)),K(this,"off",(s,r)=>this.events.off(s,r)),K(this,"removeListener",(s,r)=>this.events.removeListener(s,r)),K(this,"removeAllListeners",s=>this.events.removeAllListeners(s)),K(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"pair",async s=>{try{return await this.engine.pair(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"approve",async s=>{try{return await this.engine.approve(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"reject",async s=>{try{return await this.engine.reject(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"update",async s=>{try{return await this.engine.update(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"extend",async s=>{try{return await this.engine.extend(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"request",async s=>{try{return await this.engine.request(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"respond",async s=>{try{return await this.engine.respond(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"ping",async s=>{try{return await this.engine.ping(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"emit",async s=>{try{return await this.engine.emit(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"find",s=>{try{return this.engine.find(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}}),K(this,"authenticate",async(s,r)=>{try{return await this.engine.authenticate(s,r)}catch(n){throw this.logger.error(n.message),n}}),K(this,"formatAuthMessage",s=>{try{return this.engine.formatAuthMessage(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"approveSessionAuthenticate",async s=>{try{return await this.engine.approveSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"rejectSessionAuthenticate",async s=>{try{return await this.engine.rejectSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),this.name=e?.name||Gs.name,this.metadata=Vc(e?.metadata),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Tr(bs({level:e?.logger||Gs.logger}));this.core=e?.core||new Fm(e),this.logger=Pe(t,this.name),this.session=new ly(this.core,this.logger),this.proposal=new hy(this.core,this.logger),this.pendingRequest=new uy(this.core,this.logger),this.engine=new cy(this),this.auth=new yy(this.core,this.logger)}static async init(e){const t=new Za(e);return await t.initialize(),t}get context(){return ke(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},N.toMiliseconds(N.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const So="error",Ey="wss://relay.walletconnect.org",Iy="wc",_y="universal_provider",is=`${Iy}@2:${_y}:`,Xa="https://rpc.walletconnect.org/v1/",si="generic",Py=`${Xa}bundler`,Ke={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function $y(){}function Hr(i){return i==null||typeof i!="object"&&typeof i!="function"}function Fr(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Sy(i){if(Hr(i))return i;if(Array.isArray(i)||Fr(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 Oo(i){return typeof i=="object"&&i!==null}function ec(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function tc(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Oy="[object RegExp]",ic="[object String]",sc="[object Number]",rc="[object Boolean]",nc="[object Arguments]",Ay="[object Symbol]",xy="[object Date]",Cy="[object Map]",Ny="[object Set]",Ry="[object Array]",Ty="[object ArrayBuffer]",qy="[object Object]",jy="[object DataView]",Dy="[object Uint8Array]",ky="[object Uint8ClampedArray]",My="[object Uint16Array]",Uy="[object Uint32Array]",Ly="[object Int8Array]",By="[object Int16Array]",zy="[object Int32Array]",Ky="[object Float32Array]",Vy="[object Float64Array]";function Hy(i,e){return ai(i,void 0,i,new Map,e)}function ai(i,e,t,s=new Map,r=void 0){const n=r?.(i,e,t,s);if(n!=null)return n;if(Hr(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]=ai(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,ai(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(ai(a,void 0,t,s,r));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(i))return i.subarray();if(Fr(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=ai(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),Rt(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),Rt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),Rt(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,Rt(o,i,t,s,r),o}if(typeof i=="object"&&Fy(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),Rt(o,i,t,s,r),o}return i}function Rt(i,e,t=i,s,r){const n=[...Object.keys(e),...ec(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=ai(e[a],a,t,s,r))}}function Fy(i){switch(tc(i)){case nc:case Ry:case Ty:case jy:case rc:case xy:case Ky:case Vy:case Ly:case By:case zy:case Cy:case sc:case qy:case Oy:case Ny:case ic:case Ay:case Dy:case ky:case My:case Uy:return!0;default:return!1}}function Gy(i,e){return Hy(i,(t,s,r,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case sc:case ic:case rc:{const o=new i.constructor(i?.valueOf());return Rt(o,i),o}case nc:{const o={};return Rt(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function Ao(i){return Gy(i)}function xo(i){return i!==null&&typeof i=="object"&&tc(i)==="[object Arguments]"}function Wy(i){return Fr(i)}function Jy(i){if(typeof i!="object"||i==null)return!1;if(Object.getPrototypeOf(i)===null)return!0;if(Object.prototype.toString.call(i)!=="[object Object]"){const t=i[Symbol.toStringTag];return t==null||!Object.getOwnPropertyDescriptor(i,Symbol.toStringTag)?.writable?!1:i.toString()===`[object ${t}]`}let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function Qy(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=$r(r,o,s,new Map)}return r}function $r(i,e,t,s){if(Hr(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(s.has(e))return Sy(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),...ec(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(xo(a)&&(a={...a}),xo(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=Ao(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],u=Reflect.ownKeys(c);for(let p=0;p<u.length;p++){const d=u[p];l[d]=c[d]}c=l}else c=[];const h=t(c,a,o,i,e,s);h!=null?i[o]=h:Array.isArray(a)||Oo(c)&&Oo(a)?i[o]=$r(c,a,t,s):c==null&&Jy(a)?i[o]=$r({},a,t,s):c==null&&Wy(a)?i[o]=Ao(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Yy(i,...e){return Qy(i,...e,$y)}var Zy=Object.defineProperty,Xy=Object.defineProperties,ew=Object.getOwnPropertyDescriptors,Co=Object.getOwnPropertySymbols,tw=Object.prototype.hasOwnProperty,iw=Object.prototype.propertyIsEnumerable,No=(i,e,t)=>e in i?Zy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ss=(i,e)=>{for(var t in e||(e={}))tw.call(e,t)&&No(i,t,e[t]);if(Co)for(var t of Co(e))iw.call(e,t)&&No(i,t,e[t]);return i},sw=(i,e)=>Xy(i,ew(e));function De(i,e,t){var s;const r=ci(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${Xa}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Lt(i){return i.includes(":")?i.split(":")[1]:i}function oc(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function rw(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 rs(i={},e={}){const t=Ro(i),s=Ro(e);return Yy(t,s)}function Ro(i){var e,t,s,r,n;const o={};if(!It(i))return o;for(const[a,c]of Object.entries(i)){const h=Ss(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],p=c.rpcMap||{},d=oi(a);o[d]=sw(ss(ss({},o[d]),c),{chains:rt(h,(e=o[d])==null?void 0:e.chains),methods:rt(l,(t=o[d])==null?void 0:t.methods),events:rt(u,(s=o[d])==null?void 0:s.events)}),(It(p)||It(((r=o[d])==null?void 0:r.rpcMap)||{}))&&(o[d].rpcMap=ss(ss({},p),(n=o[d])==null?void 0:n.rpcMap))}return o}function To(i){return i.includes(":")?i.split(":")[2]:i}function qo(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=Ss(t)?[t]:s.chains?s.chains:oc(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Qs(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 ac={},F=i=>ac[i],Ys=(i,e)=>{ac[i]=e};var nw=Object.defineProperty,ow=(i,e,t)=>e in i?nw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ft=(i,e,t)=>ow(i,typeof e!="symbol"?e+"":e,t);class aw{constructor(e){Ft(this,"name","polkadot"),Ft(this,"client"),Ft(this,"httpProviders"),Ft(this,"events"),Ft(this,"namespace"),Ft(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Lt(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var cw=Object.defineProperty,hw=Object.defineProperties,lw=Object.getOwnPropertyDescriptors,jo=Object.getOwnPropertySymbols,uw=Object.prototype.hasOwnProperty,pw=Object.prototype.propertyIsEnumerable,Sr=(i,e,t)=>e in i?cw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Do=(i,e)=>{for(var t in e||(e={}))uw.call(e,t)&&Sr(i,t,e[t]);if(jo)for(var t of jo(e))pw.call(e,t)&&Sr(i,t,e[t]);return i},ko=(i,e)=>hw(i,lw(e)),Gt=(i,e,t)=>Sr(i,typeof e!="symbol"?e+"":e,t);class dw{constructor(e){Gt(this,"name","eip155"),Gt(this,"client"),Gt(this,"chainId"),Gt(this,"namespace"),Gt(this,"httpProviders"),Gt(this,"events"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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||De(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("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(Lt(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),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[h])return u?.[h];const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ko(Do({},l.sessionProperties||{}),{capabilities:ko(Do({},u||{}),{[h]:p})})})}catch(d){console.warn("Failed to update session with capabilities",d)}return p}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(Tt("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`${Py}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var gw=Object.defineProperty,fw=(i,e,t)=>e in i?gw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wt=(i,e,t)=>fw(i,typeof e!="symbol"?e+"":e,t);class mw{constructor(e){Wt(this,"name","solana"),Wt(this,"client"),Wt(this,"httpProviders"),Wt(this,"events"),Wt(this,"namespace"),Wt(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Lt(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var yw=Object.defineProperty,ww=(i,e,t)=>e in i?yw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Jt=(i,e,t)=>ww(i,typeof e!="symbol"?e+"":e,t);class bw{constructor(e){Jt(this,"name","cosmos"),Jt(this,"client"),Jt(this,"httpProviders"),Jt(this,"events"),Jt(this,"namespace"),Jt(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Lt(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var vw=Object.defineProperty,Ew=(i,e,t)=>e in i?vw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qt=(i,e,t)=>Ew(i,typeof e!="symbol"?e+"":e,t);class Iw{constructor(e){Qt(this,"name","algorand"),Qt(this,"client"),Qt(this,"httpProviders"),Qt(this,"events"),Qt(this,"namespace"),Qt(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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||De(`${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(Ke.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||De(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new ze(new Qe(s,F("disableProviderPing")))}}var _w=Object.defineProperty,Pw=(i,e,t)=>e in i?_w(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Yt=(i,e,t)=>Pw(i,typeof e!="symbol"?e+"":e,t);class $w{constructor(e){Yt(this,"name","cip34"),Yt(this,"client"),Yt(this,"httpProviders"),Yt(this,"events"),Yt(this,"namespace"),Yt(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Lt(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 ze(new Qe(s,F("disableProviderPing")))}}var Sw=Object.defineProperty,Ow=(i,e,t)=>e in i?Sw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Zt=(i,e,t)=>Ow(i,typeof e!="symbol"?e+"":e,t);class Aw{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=F("events"),this.client=F("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(Ke.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=Lt(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var xw=Object.defineProperty,Cw=(i,e,t)=>e in i?xw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xt=(i,e,t)=>Cw(i,typeof e!="symbol"?e+"":e,t);class Nw{constructor(e){Xt(this,"name","multiversx"),Xt(this,"client"),Xt(this,"httpProviders"),Xt(this,"events"),Xt(this,"namespace"),Xt(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=Lt(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var Rw=Object.defineProperty,Tw=(i,e,t)=>e in i?Rw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ei=(i,e,t)=>Tw(i,typeof e!="symbol"?e+"":e,t);class qw{constructor(e){ei(this,"name","near"),ei(this,"client"),ei(this,"httpProviders"),ei(this,"events"),ei(this,"namespace"),ei(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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||De(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(Ke.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||De(e,this.namespace);return typeof s>"u"?void 0:new ze(new Qe(s,F("disableProviderPing")))}}var jw=Object.defineProperty,Dw=(i,e,t)=>e in i?jw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ti=(i,e,t)=>Dw(i,typeof e!="symbol"?e+"":e,t);class kw{constructor(e){ti(this,"name","tezos"),ti(this,"client"),ti(this,"httpProviders"),ti(this,"events"),ti(this,"namespace"),ti(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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||De(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(Ke.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||De(e,this.namespace);return typeof s>"u"?void 0:new ze(new Qe(s))}}var Mw=Object.defineProperty,Uw=(i,e,t)=>e in i?Mw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ii=(i,e,t)=>Uw(i,typeof e!="symbol"?e+"":e,t);class Lw{constructor(e){ii(this,"name",si),ii(this,"client"),ii(this,"httpProviders"),ii(this,"events"),ii(this,"namespace"),ii(this,"chainId"),this.namespace=e.namespace,this.events=F("events"),this.client=F("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(Ke.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=ci(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new ze(new Qe(s,F("disableProviderPing")))}}var Bw=Object.defineProperty,zw=Object.defineProperties,Kw=Object.getOwnPropertyDescriptors,Mo=Object.getOwnPropertySymbols,Vw=Object.prototype.hasOwnProperty,Hw=Object.prototype.propertyIsEnumerable,Or=(i,e,t)=>e in i?Bw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ns=(i,e)=>{for(var t in e||(e={}))Vw.call(e,t)&&Or(i,t,e[t]);if(Mo)for(var t of Mo(e))Hw.call(e,t)&&Or(i,t,e[t]);return i},Zs=(i,e)=>zw(i,Kw(e)),Ue=(i,e,t)=>Or(i,typeof e!="symbol"?e+"":e,t);let Fw=class cc{constructor(e){Ue(this,"client"),Ue(this,"namespaces"),Ue(this,"optionalNamespaces"),Ue(this,"sessionProperties"),Ue(this,"scopedProperties"),Ue(this,"events",new Nr),Ue(this,"rpcProviders",{}),Ue(this,"session"),Ue(this,"providerOpts"),Ue(this,"logger"),Ue(this,"uri"),Ue(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Tr(bs({level:e?.logger||So})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new cc(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:ns({},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,vs(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:J("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=qo(this.session.namespaces);this.namespaces=rs(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=qo(r.namespaces);return this.namespaces=rs(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===si?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(Je(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 vy.init({core:this.providerOpts.core,logger:this.providerOpts.logger||So,relayUrl:this.providerOpts.relayUrl||Ey,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=>oi(t)))];Ys("client",this.client),Ys("events",this.events),Ys("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=rw(t,this.session),r=oc(s),n=rs(this.namespaces,this.optionalNamespaces),o=Zs(ns({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new dw({namespace:o});break;case"algorand":this.rpcProviders[t]=new Iw({namespace:o});break;case"solana":this.rpcProviders[t]=new mw({namespace:o});break;case"cosmos":this.rpcProviders[t]=new bw({namespace:o});break;case"polkadot":this.rpcProviders[t]=new aw({namespace:o});break;case"cip34":this.rpcProviders[t]=new $w({namespace:o});break;case"elrond":this.rpcProviders[t]=new Aw({namespace:o});break;case"multiversx":this.rpcProviders[t]=new Nw({namespace:o});break;case"near":this.rpcProviders[t]=new qw({namespace:o});break;case"tezos":this.rpcProviders[t]=new kw({namespace:o});break;default:this.rpcProviders[si]?this.rpcProviders[si].updateNamespace(o):this.rpcProviders[si]=new Lw({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&&Je(o)&&this.events.emit("accountsChanged",o.map(To))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=oi(o),h=Qs(o)!==Qs(a)?`${c}:${Qs(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=Zs(ns({},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",Zs(ns({},J("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Ke.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[si]}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=rs(t,s),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,s]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(o=>oi(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=oi(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(To);if(!Je(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(`${is}/${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(`${is}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${is}/${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(is)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const Gw=Fw,Ww="wc",Jw="ethereum_provider",Qw=`${Ww}@2:${Jw}:`,Yw="https://rpc.walletconnect.org/v1/",Ar=["eth_sendTransaction","personal_sign"],Zw=["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"],xr=["chainChanged","accountsChanged"],Xw=["chainChanged","accountsChanged","message","disconnect","connect"],eb=async()=>{const{createAppKit:i}=await uc(()=>import("./core-Bn8Mr-tS.js").then(e=>e.G),__vite__mapDeps([0,1,2,3,4,5,6,7]));return i};var tb=Object.defineProperty,ib=Object.defineProperties,sb=Object.getOwnPropertyDescriptors,Uo=Object.getOwnPropertySymbols,rb=Object.prototype.hasOwnProperty,nb=Object.prototype.propertyIsEnumerable,Cr=(i,e,t)=>e in i?tb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,xt=(i,e)=>{for(var t in e||(e={}))rb.call(e,t)&&Cr(i,t,e[t]);if(Uo)for(var t of Uo(e))nb.call(e,t)&&Cr(i,t,e[t]);return i},xi=(i,e)=>ib(i,sb(e)),Ne=(i,e,t)=>Cr(i,typeof e!="symbol"?e+"":e,t);function ws(i){return Number(i[0].split(":")[1])}function os(i){return`0x${i.toString(16)}`}function ob(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!Je(e))throw new Error("Invalid chains");const c={chains:e,methods:s||Ar,events:n||xr,rpcMap:xt({},e.length?{[ws(e)]:a[ws(e)]}:{})},h=n?.filter(d=>!xr.includes(d)),l=s?.filter(d=>!Ar.includes(d));if(!t&&!o&&!r&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=h?.length&&l?.length||!t,p={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(r!=null&&r.length?r:Zw))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Xw))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?p:void 0}}class Gr{constructor(){Ne(this,"events",new _t.EventEmitter),Ne(this,"namespace","eip155"),Ne(this,"accounts",[]),Ne(this,"signer"),Ne(this,"chainId",1),Ne(this,"modal"),Ne(this,"rpc"),Ne(this,"STORAGE_KEY",Qw),Ne(this,"on",(e,t)=>(this.events.on(e,t),this)),Ne(this,"once",(e,t)=>(this.events.once(e,t),this)),Ne(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),Ne(this,"off",(e,t)=>(this.events.off(e,t),this)),Ne(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new Gr;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}=ob(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(p=>{!p.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const u=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(xi(xt({namespaces:xt({},s&&{[this.namespace]:s})},r&&{optionalNamespaces:{[this.namespace]:r}}),{pairingTopic:e?.pairingTopic,scopedProperties:u})).then(p=>{a(p)}).catch(p=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(p.message))})});if(!n)return;const o=Zr(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:os(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?.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(xi(xt({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=r.session;if(n){const o=Zr(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:os(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",os(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",xi(xt({},J("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",os(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?.chains)!=null?t:[],n=(s=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?.methods||Ar:[],c=r.length?e?.events||xr:[],h=e?.optionalMethods||[],l=e?.optionalEvents||[],u=e?.rpcMap||this.buildRpcMap(o,e.projectId),p=e?.qrModalOptions||void 0;return{chains:r?.map(d=>this.formatChainId(d)),optionalChains:n.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:h,optionalEvents:l,rpcMap:u,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:p,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?ws(this.rpc.chains):ws(this.rpc.optionalChains),this.signer=await Gw.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 eb(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return mb}),n=r(xi(xt({},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(xi(xt({},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&&Je(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=r?.[n]||this.getRpcUrl(n)})),s&&Je(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=r?.[n]||this.getRpcUrl(n)}))}getRpcUrl(e,t){var s;return((s=this.rpc.rpcMap)==null?void 0:s[e])||`${Yw}?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?.accounts),this.setAccounts(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 zb=Gr;var ab=Object.defineProperty,cb=Object.defineProperties,hb=Object.getOwnPropertyDescriptors,Lo=Object.getOwnPropertySymbols,lb=Object.prototype.hasOwnProperty,ub=Object.prototype.propertyIsEnumerable,Bo=(i,e,t)=>e in i?ab(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,hc=(i,e)=>{for(var t in e||(e={}))lb.call(e,t)&&Bo(i,t,e[t]);if(Lo)for(var t of Lo(e))ub.call(e,t)&&Bo(i,t,e[t]);return i},pb=(i,e)=>cb(i,hb(e));function db(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 gb=i=>{const[e,t]=i.split(":");return lc({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function fb(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(gb).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(u=>{var p;return u.id===((p=i.defaultChain)==null?void 0:p.id)}),l={projectId:i.projectId,networks:c,themeMode:i.themeMode,themeVariables:db(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:pb(hc({},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 u=[...(i.mobileWallets||[]).map(g=>({id:g.id,name:g.name,links:g.links})),...(i.desktopWallets||[]).map(g=>({id:g.id,name:g.name,links:{native:g.links.native,universal:g.links.universal}}))],p=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],d=u.filter(g=>!p.includes(g.id));d.length&&(l.customWallets=d)}return l}function lc(i){return hc({formatters:void 0,fees:void 0,serializers:void 0},i)}var mb=Object.freeze({__proto__:null,convertWCMToAppKitOptions:fb,defineChain:lc});export{zb as EthereumProvider,Xw as OPTIONAL_EVENTS,Zw as OPTIONAL_METHODS,xr as REQUIRED_EVENTS,Ar as REQUIRED_METHODS,Gr as default};
|